aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSadaf Ebrahimi <sadafebrahimi@google.com>2023-09-13 23:04:09 +0000
committerAutomerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>2023-09-13 23:04:09 +0000
commit0eeb05ad047657d98f03e304ee7b6482552b39e7 (patch)
tree4655d54ddadab48b44168c42aef5b875b762630d
parent150958c7170103f3cd5435a111b5d5d8ddea6ce1 (diff)
parent9b5367ffe3dc79dc8bab2d250b00dccc1a33d331 (diff)
downloadguava-0eeb05ad047657d98f03e304ee7b6482552b39e7.tar.gz
Merge "Upgrade guava to v32.1.2" into main am: 7646f76c78 am: 9b5367ffe3
Original change: https://android-review.googlesource.com/c/platform/external/guava/+/2731599 Change-Id: I265218f3c687b89b695fa2489b26ee220a9cba12 Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
-rw-r--r--.github/workflows/ci.yml64
-rw-r--r--.github/workflows/gradle-wrapper-validation.yml13
-rw-r--r--.github/workflows/scorecard.yml72
-rw-r--r--Android.bp13
-rw-r--r--LICENSE (renamed from COPYING)0
-rw-r--r--METADATA8
-rw-r--r--README.md36
-rw-r--r--android/guava-bom/pom.xml2
-rw-r--r--android/guava-testlib/pom.xml17
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java5
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java13
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java8
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java41
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java14
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/Helpers.java103
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/Platform.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java37
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java19
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/SampleElements.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java5
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/features/package-info.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/google/package-info.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/package-info.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java3
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java2
-rw-r--r--android/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java2
-rw-r--r--android/guava-testlib/src/com/google/common/escape/testing/package-info.java2
-rw-r--r--android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java6
-rw-r--r--android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java21
-rw-r--r--android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java44
-rw-r--r--android/guava-testlib/src/com/google/common/testing/ClusterException.java11
-rw-r--r--android/guava-testlib/src/com/google/common/testing/DummyProxy.java10
-rw-r--r--android/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java41
-rw-r--r--android/guava-testlib/src/com/google/common/testing/EqualsTester.java19
-rw-r--r--android/guava-testlib/src/com/google/common/testing/EquivalenceTester.java5
-rw-r--r--android/guava-testlib/src/com/google/common/testing/FakeTicker.java5
-rw-r--r--android/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java18
-rw-r--r--android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java81
-rw-r--r--android/guava-testlib/src/com/google/common/testing/GcFinalization.java3
-rw-r--r--android/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java29
-rw-r--r--android/guava-testlib/src/com/google/common/testing/NullPointerTester.java159
-rw-r--r--android/guava-testlib/src/com/google/common/testing/Platform.java1
-rw-r--r--android/guava-testlib/src/com/google/common/testing/RelationshipTester.java3
-rw-r--r--android/guava-testlib/src/com/google/common/testing/SerializableTester.java4
-rw-r--r--android/guava-testlib/src/com/google/common/testing/SloppyTearDown.java3
-rw-r--r--android/guava-testlib/src/com/google/common/testing/TearDown.java3
-rw-r--r--android/guava-testlib/src/com/google/common/testing/TearDownAccepter.java5
-rw-r--r--android/guava-testlib/src/com/google/common/testing/TearDownStack.java3
-rw-r--r--android/guava-testlib/src/com/google/common/testing/TestLogHandler.java10
-rw-r--r--android/guava-testlib/src/com/google/common/testing/package-info.java5
-rw-r--r--android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java5
-rw-r--r--android/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java2
-rw-r--r--android/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java9
-rw-r--r--android/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java27
-rw-r--r--android/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java2
-rw-r--r--android/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java13
-rw-r--r--android/guava-testlib/test/com/google/common/collect/testing/MyTester.java38
-rw-r--r--android/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java55
-rw-r--r--android/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java32
-rw-r--r--android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java5
-rw-r--r--android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java107
-rw-r--r--android/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java17
-rw-r--r--android/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java2
-rw-r--r--android/guava-testlib/test/com/google/common/testing/FakeTickerTest.java17
-rw-r--r--android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java8
-rw-r--r--android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java86
-rw-r--r--android/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java7
-rw-r--r--android/guava-testlib/test/com/google/common/testing/TearDownStackTest.java3
-rw-r--r--android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java16
-rw-r--r--android/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java6
-rw-r--r--android/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java4
-rw-r--r--android/guava-tests/benchmark/com/google/common/collect/ConcurrentHashMultisetBenchmark.java12
-rw-r--r--android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java4
-rw-r--r--android/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java3
-rw-r--r--android/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java11
-rw-r--r--android/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java2
-rw-r--r--android/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java5
-rw-r--r--android/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java2
-rw-r--r--android/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java16
-rw-r--r--android/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java4
-rw-r--r--android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java33
-rw-r--r--android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java35
-rw-r--r--android/guava-tests/pom.xml27
-rw-r--r--android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java12
-rw-r--r--android/guava-tests/test/com/google/common/base/AndroidIncompatible.java2
-rw-r--r--android/guava-tests/test/com/google/common/base/AsciiTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/base/CaseFormatTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/base/CharMatcherTest.java19
-rw-r--r--android/guava-tests/test/com/google/common/base/CharsetsTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/base/EnumsTest.java21
-rw-r--r--android/guava-tests/test/com/google/common/base/EquivalenceTest.java17
-rw-r--r--android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java11
-rw-r--r--android/guava-tests/test/com/google/common/base/FunctionsTest.java24
-rw-r--r--android/guava-tests/test/com/google/common/base/JoinerTest.java10
-rw-r--r--android/guava-tests/test/com/google/common/base/MoreObjectsTest.java497
-rw-r--r--android/guava-tests/test/com/google/common/base/ObjectsTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/base/OptionalTest.java30
-rw-r--r--android/guava-tests/test/com/google/common/base/PreconditionsTest.java13
-rw-r--r--android/guava-tests/test/com/google/common/base/PredicatesTest.java48
-rw-r--r--android/guava-tests/test/com/google/common/base/SplitterTest.java31
-rw-r--r--android/guava-tests/test/com/google/common/base/StopwatchTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/base/StringsTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/base/SuppliersTest.java31
-rw-r--r--android/guava-tests/test/com/google/common/base/ThrowablesTest.java40
-rw-r--r--android/guava-tests/test/com/google/common/base/ToStringHelperTest.java25
-rw-r--r--android/guava-tests/test/com/google/common/base/Utf8Test.java6
-rw-r--r--android/guava-tests/test/com/google/common/base/VerifyTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/cache/AbstractCacheTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java9
-rw-r--r--android/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java28
-rw-r--r--android/guava-tests/test/com/google/common/cache/CacheBuilderTest.java1
-rw-r--r--android/guava-tests/test/com/google/common/cache/CacheExpirationTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/cache/CacheLoaderTest.java8
-rw-r--r--android/guava-tests/test/com/google/common/cache/CacheLoadingTest.java10
-rw-r--r--android/guava-tests/test/com/google/common/cache/CacheTesting.java6
-rw-r--r--android/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/cache/LocalCacheTest.java27
-rw-r--r--android/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/cache/TestingCacheLoaders.java4
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java55
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java54
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java55
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java15
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java45
-rw-r--r--android/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java45
-rw-r--r--android/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java4
-rw-r--r--android/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java34
-rw-r--r--android/guava-tests/test/com/google/common/collect/Collections2Test.java46
-rw-r--r--android/guava-tests/test/com/google/common/collect/ComparatorsTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/ComparisonChainTest.java89
-rw-r--r--android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java1
-rw-r--r--android/guava-tests/test/com/google/common/collect/FauxveridesTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java27
-rw-r--r--android/guava-tests/test/com/google/common/collect/FilteredCollectionsTestUtil.java (renamed from android/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java)86
-rw-r--r--android/guava-tests/test/com/google/common/collect/FilteredMapTest.java211
-rw-r--r--android/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java61
-rw-r--r--android/guava-tests/test/com/google/common/collect/FluentIterableTest.java8
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingListTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingMapTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java29
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java15
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingSetTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java10
-rw-r--r--android/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java1104
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java201
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableListTest.java1075
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java1336
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java50
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java1101
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java29
-rw-r--r--android/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java33
-rw-r--r--android/guava-tests/test/com/google/common/collect/LegacyComparable.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/ListsImplTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java40
-rw-r--r--android/guava-tests/test/com/google/common/collect/MapMakerTest.java1
-rw-r--r--android/guava-tests/test/com/google/common/collect/MapsCollectionTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/collect/MapsTest.java267
-rw-r--r--android/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java14
-rw-r--r--android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java14
-rw-r--r--android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/collect/MultimapsTest.java10
-rw-r--r--android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/OrderingTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/collect/QueuesTest.java11
-rw-r--r--android/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java47
-rw-r--r--android/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java40
-rw-r--r--android/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java40
-rw-r--r--android/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java33
-rw-r--r--android/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java34
-rw-r--r--android/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java42
-rw-r--r--android/guava-tests/test/com/google/common/collect/SetsTest.java14
-rw-r--r--android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java13
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java9
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java20
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java27
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java15
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java13
-rw-r--r--android/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java12
-rw-r--r--android/guava-tests/test/com/google/common/collect/TableCollectionTest.java593
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java45
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java46
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java43
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java33
-rw-r--r--android/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java33
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java52
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java74
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java53
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java52
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java32
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java54
-rw-r--r--android/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java43
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java43
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java43
-rw-r--r--android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java44
-rw-r--r--android/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/escape/EscapersTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/eventbus/DispatcherTest.java1
-rw-r--r--android/guava-tests/test/com/google/common/eventbus/EventBusTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/eventbus/PackageSanityTests.java4
-rw-r--r--android/guava-tests/test/com/google/common/eventbus/StringCatcher.java6
-rw-r--r--android/guava-tests/test/com/google/common/eventbus/SubscriberTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java45
-rw-r--r--android/guava-tests/test/com/google/common/graph/ElementOrderTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/graph/EndpointPairTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/graph/ValueGraphTest.java46
-rw-r--r--android/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/hash/BloomFilterTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/hash/HashCodeTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/hash/HashTestUtils.java2
-rw-r--r--android/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/io/BaseEncodingTest.java118
-rw-r--r--android/guava-tests/test/com/google/common/io/ByteSinkTester.java4
-rw-r--r--android/guava-tests/test/com/google/common/io/ByteSourceTest.java11
-rw-r--r--android/guava-tests/test/com/google/common/io/ByteSourceTester.java4
-rw-r--r--android/guava-tests/test/com/google/common/io/ByteStreamsTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/io/CharSinkTester.java4
-rw-r--r--android/guava-tests/test/com/google/common/io/CharSourceTester.java4
-rw-r--r--android/guava-tests/test/com/google/common/io/CloserTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java54
-rw-r--r--android/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java60
-rw-r--r--android/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java74
-rw-r--r--android/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java33
-rw-r--r--android/guava-tests/test/com/google/common/io/FilesTest.java16
-rw-r--r--android/guava-tests/test/com/google/common/io/IoTestCase.java3
-rw-r--r--android/guava-tests/test/com/google/common/io/ResourcesTest.java12
-rw-r--r--android/guava-tests/test/com/google/common/io/SourceSinkFactories.java6
-rw-r--r--android/guava-tests/test/com/google/common/io/SourceSinkTester.java2
-rw-r--r--android/guava-tests/test/com/google/common/math/BigIntegerMathTest.java50
-rw-r--r--android/guava-tests/test/com/google/common/math/DoubleMathTest.java45
-rw-r--r--android/guava-tests/test/com/google/common/math/IntMathTest.java27
-rw-r--r--android/guava-tests/test/com/google/common/math/LongMathTest.java57
-rw-r--r--android/guava-tests/test/com/google/common/math/MathPreconditionsTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/math/MathTesting.java4
-rw-r--r--android/guava-tests/test/com/google/common/math/QuantilesTest.java14
-rw-r--r--android/guava-tests/test/com/google/common/math/StatsTesting.java4
-rw-r--r--android/guava-tests/test/com/google/common/math/TestPlatform.java2
-rw-r--r--android/guava-tests/test/com/google/common/net/HostAndPortTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/net/HttpHeadersTest.java7
-rw-r--r--android/guava-tests/test/com/google/common/net/InetAddressesTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/net/PercentEscaperTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/BooleansTest.java481
-rw-r--r--android/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/BytesTest.java292
-rw-r--r--android/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/CharsTest.java483
-rw-r--r--android/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/primitives/DoublesTest.java495
-rw-r--r--android/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/FloatsTest.java465
-rw-r--r--android/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java16
-rw-r--r--android/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java11
-rw-r--r--android/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java11
-rw-r--r--android/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/IntsTest.java469
-rw-r--r--android/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/LongsTest.java548
-rw-r--r--android/guava-tests/test/com/google/common/primitives/PrimitivesTest.java39
-rw-r--r--android/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/primitives/ShortsTest.java452
-rw-r--r--android/guava-tests/test/com/google/common/primitives/SignedBytesTest.java70
-rw-r--r--android/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java113
-rw-r--r--android/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java62
-rw-r--r--android/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java133
-rw-r--r--android/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java79
-rw-r--r--android/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java152
-rw-r--r--android/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java3
-rw-r--r--android/guava-tests/test/com/google/common/reflect/ClassPathTest.java29
-rw-r--r--android/guava-tests/test/com/google/common/reflect/InvokableTest.java14
-rw-r--r--android/guava-tests/test/com/google/common/reflect/ParameterTest.java10
-rw-r--r--android/guava-tests/test/com/google/common/reflect/SubtypeTester.java5
-rw-r--r--android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java8
-rw-r--r--android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java17
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureBenchmarks.java10
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java82
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java115
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java543
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java6
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java19
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java15
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java70
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java2
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java58
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java19
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java9
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java28
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java42
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java6
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java5
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java18
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java4
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java2
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/TestThread.java10
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java9
-rw-r--r--android/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java2
-rw-r--r--android/guava/pom.xml60
-rw-r--r--android/guava/src/com/google/common/annotations/J2ktIncompatible.java31
-rw-r--r--android/guava/src/com/google/common/annotations/VisibleForTesting.java4
-rw-r--r--android/guava/src/com/google/common/annotations/package-info.java4
-rw-r--r--android/guava/src/com/google/common/base/CaseFormat.java3
-rw-r--r--android/guava/src/com/google/common/base/CharMatcher.java15
-rw-r--r--android/guava/src/com/google/common/base/Charsets.java5
-rw-r--r--android/guava/src/com/google/common/base/Converter.java58
-rw-r--r--android/guava/src/com/google/common/base/Defaults.java2
-rw-r--r--android/guava/src/com/google/common/base/Enums.java18
-rw-r--r--android/guava/src/com/google/common/base/Equivalence.java57
-rw-r--r--android/guava/src/com/google/common/base/FinalizablePhantomReference.java2
-rw-r--r--android/guava/src/com/google/common/base/FinalizableReference.java2
-rw-r--r--android/guava/src/com/google/common/base/FinalizableReferenceQueue.java2
-rw-r--r--android/guava/src/com/google/common/base/FinalizableSoftReference.java2
-rw-r--r--android/guava/src/com/google/common/base/FinalizableWeakReference.java2
-rw-r--r--android/guava/src/com/google/common/base/Function.java2
-rw-r--r--android/guava/src/com/google/common/base/FunctionalEquivalence.java2
-rw-r--r--android/guava/src/com/google/common/base/Functions.java7
-rw-r--r--android/guava/src/com/google/common/base/Java8Compatibility.java2
-rw-r--r--android/guava/src/com/google/common/base/JdkPattern.java2
-rw-r--r--android/guava/src/com/google/common/base/Joiner.java7
-rw-r--r--android/guava/src/com/google/common/base/MoreObjects.java25
-rw-r--r--android/guava/src/com/google/common/base/Optional.java6
-rw-r--r--android/guava/src/com/google/common/base/PairwiseEquivalence.java3
-rw-r--r--android/guava/src/com/google/common/base/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/base/PatternCompiler.java2
-rw-r--r--android/guava/src/com/google/common/base/Platform.java8
-rw-r--r--android/guava/src/com/google/common/base/Preconditions.java330
-rw-r--r--android/guava/src/com/google/common/base/Predicate.java2
-rw-r--r--android/guava/src/com/google/common/base/Predicates.java27
-rw-r--r--android/guava/src/com/google/common/base/SmallCharMatcher.java2
-rw-r--r--android/guava/src/com/google/common/base/Splitter.java8
-rw-r--r--android/guava/src/com/google/common/base/StandardSystemProperty.java4
-rw-r--r--android/guava/src/com/google/common/base/Stopwatch.java17
-rw-r--r--android/guava/src/com/google/common/base/Supplier.java2
-rw-r--r--android/guava/src/com/google/common/base/Suppliers.java45
-rw-r--r--android/guava/src/com/google/common/base/Throwables.java24
-rw-r--r--android/guava/src/com/google/common/base/Ticker.java3
-rw-r--r--android/guava/src/com/google/common/base/Utf8.java2
-rw-r--r--android/guava/src/com/google/common/base/package-info.java43
-rw-r--r--android/guava/src/com/google/common/cache/AbstractLoadingCache.java2
-rw-r--r--android/guava/src/com/google/common/cache/Cache.java7
-rw-r--r--android/guava/src/com/google/common/cache/CacheBuilder.java130
-rw-r--r--android/guava/src/com/google/common/cache/CacheBuilderSpec.java14
-rw-r--r--android/guava/src/com/google/common/cache/CacheLoader.java21
-rw-r--r--android/guava/src/com/google/common/cache/CacheStats.java4
-rw-r--r--android/guava/src/com/google/common/cache/ForwardingLoadingCache.java4
-rw-r--r--android/guava/src/com/google/common/cache/LoadingCache.java4
-rw-r--r--android/guava/src/com/google/common/cache/LocalCache.java206
-rw-r--r--android/guava/src/com/google/common/cache/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/cache/package-info.java15
-rw-r--r--android/guava/src/com/google/common/collect/AbstractBiMap.java34
-rw-r--r--android/guava/src/com/google/common/collect/AbstractIterator.java1
-rw-r--r--android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java1
-rw-r--r--android/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java4
-rw-r--r--android/guava/src/com/google/common/collect/AbstractNavigableMap.java4
-rw-r--r--android/guava/src/com/google/common/collect/AbstractSortedMultiset.java3
-rw-r--r--android/guava/src/com/google/common/collect/AllEqualOrdering.java3
-rw-r--r--android/guava/src/com/google/common/collect/ArrayListMultimap.java4
-rw-r--r--android/guava/src/com/google/common/collect/ArrayTable.java7
-rw-r--r--android/guava/src/com/google/common/collect/BiMap.java9
-rw-r--r--android/guava/src/com/google/common/collect/ClassToInstanceMap.java39
-rw-r--r--android/guava/src/com/google/common/collect/Collections2.java4
-rw-r--r--android/guava/src/com/google/common/collect/CompactHashMap.java10
-rw-r--r--android/guava/src/com/google/common/collect/CompactHashSet.java3
-rw-r--r--android/guava/src/com/google/common/collect/CompactLinkedHashMap.java2
-rw-r--r--android/guava/src/com/google/common/collect/CompoundOrdering.java4
-rw-r--r--android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java5
-rw-r--r--android/guava/src/com/google/common/collect/ConsumingQueueIterator.java4
-rw-r--r--android/guava/src/com/google/common/collect/ContiguousSet.java7
-rw-r--r--android/guava/src/com/google/common/collect/DescendingMultiset.java7
-rw-r--r--android/guava/src/com/google/common/collect/DiscreteDomain.java9
-rw-r--r--android/guava/src/com/google/common/collect/EmptyContiguousSet.java13
-rw-r--r--android/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java12
-rw-r--r--android/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java12
-rw-r--r--android/guava/src/com/google/common/collect/EnumBiMap.java64
-rw-r--r--android/guava/src/com/google/common/collect/EnumHashBiMap.java28
-rw-r--r--android/guava/src/com/google/common/collect/EnumMultiset.java2
-rw-r--r--android/guava/src/com/google/common/collect/EvictingQueue.java4
-rw-r--r--android/guava/src/com/google/common/collect/FluentIterable.java71
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingBlockingDeque.java2
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingDeque.java2
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingList.java5
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingMap.java8
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingMapEntry.java2
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingMultiset.java4
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingNavigableMap.java8
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingNavigableSet.java3
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingSortedMap.java4
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java2
-rw-r--r--android/guava/src/com/google/common/collect/ForwardingSortedSet.java4
-rw-r--r--android/guava/src/com/google/common/collect/GeneralRange.java13
-rw-r--r--android/guava/src/com/google/common/collect/HashBiMap.java9
-rw-r--r--android/guava/src/com/google/common/collect/HashMultimap.java4
-rw-r--r--android/guava/src/com/google/common/collect/HashMultiset.java2
-rw-r--r--android/guava/src/com/google/common/collect/IgnoreJRERequirement.java30
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableAsList.java4
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableBiMap.java15
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java11
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableCollection.java10
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableEntry.java6
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableEnumMap.java10
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableEnumSet.java15
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableList.java10
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableListMultimap.java10
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableMap.java15
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableMapEntrySet.java11
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableMapKeySet.java2
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableMapValues.java2
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableMultimap.java17
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableMultiset.java20
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableRangeMap.java12
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableRangeSet.java21
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableSet.java12
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableSetMultimap.java8
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableSortedMap.java44
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java12
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableSortedSet.java12
-rw-r--r--android/guava/src/com/google/common/collect/ImmutableTable.java12
-rw-r--r--android/guava/src/com/google/common/collect/Interner.java4
-rw-r--r--android/guava/src/com/google/common/collect/Interners.java2
-rw-r--r--android/guava/src/com/google/common/collect/Iterables.java36
-rw-r--r--android/guava/src/com/google/common/collect/Iterators.java14
-rw-r--r--android/guava/src/com/google/common/collect/LinkedHashMultimap.java10
-rw-r--r--android/guava/src/com/google/common/collect/LinkedListMultimap.java8
-rw-r--r--android/guava/src/com/google/common/collect/Lists.java27
-rw-r--r--android/guava/src/com/google/common/collect/MapMaker.java2
-rw-r--r--android/guava/src/com/google/common/collect/MapMakerInternalMap.java428
-rw-r--r--android/guava/src/com/google/common/collect/Maps.java167
-rw-r--r--android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java59
-rw-r--r--android/guava/src/com/google/common/collect/Multimap.java17
-rw-r--r--android/guava/src/com/google/common/collect/MultimapBuilder.java15
-rw-r--r--android/guava/src/com/google/common/collect/Multimaps.java60
-rw-r--r--android/guava/src/com/google/common/collect/Multiset.java13
-rw-r--r--android/guava/src/com/google/common/collect/Multisets.java16
-rw-r--r--android/guava/src/com/google/common/collect/MutableClassToInstanceMap.java81
-rw-r--r--android/guava/src/com/google/common/collect/NaturalOrdering.java6
-rw-r--r--android/guava/src/com/google/common/collect/NullsFirstOrdering.java9
-rw-r--r--android/guava/src/com/google/common/collect/NullsLastOrdering.java9
-rw-r--r--android/guava/src/com/google/common/collect/ObjectArrays.java7
-rw-r--r--android/guava/src/com/google/common/collect/Ordering.java29
-rw-r--r--android/guava/src/com/google/common/collect/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/collect/Platform.java18
-rw-r--r--android/guava/src/com/google/common/collect/Queues.java18
-rw-r--r--android/guava/src/com/google/common/collect/Range.java9
-rw-r--r--android/guava/src/com/google/common/collect/RangeMap.java4
-rw-r--r--android/guava/src/com/google/common/collect/RangeSet.java2
-rw-r--r--android/guava/src/com/google/common/collect/RegularContiguousSet.java15
-rw-r--r--android/guava/src/com/google/common/collect/RegularImmutableMap.java2
-rw-r--r--android/guava/src/com/google/common/collect/Serialization.java2
-rw-r--r--android/guava/src/com/google/common/collect/Sets.java32
-rw-r--r--android/guava/src/com/google/common/collect/SortedLists.java2
-rw-r--r--android/guava/src/com/google/common/collect/SortedMultiset.java4
-rw-r--r--android/guava/src/com/google/common/collect/StandardTable.java9
-rw-r--r--android/guava/src/com/google/common/collect/Synchronized.java37
-rw-r--r--android/guava/src/com/google/common/collect/Table.java10
-rw-r--r--android/guava/src/com/google/common/collect/TableCollectors.java225
-rw-r--r--android/guava/src/com/google/common/collect/Tables.java9
-rw-r--r--android/guava/src/com/google/common/collect/TopKSelector.java4
-rw-r--r--android/guava/src/com/google/common/collect/TreeMultimap.java6
-rw-r--r--android/guava/src/com/google/common/collect/TreeMultiset.java6
-rw-r--r--android/guava/src/com/google/common/collect/TreeRangeMap.java10
-rw-r--r--android/guava/src/com/google/common/collect/TreeRangeSet.java13
-rw-r--r--android/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java3
-rw-r--r--android/guava/src/com/google/common/collect/package-info.java235
-rw-r--r--android/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java2
-rw-r--r--android/guava/src/com/google/common/escape/Escapers.java2
-rw-r--r--android/guava/src/com/google/common/escape/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/escape/package-info.java4
-rw-r--r--android/guava/src/com/google/common/eventbus/Dispatcher.java2
-rw-r--r--android/guava/src/com/google/common/eventbus/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/eventbus/package-info.java234
-rw-r--r--android/guava/src/com/google/common/graph/AbstractBaseGraph.java16
-rw-r--r--android/guava/src/com/google/common/graph/AbstractNetwork.java20
-rw-r--r--android/guava/src/com/google/common/graph/AbstractValueGraph.java13
-rw-r--r--android/guava/src/com/google/common/graph/GraphBuilder.java13
-rw-r--r--android/guava/src/com/google/common/graph/GraphConstants.java2
-rw-r--r--android/guava/src/com/google/common/graph/Graphs.java8
-rw-r--r--android/guava/src/com/google/common/graph/Network.java14
-rw-r--r--android/guava/src/com/google/common/graph/NetworkBuilder.java14
-rw-r--r--android/guava/src/com/google/common/graph/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/graph/Traverser.java2
-rw-r--r--android/guava/src/com/google/common/graph/ValueGraphBuilder.java13
-rw-r--r--android/guava/src/com/google/common/hash/AbstractByteHasher.java10
-rw-r--r--android/guava/src/com/google/common/hash/AbstractHasher.java14
-rw-r--r--android/guava/src/com/google/common/hash/AbstractStreamingHasher.java9
-rw-r--r--android/guava/src/com/google/common/hash/BloomFilter.java6
-rw-r--r--android/guava/src/com/google/common/hash/BloomFilterStrategies.java2
-rw-r--r--android/guava/src/com/google/common/hash/FarmHashFingerprint64.java6
-rw-r--r--android/guava/src/com/google/common/hash/Funnels.java6
-rw-r--r--android/guava/src/com/google/common/hash/Hasher.java15
-rw-r--r--android/guava/src/com/google/common/hash/Hashing.java13
-rw-r--r--android/guava/src/com/google/common/hash/IgnoreJRERequirement.java30
-rw-r--r--android/guava/src/com/google/common/hash/LittleEndianByteArray.java44
-rw-r--r--android/guava/src/com/google/common/hash/MessageDigestHashFunction.java6
-rw-r--r--android/guava/src/com/google/common/hash/Murmur3_32HashFunction.java8
-rw-r--r--android/guava/src/com/google/common/hash/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/hash/PrimitiveSink.java14
-rw-r--r--android/guava/src/com/google/common/html/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/html/package-info.java2
-rw-r--r--android/guava/src/com/google/common/io/AppendableWriter.java2
-rw-r--r--android/guava/src/com/google/common/io/BaseEncoding.java125
-rw-r--r--android/guava/src/com/google/common/io/ByteArrayDataInput.java2
-rw-r--r--android/guava/src/com/google/common/io/ByteArrayDataOutput.java2
-rw-r--r--android/guava/src/com/google/common/io/ByteProcessor.java4
-rw-r--r--android/guava/src/com/google/common/io/ByteSink.java2
-rw-r--r--android/guava/src/com/google/common/io/ByteSource.java12
-rw-r--r--android/guava/src/com/google/common/io/ByteStreams.java20
-rw-r--r--android/guava/src/com/google/common/io/CharSequenceReader.java2
-rw-r--r--android/guava/src/com/google/common/io/CharSink.java2
-rw-r--r--android/guava/src/com/google/common/io/CharSource.java7
-rw-r--r--android/guava/src/com/google/common/io/CharStreams.java9
-rw-r--r--android/guava/src/com/google/common/io/Closeables.java4
-rw-r--r--android/guava/src/com/google/common/io/Closer.java4
-rw-r--r--android/guava/src/com/google/common/io/CountingInputStream.java4
-rw-r--r--android/guava/src/com/google/common/io/CountingOutputStream.java2
-rw-r--r--android/guava/src/com/google/common/io/FileBackedOutputStream.java26
-rw-r--r--android/guava/src/com/google/common/io/FileWriteMode.java2
-rw-r--r--android/guava/src/com/google/common/io/Files.java59
-rw-r--r--android/guava/src/com/google/common/io/Flushables.java4
-rw-r--r--android/guava/src/com/google/common/io/IgnoreJRERequirement.java (renamed from android/guava/src/com/google/common/primitives/Platform.java)24
-rw-r--r--android/guava/src/com/google/common/io/Java8Compatibility.java2
-rw-r--r--android/guava/src/com/google/common/io/LineBuffer.java2
-rw-r--r--android/guava/src/com/google/common/io/LineProcessor.java4
-rw-r--r--android/guava/src/com/google/common/io/LineReader.java4
-rw-r--r--android/guava/src/com/google/common/io/LittleEndianDataInputStream.java4
-rw-r--r--android/guava/src/com/google/common/io/LittleEndianDataOutputStream.java4
-rw-r--r--android/guava/src/com/google/common/io/MultiInputStream.java2
-rw-r--r--android/guava/src/com/google/common/io/MultiReader.java2
-rw-r--r--android/guava/src/com/google/common/io/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/io/PatternFilenameFilter.java4
-rw-r--r--android/guava/src/com/google/common/io/ReaderInputStream.java6
-rw-r--r--android/guava/src/com/google/common/io/Resources.java2
-rw-r--r--android/guava/src/com/google/common/io/TempFileCreator.java239
-rw-r--r--android/guava/src/com/google/common/io/package-info.java13
-rw-r--r--android/guava/src/com/google/common/math/BigDecimalMath.java2
-rw-r--r--android/guava/src/com/google/common/math/BigIntegerMath.java12
-rw-r--r--android/guava/src/com/google/common/math/DoubleMath.java11
-rw-r--r--android/guava/src/com/google/common/math/IntMath.java12
-rw-r--r--android/guava/src/com/google/common/math/LinearTransformation.java4
-rw-r--r--android/guava/src/com/google/common/math/LongMath.java52
-rw-r--r--android/guava/src/com/google/common/math/MathPreconditions.java8
-rw-r--r--android/guava/src/com/google/common/math/PairedStats.java4
-rw-r--r--android/guava/src/com/google/common/math/PairedStatsAccumulator.java4
-rw-r--r--android/guava/src/com/google/common/math/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/math/Quantiles.java4
-rw-r--r--android/guava/src/com/google/common/math/Stats.java22
-rw-r--r--android/guava/src/com/google/common/math/StatsAccumulator.java4
-rw-r--r--android/guava/src/com/google/common/math/ToDoubleRounder.java2
-rw-r--r--android/guava/src/com/google/common/math/package-info.java5
-rw-r--r--android/guava/src/com/google/common/net/HostSpecifier.java2
-rw-r--r--android/guava/src/com/google/common/net/HttpHeaders.java69
-rw-r--r--android/guava/src/com/google/common/net/InetAddresses.java6
-rw-r--r--android/guava/src/com/google/common/net/InternetDomainName.java112
-rw-r--r--android/guava/src/com/google/common/net/MediaType.java9
-rw-r--r--android/guava/src/com/google/common/net/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/net/PercentEscaper.java4
-rw-r--r--android/guava/src/com/google/common/net/package-info.java5
-rw-r--r--android/guava/src/com/google/common/primitives/Booleans.java61
-rw-r--r--android/guava/src/com/google/common/primitives/Bytes.java52
-rw-r--r--android/guava/src/com/google/common/primitives/Chars.java54
-rw-r--r--android/guava/src/com/google/common/primitives/Doubles.java60
-rw-r--r--android/guava/src/com/google/common/primitives/Floats.java58
-rw-r--r--android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java10
-rw-r--r--android/guava/src/com/google/common/primitives/ImmutableIntArray.java10
-rw-r--r--android/guava/src/com/google/common/primitives/ImmutableLongArray.java10
-rw-r--r--android/guava/src/com/google/common/primitives/Ints.java83
-rw-r--r--android/guava/src/com/google/common/primitives/Longs.java73
-rw-r--r--android/guava/src/com/google/common/primitives/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/primitives/Primitives.java4
-rw-r--r--android/guava/src/com/google/common/primitives/Shorts.java55
-rw-r--r--android/guava/src/com/google/common/primitives/UnsignedBytes.java7
-rw-r--r--android/guava/src/com/google/common/primitives/UnsignedInteger.java2
-rw-r--r--android/guava/src/com/google/common/primitives/UnsignedInts.java2
-rw-r--r--android/guava/src/com/google/common/primitives/UnsignedLongs.java2
-rw-r--r--android/guava/src/com/google/common/primitives/package-info.java43
-rw-r--r--android/guava/src/com/google/common/reflect/IgnoreJRERequirement.java30
-rw-r--r--android/guava/src/com/google/common/reflect/Invokable.java71
-rw-r--r--android/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java44
-rw-r--r--android/guava/src/com/google/common/reflect/Parameter.java61
-rw-r--r--android/guava/src/com/google/common/reflect/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/reflect/Reflection.java2
-rw-r--r--android/guava/src/com/google/common/reflect/TypeResolver.java4
-rw-r--r--android/guava/src/com/google/common/reflect/TypeToInstanceMap.java16
-rw-r--r--android/guava/src/com/google/common/reflect/TypeToken.java12
-rw-r--r--android/guava/src/com/google/common/reflect/Types.java2
-rw-r--r--android/guava/src/com/google/common/reflect/package-info.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java82
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractFuture.java71
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractIdleService.java45
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java20
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java89
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractService.java11
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AggregateFuture.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AggregateFutureState.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/AtomicLongMap.java9
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Callables.java7
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ClosingFuture.java152
-rw-r--r--android/guava/src/com/google/common/util/concurrent/CollectionFuture.java6
-rw-r--r--android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java10
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ExecutionError.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ExecutionList.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java7
-rw-r--r--android/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java18
-rw-r--r--android/guava/src/com/google/common/util/concurrent/FluentFuture.java10
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java8
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingCondition.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java10
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingFuture.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java8
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ForwardingLock.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Futures.java75
-rw-r--r--android/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java12
-rw-r--r--android/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ImmediateFuture.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/InterruptibleTask.java7
-rw-r--r--android/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java13
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ListenableFuture.java9
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Monitor.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/MoreExecutors.java47
-rw-r--r--android/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Platform.java10
-rw-r--r--android/guava/src/com/google/common/util/concurrent/RateLimiter.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Runnables.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/SequentialExecutor.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Service.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ServiceManager.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java28
-rw-r--r--android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Striped.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java15
-rw-r--r--android/guava/src/com/google/common/util/concurrent/TimeLimiter.java7
-rw-r--r--android/guava/src/com/google/common/util/concurrent/TimeoutFuture.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java2
-rw-r--r--android/guava/src/com/google/common/util/concurrent/Uninterruptibles.java16
-rw-r--r--android/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java6
-rw-r--r--android/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java4
-rw-r--r--android/guava/src/com/google/common/util/concurrent/package-info.java11
-rw-r--r--android/guava/src/com/google/common/xml/ParametricNullness.java43
-rw-r--r--android/guava/src/com/google/common/xml/package-info.java2
-rw-r--r--android/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java10
-rw-r--r--android/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java31
-rw-r--r--android/pom.xml243
-rw-r--r--futures/failureaccess/pom.xml2
-rw-r--r--futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutureFailureAccess.java4
-rw-r--r--futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutures.java4
-rw-r--r--futures/listenablefuture1/src/com/google/common/util/concurrent/ListenableFuture.java9
-rw-r--r--guava-bom/pom.xml2
-rw-r--r--guava-gwt/pom.xml46
-rw-r--r--guava-gwt/src-super/com/google/common/base/super/com/google/common/base/Platform.java27
-rw-r--r--guava-gwt/src-super/com/google/common/cache/super/com/google/common/cache/LocalCache.java4
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/AbstractSortedMultiset.java6
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EnumMultiset.java54
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMap.java7
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java5
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableList.java8
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMap.java7
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSet.java14
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedMap.java6
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedSet.java6
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/MapMaker.java3
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java51
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.native.js3
-rw-r--r--guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultiset.java2
-rw-r--r--guava-gwt/src-super/com/google/common/primitives/super/com/google/common/primitives/Platform.java32
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AbstractFuture.java22
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AggregateFutureState.java7
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java5
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java6
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/InterruptibleTask.java5
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java76
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Platform.java4
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Thenable.java44
-rw-r--r--guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Uninterruptibles.java7
-rw-r--r--guava-gwt/src/com/google/common/util/concurrent/Concurrent.gwt.xml1
-rw-r--r--guava-testlib/README.md4
-rw-r--r--guava-testlib/pom.xml13
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java5
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java13
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/AbstractTester.java8
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/BaseComparable.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java41
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java14
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/Helpers.java103
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/MinimalSet.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/Platform.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java37
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java19
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/SampleElements.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java5
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/SpliteratorTester.java7
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/features/package-info.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/google/package-info.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/package-info.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/suites/package-info.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java3
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/MapMergeTester.java1
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/MapPutIfAbsentTester.java16
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java2
-rw-r--r--guava-testlib/src/com/google/common/collect/testing/testers/package-info.java2
-rw-r--r--guava-testlib/src/com/google/common/escape/testing/package-info.java2
-rw-r--r--guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java7
-rw-r--r--guava-testlib/src/com/google/common/testing/ArbitraryInstances.java10
-rw-r--r--guava-testlib/src/com/google/common/testing/ClassSanityTester.java28
-rw-r--r--guava-testlib/src/com/google/common/testing/ClusterException.java11
-rw-r--r--guava-testlib/src/com/google/common/testing/CollectorTester.java41
-rw-r--r--guava-testlib/src/com/google/common/testing/DummyProxy.java10
-rw-r--r--guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java41
-rw-r--r--guava-testlib/src/com/google/common/testing/EqualsTester.java19
-rw-r--r--guava-testlib/src/com/google/common/testing/EquivalenceTester.java5
-rw-r--r--guava-testlib/src/com/google/common/testing/FakeTicker.java10
-rw-r--r--guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java18
-rw-r--r--guava-testlib/src/com/google/common/testing/FreshValueGenerator.java18
-rw-r--r--guava-testlib/src/com/google/common/testing/GcFinalization.java3
-rw-r--r--guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java29
-rw-r--r--guava-testlib/src/com/google/common/testing/NullPointerTester.java180
-rw-r--r--guava-testlib/src/com/google/common/testing/Platform.java1
-rw-r--r--guava-testlib/src/com/google/common/testing/RelationshipTester.java3
-rw-r--r--guava-testlib/src/com/google/common/testing/SerializableTester.java4
-rw-r--r--guava-testlib/src/com/google/common/testing/SloppyTearDown.java3
-rw-r--r--guava-testlib/src/com/google/common/testing/TearDown.java3
-rw-r--r--guava-testlib/src/com/google/common/testing/TearDownAccepter.java5
-rw-r--r--guava-testlib/src/com/google/common/testing/TearDownStack.java3
-rw-r--r--guava-testlib/src/com/google/common/testing/TestLogHandler.java6
-rw-r--r--guava-testlib/src/com/google/common/testing/package-info.java5
-rw-r--r--guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java5
-rw-r--r--guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java2
-rw-r--r--guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java9
-rw-r--r--guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java27
-rw-r--r--guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java2
-rw-r--r--guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java13
-rw-r--r--guava-testlib/test/com/google/common/collect/testing/MyTester.java38
-rw-r--r--guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java55
-rw-r--r--guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java32
-rw-r--r--guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java5
-rw-r--r--guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java68
-rw-r--r--guava-testlib/test/com/google/common/testing/EqualsTesterTest.java17
-rw-r--r--guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java2
-rw-r--r--guava-testlib/test/com/google/common/testing/FakeTickerTest.java17
-rw-r--r--guava-testlib/test/com/google/common/testing/GcFinalizationTest.java8
-rw-r--r--guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java7
-rw-r--r--guava-testlib/test/com/google/common/testing/SerializableTesterTest.java7
-rw-r--r--guava-testlib/test/com/google/common/testing/TearDownStackTest.java3
-rw-r--r--guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java16
-rw-r--r--guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java6
-rw-r--r--guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java4
-rw-r--r--guava-tests/benchmark/com/google/common/cache/MapMakerComparisonBenchmark.java1
-rw-r--r--guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java4
-rw-r--r--guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java3
-rw-r--r--guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java11
-rw-r--r--guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java2
-rw-r--r--guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java5
-rw-r--r--guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java2
-rw-r--r--guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java8
-rw-r--r--guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java4
-rw-r--r--guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java27
-rw-r--r--guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java27
-rw-r--r--guava-tests/pom.xml25
-rw-r--r--guava-tests/test/com/google/common/base/AbstractIteratorTest.java12
-rw-r--r--guava-tests/test/com/google/common/base/AndroidIncompatible.java2
-rw-r--r--guava-tests/test/com/google/common/base/AsciiTest.java2
-rw-r--r--guava-tests/test/com/google/common/base/CaseFormatTest.java2
-rw-r--r--guava-tests/test/com/google/common/base/CharMatcherTest.java19
-rw-r--r--guava-tests/test/com/google/common/base/CharsetsTest.java7
-rw-r--r--guava-tests/test/com/google/common/base/EnumsTest.java21
-rw-r--r--guava-tests/test/com/google/common/base/EquivalenceTest.java17
-rw-r--r--guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java11
-rw-r--r--guava-tests/test/com/google/common/base/FunctionsTest.java24
-rw-r--r--guava-tests/test/com/google/common/base/JoinerTest.java10
-rw-r--r--guava-tests/test/com/google/common/base/MoreObjectsTest.java497
-rw-r--r--guava-tests/test/com/google/common/base/ObjectsTest.java2
-rw-r--r--guava-tests/test/com/google/common/base/OptionalTest.java30
-rw-r--r--guava-tests/test/com/google/common/base/PreconditionsTest.java13
-rw-r--r--guava-tests/test/com/google/common/base/PredicatesTest.java48
-rw-r--r--guava-tests/test/com/google/common/base/SplitterTest.java31
-rw-r--r--guava-tests/test/com/google/common/base/StopwatchJavaTimeTest.java2
-rw-r--r--guava-tests/test/com/google/common/base/StopwatchTest.java2
-rw-r--r--guava-tests/test/com/google/common/base/StringsTest.java5
-rw-r--r--guava-tests/test/com/google/common/base/SuppliersTest.java31
-rw-r--r--guava-tests/test/com/google/common/base/ThrowablesTest.java40
-rw-r--r--guava-tests/test/com/google/common/base/ToStringHelperTest.java25
-rw-r--r--guava-tests/test/com/google/common/base/Utf8Test.java6
-rw-r--r--guava-tests/test/com/google/common/base/VerifyTest.java2
-rw-r--r--guava-tests/test/com/google/common/cache/AbstractCacheTest.java7
-rw-r--r--guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java9
-rw-r--r--guava-tests/test/com/google/common/cache/CacheBuilderFactory.java24
-rw-r--r--guava-tests/test/com/google/common/cache/CacheBuilderGwtTest.java4
-rw-r--r--guava-tests/test/com/google/common/cache/CacheBuilderTest.java1
-rw-r--r--guava-tests/test/com/google/common/cache/CacheExpirationTest.java4
-rw-r--r--guava-tests/test/com/google/common/cache/CacheLoaderTest.java8
-rw-r--r--guava-tests/test/com/google/common/cache/CacheLoadingTest.java10
-rw-r--r--guava-tests/test/com/google/common/cache/CacheTesting.java2
-rw-r--r--guava-tests/test/com/google/common/cache/ForwardingCacheTest.java2
-rw-r--r--guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java2
-rw-r--r--guava-tests/test/com/google/common/cache/LocalCacheMapComputeTest.java2
-rw-r--r--guava-tests/test/com/google/common/cache/LocalCacheTest.java27
-rw-r--r--guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java55
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java54
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java55
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractIteratorTest.java15
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java45
-rw-r--r--guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ArrayTableRowTest.java45
-rw-r--r--guava-tests/test/com/google/common/collect/BenchmarkHelpers.java4
-rw-r--r--guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java5
-rw-r--r--guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java34
-rw-r--r--guava-tests/test/com/google/common/collect/Collections2Test.java46
-rw-r--r--guava-tests/test/com/google/common/collect/ComparatorsTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/ComparisonChainTest.java189
-rw-r--r--guava-tests/test/com/google/common/collect/EnumBiMapTest.java2
-rw-r--r--guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java1
-rw-r--r--guava-tests/test/com/google/common/collect/FauxveridesTest.java7
-rw-r--r--guava-tests/test/com/google/common/collect/FilteredBiMapTest.java27
-rw-r--r--guava-tests/test/com/google/common/collect/FilteredCollectionsTestUtil.java (renamed from guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java)86
-rw-r--r--guava-tests/test/com/google/common/collect/FilteredMapTest.java211
-rw-r--r--guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java61
-rw-r--r--guava-tests/test/com/google/common/collect/FluentIterableTest.java4
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingListTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingMapTest.java7
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java29
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java15
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingQueueTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingSetTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableBiMapFloodingTest.java114
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java1196
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java201
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableListTest.java1049
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableMapFloodingTest.java106
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableMapTest.java1425
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java50
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableMultisetFloodingTest.java76
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java61
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSetFloodingTest.java93
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSetTest.java77
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java1142
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/ImmutableTableTest.java29
-rw-r--r--guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java33
-rw-r--r--guava-tests/test/com/google/common/collect/LegacyComparable.java3
-rw-r--r--guava-tests/test/com/google/common/collect/ListsImplTest.java2
-rw-r--r--guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java40
-rw-r--r--guava-tests/test/com/google/common/collect/MapMakerTest.java1
-rw-r--r--guava-tests/test/com/google/common/collect/MapsTest.java267
-rw-r--r--guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java10
-rw-r--r--guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java10
-rw-r--r--guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java2
-rw-r--r--guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/OrderingTest.java2
-rw-r--r--guava-tests/test/com/google/common/collect/QueuesTest.java10
-rw-r--r--guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java47
-rw-r--r--guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java40
-rw-r--r--guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java40
-rw-r--r--guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java33
-rw-r--r--guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java34
-rw-r--r--guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java42
-rw-r--r--guava-tests/test/com/google/common/collect/SetsTest.java29
-rw-r--r--guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java39
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java3
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java13
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedMapTest.java9
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java27
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java15
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedSetTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/SynchronizedTableTest.java6
-rw-r--r--guava-tests/test/com/google/common/collect/TableCollectionTest.java593
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java45
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java46
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java43
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java7
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java33
-rw-r--r--guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java33
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java52
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java74
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java53
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java52
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java32
-rw-r--r--guava-tests/test/com/google/common/collect/TreeBasedTableTest.java54
-rw-r--r--guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java5
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java43
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java43
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java44
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java43
-rw-r--r--guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java44
-rw-r--r--guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java2
-rw-r--r--guava-tests/test/com/google/common/escape/EscapersTest.java6
-rw-r--r--guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java7
-rw-r--r--guava-tests/test/com/google/common/eventbus/DispatcherTest.java1
-rw-r--r--guava-tests/test/com/google/common/eventbus/EventBusTest.java3
-rw-r--r--guava-tests/test/com/google/common/eventbus/SubscriberTest.java3
-rw-r--r--guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java3
-rw-r--r--guava-tests/test/com/google/common/graph/AbstractNetworkTest.java6
-rw-r--r--guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java4
-rw-r--r--guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java52
-rw-r--r--guava-tests/test/com/google/common/graph/ElementOrderTest.java2
-rw-r--r--guava-tests/test/com/google/common/graph/EndpointPairTest.java4
-rw-r--r--guava-tests/test/com/google/common/graph/ValueGraphTest.java61
-rw-r--r--guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java2
-rw-r--r--guava-tests/test/com/google/common/hash/HashCodeTest.java3
-rw-r--r--guava-tests/test/com/google/common/hash/HashTestUtils.java2
-rw-r--r--guava-tests/test/com/google/common/hash/MacHashFunctionTest.java3
-rw-r--r--guava-tests/test/com/google/common/io/BaseEncodingTest.java104
-rw-r--r--guava-tests/test/com/google/common/io/ByteSinkTester.java4
-rw-r--r--guava-tests/test/com/google/common/io/ByteSourceTest.java11
-rw-r--r--guava-tests/test/com/google/common/io/ByteSourceTester.java4
-rw-r--r--guava-tests/test/com/google/common/io/ByteStreamsTest.java2
-rw-r--r--guava-tests/test/com/google/common/io/CharSinkTester.java4
-rw-r--r--guava-tests/test/com/google/common/io/CharSourceTester.java4
-rw-r--r--guava-tests/test/com/google/common/io/CloserTest.java2
-rw-r--r--guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java54
-rw-r--r--guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java60
-rw-r--r--guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java74
-rw-r--r--guava-tests/test/com/google/common/io/FilesFileTraverserTest.java33
-rw-r--r--guava-tests/test/com/google/common/io/FilesTest.java16
-rw-r--r--guava-tests/test/com/google/common/io/IoTestCase.java3
-rw-r--r--guava-tests/test/com/google/common/io/MoreFilesTest.java14
-rw-r--r--guava-tests/test/com/google/common/io/ResourcesTest.java12
-rw-r--r--guava-tests/test/com/google/common/io/SourceSinkTester.java2
-rw-r--r--guava-tests/test/com/google/common/math/BigIntegerMathTest.java50
-rw-r--r--guava-tests/test/com/google/common/math/DoubleMathTest.java45
-rw-r--r--guava-tests/test/com/google/common/math/IntMathTest.java27
-rw-r--r--guava-tests/test/com/google/common/math/LongMathTest.java57
-rw-r--r--guava-tests/test/com/google/common/math/MathPreconditionsTest.java4
-rw-r--r--guava-tests/test/com/google/common/math/MathTesting.java4
-rw-r--r--guava-tests/test/com/google/common/math/QuantilesTest.java10
-rw-r--r--guava-tests/test/com/google/common/math/StatsTesting.java6
-rw-r--r--guava-tests/test/com/google/common/math/TestPlatform.java2
-rw-r--r--guava-tests/test/com/google/common/net/HostAndPortTest.java10
-rw-r--r--guava-tests/test/com/google/common/net/HttpHeadersTest.java7
-rw-r--r--guava-tests/test/com/google/common/net/InetAddressesTest.java2
-rw-r--r--guava-tests/test/com/google/common/net/PercentEscaperTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/BooleansTest.java481
-rw-r--r--guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/BytesTest.java292
-rw-r--r--guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/CharsTest.java483
-rw-r--r--guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java6
-rw-r--r--guava-tests/test/com/google/common/primitives/DoublesTest.java495
-rw-r--r--guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/FloatsTest.java465
-rw-r--r--guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java13
-rw-r--r--guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java13
-rw-r--r--guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java13
-rw-r--r--guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/IntsTest.java469
-rw-r--r--guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/LongsTest.java548
-rw-r--r--guava-tests/test/com/google/common/primitives/PrimitivesTest.java39
-rw-r--r--guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java2
-rw-r--r--guava-tests/test/com/google/common/primitives/ShortsTest.java452
-rw-r--r--guava-tests/test/com/google/common/primitives/SignedBytesTest.java70
-rw-r--r--guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java113
-rw-r--r--guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java62
-rw-r--r--guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java133
-rw-r--r--guava-tests/test/com/google/common/primitives/UnsignedLongTest.java79
-rw-r--r--guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java152
-rw-r--r--guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java3
-rw-r--r--guava-tests/test/com/google/common/reflect/ClassPathTest.java35
-rw-r--r--guava-tests/test/com/google/common/reflect/InvokableTest.java8
-rw-r--r--guava-tests/test/com/google/common/reflect/ParameterTest.java10
-rw-r--r--guava-tests/test/com/google/common/reflect/SubtypeTester.java5
-rw-r--r--guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java4
-rw-r--r--guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java8
-rw-r--r--guava-tests/test/com/google/common/reflect/TypeTokenTest.java17
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java4
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java82
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java115
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java543
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java6
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/CallablesTest.java19
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java15
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java70
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java2
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java52
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/FuturesTest.java15
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java9
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java28
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java42
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ListeningExecutorServiceTest.java135
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java5
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java18
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java2
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java4
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java2
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/TestThread.java4
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java9
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java2
-rw-r--r--guava/module.json295
-rw-r--r--guava/pom.xml60
-rw-r--r--guava/src/com/google/common/annotations/J2ktIncompatible.java31
-rw-r--r--guava/src/com/google/common/annotations/VisibleForTesting.java4
-rw-r--r--guava/src/com/google/common/annotations/package-info.java4
-rw-r--r--guava/src/com/google/common/base/CaseFormat.java3
-rw-r--r--guava/src/com/google/common/base/CharMatcher.java15
-rw-r--r--guava/src/com/google/common/base/Charsets.java5
-rw-r--r--guava/src/com/google/common/base/Converter.java58
-rw-r--r--guava/src/com/google/common/base/Defaults.java2
-rw-r--r--guava/src/com/google/common/base/Enums.java18
-rw-r--r--guava/src/com/google/common/base/Equivalence.java57
-rw-r--r--guava/src/com/google/common/base/FinalizablePhantomReference.java2
-rw-r--r--guava/src/com/google/common/base/FinalizableReference.java2
-rw-r--r--guava/src/com/google/common/base/FinalizableReferenceQueue.java2
-rw-r--r--guava/src/com/google/common/base/FinalizableSoftReference.java2
-rw-r--r--guava/src/com/google/common/base/FinalizableWeakReference.java2
-rw-r--r--guava/src/com/google/common/base/Function.java2
-rw-r--r--guava/src/com/google/common/base/FunctionalEquivalence.java2
-rw-r--r--guava/src/com/google/common/base/Functions.java7
-rw-r--r--guava/src/com/google/common/base/Java8Compatibility.java2
-rw-r--r--guava/src/com/google/common/base/JdkPattern.java2
-rw-r--r--guava/src/com/google/common/base/Joiner.java7
-rw-r--r--guava/src/com/google/common/base/MoreObjects.java25
-rw-r--r--guava/src/com/google/common/base/Optional.java6
-rw-r--r--guava/src/com/google/common/base/PairwiseEquivalence.java3
-rw-r--r--guava/src/com/google/common/base/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/base/PatternCompiler.java2
-rw-r--r--guava/src/com/google/common/base/Platform.java27
-rw-r--r--guava/src/com/google/common/base/Preconditions.java330
-rw-r--r--guava/src/com/google/common/base/Predicate.java2
-rw-r--r--guava/src/com/google/common/base/Predicates.java27
-rw-r--r--guava/src/com/google/common/base/SmallCharMatcher.java2
-rw-r--r--guava/src/com/google/common/base/Splitter.java9
-rw-r--r--guava/src/com/google/common/base/StandardSystemProperty.java4
-rw-r--r--guava/src/com/google/common/base/Stopwatch.java10
-rw-r--r--guava/src/com/google/common/base/Supplier.java2
-rw-r--r--guava/src/com/google/common/base/Suppliers.java45
-rw-r--r--guava/src/com/google/common/base/Throwables.java24
-rw-r--r--guava/src/com/google/common/base/Ticker.java3
-rw-r--r--guava/src/com/google/common/base/Utf8.java2
-rw-r--r--guava/src/com/google/common/base/package-info.java43
-rw-r--r--guava/src/com/google/common/cache/AbstractLoadingCache.java2
-rw-r--r--guava/src/com/google/common/cache/Cache.java7
-rw-r--r--guava/src/com/google/common/cache/CacheBuilder.java135
-rw-r--r--guava/src/com/google/common/cache/CacheBuilderSpec.java14
-rw-r--r--guava/src/com/google/common/cache/CacheLoader.java21
-rw-r--r--guava/src/com/google/common/cache/CacheStats.java4
-rw-r--r--guava/src/com/google/common/cache/ForwardingLoadingCache.java4
-rw-r--r--guava/src/com/google/common/cache/LoadingCache.java4
-rw-r--r--guava/src/com/google/common/cache/LocalCache.java356
-rw-r--r--guava/src/com/google/common/cache/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/cache/package-info.java15
-rw-r--r--guava/src/com/google/common/collect/AbstractBiMap.java34
-rw-r--r--guava/src/com/google/common/collect/AbstractIterator.java1
-rw-r--r--guava/src/com/google/common/collect/AbstractMapBasedMultimap.java1
-rw-r--r--guava/src/com/google/common/collect/AbstractMapBasedMultiset.java3
-rw-r--r--guava/src/com/google/common/collect/AbstractNavigableMap.java4
-rw-r--r--guava/src/com/google/common/collect/AbstractSortedMultiset.java3
-rw-r--r--guava/src/com/google/common/collect/AllEqualOrdering.java3
-rw-r--r--guava/src/com/google/common/collect/ArrayListMultimap.java4
-rw-r--r--guava/src/com/google/common/collect/ArrayTable.java7
-rw-r--r--guava/src/com/google/common/collect/BiMap.java9
-rw-r--r--guava/src/com/google/common/collect/ClassToInstanceMap.java39
-rw-r--r--guava/src/com/google/common/collect/CollectCollectors.java35
-rw-r--r--guava/src/com/google/common/collect/Collections2.java4
-rw-r--r--guava/src/com/google/common/collect/CompactHashMap.java10
-rw-r--r--guava/src/com/google/common/collect/CompactHashSet.java3
-rw-r--r--guava/src/com/google/common/collect/CompactLinkedHashMap.java2
-rw-r--r--guava/src/com/google/common/collect/ComparisonChain.java48
-rw-r--r--guava/src/com/google/common/collect/CompoundOrdering.java4
-rw-r--r--guava/src/com/google/common/collect/ConcurrentHashMultiset.java5
-rw-r--r--guava/src/com/google/common/collect/ConsumingQueueIterator.java4
-rw-r--r--guava/src/com/google/common/collect/ContiguousSet.java7
-rw-r--r--guava/src/com/google/common/collect/DescendingMultiset.java7
-rw-r--r--guava/src/com/google/common/collect/DiscreteDomain.java9
-rw-r--r--guava/src/com/google/common/collect/EmptyContiguousSet.java13
-rw-r--r--guava/src/com/google/common/collect/EmptyImmutableListMultimap.java12
-rw-r--r--guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java12
-rw-r--r--guava/src/com/google/common/collect/EnumBiMap.java64
-rw-r--r--guava/src/com/google/common/collect/EnumHashBiMap.java28
-rw-r--r--guava/src/com/google/common/collect/EnumMultiset.java2
-rw-r--r--guava/src/com/google/common/collect/EvictingQueue.java4
-rw-r--r--guava/src/com/google/common/collect/FluentIterable.java73
-rw-r--r--guava/src/com/google/common/collect/ForwardingBlockingDeque.java2
-rw-r--r--guava/src/com/google/common/collect/ForwardingDeque.java2
-rw-r--r--guava/src/com/google/common/collect/ForwardingList.java5
-rw-r--r--guava/src/com/google/common/collect/ForwardingMap.java8
-rw-r--r--guava/src/com/google/common/collect/ForwardingMapEntry.java2
-rw-r--r--guava/src/com/google/common/collect/ForwardingMultiset.java4
-rw-r--r--guava/src/com/google/common/collect/ForwardingNavigableMap.java8
-rw-r--r--guava/src/com/google/common/collect/ForwardingNavigableSet.java3
-rw-r--r--guava/src/com/google/common/collect/ForwardingSortedMap.java4
-rw-r--r--guava/src/com/google/common/collect/ForwardingSortedMultiset.java2
-rw-r--r--guava/src/com/google/common/collect/ForwardingSortedSet.java4
-rw-r--r--guava/src/com/google/common/collect/GeneralRange.java13
-rw-r--r--guava/src/com/google/common/collect/HashBiMap.java16
-rw-r--r--guava/src/com/google/common/collect/HashMultimap.java4
-rw-r--r--guava/src/com/google/common/collect/HashMultiset.java4
-rw-r--r--guava/src/com/google/common/collect/IgnoreJRERequirement.java30
-rw-r--r--guava/src/com/google/common/collect/ImmutableAsList.java4
-rw-r--r--guava/src/com/google/common/collect/ImmutableBiMap.java27
-rw-r--r--guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java11
-rw-r--r--guava/src/com/google/common/collect/ImmutableCollection.java10
-rw-r--r--guava/src/com/google/common/collect/ImmutableEntry.java6
-rw-r--r--guava/src/com/google/common/collect/ImmutableEnumMap.java10
-rw-r--r--guava/src/com/google/common/collect/ImmutableEnumSet.java15
-rw-r--r--guava/src/com/google/common/collect/ImmutableList.java12
-rw-r--r--guava/src/com/google/common/collect/ImmutableListMultimap.java10
-rw-r--r--guava/src/com/google/common/collect/ImmutableMap.java41
-rw-r--r--guava/src/com/google/common/collect/ImmutableMapEntry.java2
-rw-r--r--guava/src/com/google/common/collect/ImmutableMapEntrySet.java11
-rw-r--r--guava/src/com/google/common/collect/ImmutableMapKeySet.java2
-rw-r--r--guava/src/com/google/common/collect/ImmutableMapValues.java2
-rw-r--r--guava/src/com/google/common/collect/ImmutableMultimap.java17
-rw-r--r--guava/src/com/google/common/collect/ImmutableMultiset.java21
-rw-r--r--guava/src/com/google/common/collect/ImmutableRangeMap.java12
-rw-r--r--guava/src/com/google/common/collect/ImmutableRangeSet.java21
-rw-r--r--guava/src/com/google/common/collect/ImmutableSet.java17
-rw-r--r--guava/src/com/google/common/collect/ImmutableSetMultimap.java8
-rw-r--r--guava/src/com/google/common/collect/ImmutableSortedMap.java50
-rw-r--r--guava/src/com/google/common/collect/ImmutableSortedMultiset.java12
-rw-r--r--guava/src/com/google/common/collect/ImmutableSortedSet.java16
-rw-r--r--guava/src/com/google/common/collect/ImmutableTable.java12
-rw-r--r--guava/src/com/google/common/collect/Interner.java4
-rw-r--r--guava/src/com/google/common/collect/Interners.java2
-rw-r--r--guava/src/com/google/common/collect/Iterables.java36
-rw-r--r--guava/src/com/google/common/collect/Iterators.java14
-rw-r--r--guava/src/com/google/common/collect/JdkBackedImmutableMultiset.java3
-rw-r--r--guava/src/com/google/common/collect/LinkedHashMultimap.java10
-rw-r--r--guava/src/com/google/common/collect/LinkedHashMultiset.java4
-rw-r--r--guava/src/com/google/common/collect/LinkedListMultimap.java8
-rw-r--r--guava/src/com/google/common/collect/Lists.java27
-rw-r--r--guava/src/com/google/common/collect/MapMaker.java2
-rw-r--r--guava/src/com/google/common/collect/MapMakerInternalMap.java499
-rw-r--r--guava/src/com/google/common/collect/Maps.java175
-rw-r--r--guava/src/com/google/common/collect/MinMaxPriorityQueue.java59
-rw-r--r--guava/src/com/google/common/collect/MoreCollectors.java3
-rw-r--r--guava/src/com/google/common/collect/Multimap.java17
-rw-r--r--guava/src/com/google/common/collect/MultimapBuilder.java15
-rw-r--r--guava/src/com/google/common/collect/Multimaps.java61
-rw-r--r--guava/src/com/google/common/collect/Multiset.java15
-rw-r--r--guava/src/com/google/common/collect/Multisets.java16
-rw-r--r--guava/src/com/google/common/collect/MutableClassToInstanceMap.java81
-rw-r--r--guava/src/com/google/common/collect/NaturalOrdering.java6
-rw-r--r--guava/src/com/google/common/collect/NullsFirstOrdering.java9
-rw-r--r--guava/src/com/google/common/collect/NullsLastOrdering.java9
-rw-r--r--guava/src/com/google/common/collect/ObjectArrays.java7
-rw-r--r--guava/src/com/google/common/collect/Ordering.java29
-rw-r--r--guava/src/com/google/common/collect/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/collect/Platform.java37
-rw-r--r--guava/src/com/google/common/collect/Queues.java22
-rw-r--r--guava/src/com/google/common/collect/Range.java9
-rw-r--r--guava/src/com/google/common/collect/RangeMap.java4
-rw-r--r--guava/src/com/google/common/collect/RangeSet.java2
-rw-r--r--guava/src/com/google/common/collect/RegularContiguousSet.java15
-rw-r--r--guava/src/com/google/common/collect/RegularImmutableBiMap.java10
-rw-r--r--guava/src/com/google/common/collect/RegularImmutableMap.java14
-rw-r--r--guava/src/com/google/common/collect/Serialization.java2
-rw-r--r--guava/src/com/google/common/collect/Sets.java32
-rw-r--r--guava/src/com/google/common/collect/SortedLists.java2
-rw-r--r--guava/src/com/google/common/collect/SortedMultiset.java4
-rw-r--r--guava/src/com/google/common/collect/StandardTable.java9
-rw-r--r--guava/src/com/google/common/collect/Streams.java3
-rw-r--r--guava/src/com/google/common/collect/Synchronized.java42
-rw-r--r--guava/src/com/google/common/collect/Table.java10
-rw-r--r--guava/src/com/google/common/collect/Tables.java14
-rw-r--r--guava/src/com/google/common/collect/TopKSelector.java4
-rw-r--r--guava/src/com/google/common/collect/TreeMultimap.java6
-rw-r--r--guava/src/com/google/common/collect/TreeMultiset.java6
-rw-r--r--guava/src/com/google/common/collect/TreeRangeMap.java10
-rw-r--r--guava/src/com/google/common/collect/TreeRangeSet.java13
-rw-r--r--guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java3
-rw-r--r--guava/src/com/google/common/collect/package-info.java235
-rw-r--r--guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java2
-rw-r--r--guava/src/com/google/common/escape/Escapers.java2
-rw-r--r--guava/src/com/google/common/escape/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/escape/package-info.java4
-rw-r--r--guava/src/com/google/common/eventbus/Dispatcher.java2
-rw-r--r--guava/src/com/google/common/eventbus/EventBus.java3
-rw-r--r--guava/src/com/google/common/eventbus/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/eventbus/package-info.java234
-rw-r--r--guava/src/com/google/common/graph/AbstractBaseGraph.java16
-rw-r--r--guava/src/com/google/common/graph/AbstractNetwork.java20
-rw-r--r--guava/src/com/google/common/graph/AbstractValueGraph.java13
-rw-r--r--guava/src/com/google/common/graph/GraphBuilder.java13
-rw-r--r--guava/src/com/google/common/graph/GraphConstants.java2
-rw-r--r--guava/src/com/google/common/graph/Graphs.java8
-rw-r--r--guava/src/com/google/common/graph/Network.java14
-rw-r--r--guava/src/com/google/common/graph/NetworkBuilder.java14
-rw-r--r--guava/src/com/google/common/graph/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/graph/Traverser.java2
-rw-r--r--guava/src/com/google/common/graph/ValueGraphBuilder.java13
-rw-r--r--guava/src/com/google/common/hash/AbstractByteHasher.java10
-rw-r--r--guava/src/com/google/common/hash/AbstractHasher.java14
-rw-r--r--guava/src/com/google/common/hash/AbstractStreamingHasher.java9
-rw-r--r--guava/src/com/google/common/hash/BloomFilter.java6
-rw-r--r--guava/src/com/google/common/hash/BloomFilterStrategies.java2
-rw-r--r--guava/src/com/google/common/hash/FarmHashFingerprint64.java6
-rw-r--r--guava/src/com/google/common/hash/Funnels.java6
-rw-r--r--guava/src/com/google/common/hash/Hasher.java15
-rw-r--r--guava/src/com/google/common/hash/Hashing.java111
-rw-r--r--guava/src/com/google/common/hash/IgnoreJRERequirement.java30
-rw-r--r--guava/src/com/google/common/hash/LittleEndianByteArray.java46
-rw-r--r--guava/src/com/google/common/hash/MessageDigestHashFunction.java6
-rw-r--r--guava/src/com/google/common/hash/Murmur3_32HashFunction.java8
-rw-r--r--guava/src/com/google/common/hash/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/hash/PrimitiveSink.java14
-rw-r--r--guava/src/com/google/common/html/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/html/package-info.java2
-rw-r--r--guava/src/com/google/common/io/AppendableWriter.java2
-rw-r--r--guava/src/com/google/common/io/BaseEncoding.java125
-rw-r--r--guava/src/com/google/common/io/ByteArrayDataInput.java2
-rw-r--r--guava/src/com/google/common/io/ByteArrayDataOutput.java2
-rw-r--r--guava/src/com/google/common/io/ByteProcessor.java4
-rw-r--r--guava/src/com/google/common/io/ByteSink.java2
-rw-r--r--guava/src/com/google/common/io/ByteSource.java12
-rw-r--r--guava/src/com/google/common/io/ByteStreams.java20
-rw-r--r--guava/src/com/google/common/io/CharSequenceReader.java2
-rw-r--r--guava/src/com/google/common/io/CharSink.java5
-rw-r--r--guava/src/com/google/common/io/CharSource.java9
-rw-r--r--guava/src/com/google/common/io/CharStreams.java9
-rw-r--r--guava/src/com/google/common/io/Closeables.java4
-rw-r--r--guava/src/com/google/common/io/Closer.java4
-rw-r--r--guava/src/com/google/common/io/CountingInputStream.java4
-rw-r--r--guava/src/com/google/common/io/CountingOutputStream.java2
-rw-r--r--guava/src/com/google/common/io/FileBackedOutputStream.java26
-rw-r--r--guava/src/com/google/common/io/FileWriteMode.java2
-rw-r--r--guava/src/com/google/common/io/Files.java59
-rw-r--r--guava/src/com/google/common/io/Flushables.java4
-rw-r--r--guava/src/com/google/common/io/IgnoreJRERequirement.java30
-rw-r--r--guava/src/com/google/common/io/InsecureRecursiveDeleteException.java4
-rw-r--r--guava/src/com/google/common/io/Java8Compatibility.java2
-rw-r--r--guava/src/com/google/common/io/LineBuffer.java2
-rw-r--r--guava/src/com/google/common/io/LineProcessor.java4
-rw-r--r--guava/src/com/google/common/io/LineReader.java4
-rw-r--r--guava/src/com/google/common/io/LittleEndianDataInputStream.java4
-rw-r--r--guava/src/com/google/common/io/LittleEndianDataOutputStream.java4
-rw-r--r--guava/src/com/google/common/io/MoreFiles.java21
-rw-r--r--guava/src/com/google/common/io/MultiInputStream.java2
-rw-r--r--guava/src/com/google/common/io/MultiReader.java2
-rw-r--r--guava/src/com/google/common/io/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/io/PatternFilenameFilter.java4
-rw-r--r--guava/src/com/google/common/io/ReaderInputStream.java6
-rw-r--r--guava/src/com/google/common/io/RecursiveDeleteOption.java4
-rw-r--r--guava/src/com/google/common/io/Resources.java2
-rw-r--r--guava/src/com/google/common/io/TempFileCreator.java239
-rw-r--r--guava/src/com/google/common/io/package-info.java13
-rw-r--r--guava/src/com/google/common/math/BigDecimalMath.java2
-rw-r--r--guava/src/com/google/common/math/BigIntegerMath.java12
-rw-r--r--guava/src/com/google/common/math/DoubleMath.java11
-rw-r--r--guava/src/com/google/common/math/IntMath.java12
-rw-r--r--guava/src/com/google/common/math/LinearTransformation.java4
-rw-r--r--guava/src/com/google/common/math/LongMath.java52
-rw-r--r--guava/src/com/google/common/math/MathPreconditions.java8
-rw-r--r--guava/src/com/google/common/math/PairedStats.java4
-rw-r--r--guava/src/com/google/common/math/PairedStatsAccumulator.java4
-rw-r--r--guava/src/com/google/common/math/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/math/Quantiles.java4
-rw-r--r--guava/src/com/google/common/math/Stats.java22
-rw-r--r--guava/src/com/google/common/math/StatsAccumulator.java4
-rw-r--r--guava/src/com/google/common/math/ToDoubleRounder.java2
-rw-r--r--guava/src/com/google/common/math/package-info.java5
-rw-r--r--guava/src/com/google/common/net/HostSpecifier.java2
-rw-r--r--guava/src/com/google/common/net/HttpHeaders.java69
-rw-r--r--guava/src/com/google/common/net/InetAddresses.java6
-rw-r--r--guava/src/com/google/common/net/InternetDomainName.java112
-rw-r--r--guava/src/com/google/common/net/MediaType.java9
-rw-r--r--guava/src/com/google/common/net/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/net/PercentEscaper.java4
-rw-r--r--guava/src/com/google/common/net/package-info.java5
-rw-r--r--guava/src/com/google/common/primitives/Booleans.java61
-rw-r--r--guava/src/com/google/common/primitives/Bytes.java52
-rw-r--r--guava/src/com/google/common/primitives/Chars.java54
-rw-r--r--guava/src/com/google/common/primitives/Doubles.java60
-rw-r--r--guava/src/com/google/common/primitives/Floats.java58
-rw-r--r--guava/src/com/google/common/primitives/ImmutableDoubleArray.java11
-rw-r--r--guava/src/com/google/common/primitives/ImmutableIntArray.java11
-rw-r--r--guava/src/com/google/common/primitives/ImmutableLongArray.java11
-rw-r--r--guava/src/com/google/common/primitives/Ints.java83
-rw-r--r--guava/src/com/google/common/primitives/Longs.java73
-rw-r--r--guava/src/com/google/common/primitives/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/primitives/Platform.java48
-rw-r--r--guava/src/com/google/common/primitives/Primitives.java4
-rw-r--r--guava/src/com/google/common/primitives/Shorts.java55
-rw-r--r--guava/src/com/google/common/primitives/UnsignedBytes.java7
-rw-r--r--guava/src/com/google/common/primitives/UnsignedInteger.java2
-rw-r--r--guava/src/com/google/common/primitives/UnsignedInts.java2
-rw-r--r--guava/src/com/google/common/primitives/UnsignedLongs.java2
-rw-r--r--guava/src/com/google/common/primitives/package-info.java43
-rw-r--r--guava/src/com/google/common/reflect/IgnoreJRERequirement.java30
-rw-r--r--guava/src/com/google/common/reflect/Invokable.java36
-rw-r--r--guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java44
-rw-r--r--guava/src/com/google/common/reflect/Parameter.java36
-rw-r--r--guava/src/com/google/common/reflect/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/reflect/Reflection.java2
-rw-r--r--guava/src/com/google/common/reflect/TypeResolver.java4
-rw-r--r--guava/src/com/google/common/reflect/TypeToInstanceMap.java16
-rw-r--r--guava/src/com/google/common/reflect/TypeToken.java12
-rw-r--r--guava/src/com/google/common/reflect/Types.java2
-rw-r--r--guava/src/com/google/common/reflect/package-info.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java82
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractFuture.java71
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractIdleService.java45
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java20
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractScheduledService.java89
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractService.java11
-rw-r--r--guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/AggregateFuture.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/AggregateFutureState.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/AtomicDouble.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java10
-rw-r--r--guava/src/com/google/common/util/concurrent/AtomicLongMap.java9
-rw-r--r--guava/src/com/google/common/util/concurrent/Callables.java7
-rw-r--r--guava/src/com/google/common/util/concurrent/ClosingFuture.java154
-rw-r--r--guava/src/com/google/common/util/concurrent/CollectionFuture.java6
-rw-r--r--guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java10
-rw-r--r--guava/src/com/google/common/util/concurrent/ExecutionError.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ExecutionList.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ExecutionSequencer.java7
-rw-r--r--guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java18
-rw-r--r--guava/src/com/google/common/util/concurrent/FluentFuture.java12
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java8
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingCondition.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java10
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingFuture.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java8
-rw-r--r--guava/src/com/google/common/util/concurrent/ForwardingLock.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/Futures.java83
-rw-r--r--guava/src/com/google/common/util/concurrent/FuturesGetChecked.java16
-rw-r--r--guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ImmediateFuture.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/Internal.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/InterruptibleTask.java7
-rw-r--r--guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java13
-rw-r--r--guava/src/com/google/common/util/concurrent/ListenableFuture.java9
-rw-r--r--guava/src/com/google/common/util/concurrent/ListenableFutureTask.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ListenerCallQueue.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/ListeningExecutorService.java39
-rw-r--r--guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/Monitor.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/MoreExecutors.java56
-rw-r--r--guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/util/concurrent/Platform.java10
-rw-r--r--guava/src/com/google/common/util/concurrent/RateLimiter.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/Runnables.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/SequentialExecutor.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/Service.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ServiceManager.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java28
-rw-r--r--guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/Striped.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java15
-rw-r--r--guava/src/com/google/common/util/concurrent/TimeLimiter.java8
-rw-r--r--guava/src/com/google/common/util/concurrent/TimeoutFuture.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java2
-rw-r--r--guava/src/com/google/common/util/concurrent/Uninterruptibles.java26
-rw-r--r--guava/src/com/google/common/util/concurrent/WrappingExecutorService.java6
-rw-r--r--guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java4
-rw-r--r--guava/src/com/google/common/util/concurrent/package-info.java11
-rw-r--r--guava/src/com/google/common/xml/ParametricNullness.java43
-rw-r--r--guava/src/com/google/common/xml/package-info.java2
-rw-r--r--guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java10
-rw-r--r--guava/src/com/google/thirdparty/publicsuffix/TrieParser.java31
-rw-r--r--integration-tests/gradle/.gitignore2
-rw-r--r--integration-tests/gradle/build.gradle.kts221
-rw-r--r--integration-tests/gradle/gradle/wrapper/gradle-wrapper.jarbin0 -> 61624 bytes
-rw-r--r--integration-tests/gradle/gradle/wrapper/gradle-wrapper.properties6
-rwxr-xr-xintegration-tests/gradle/gradlew244
-rwxr-xr-xintegration-tests/gradle/gradlew.bat92
-rw-r--r--integration-tests/gradle/settings.gradle.kts29
-rw-r--r--overview.html11
-rw-r--r--pom.xml256
-rw-r--r--proguard/base.pro33
-rw-r--r--proguard/cache.pro12
-rw-r--r--proguard/collect.pro34
-rw-r--r--proguard/concurrent.pro40
-rw-r--r--proguard/hash.pro12
-rw-r--r--proguard/io.pro3
-rw-r--r--proguard/primitives.pro2
-rw-r--r--proguard/reflect.pro9
-rwxr-xr-xutil/gradle_integration_tests.sh36
-rwxr-xr-xutil/set_version.sh14
1503 files changed, 34601 insertions, 19500 deletions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ea5961ae0..23e7c71fc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -8,36 +8,42 @@ on:
branches:
- master
+permissions:
+ contents: read
+
jobs:
test:
- name: "${{ matrix.root-pom }} on JDK ${{ matrix.java }}"
+ permissions:
+ actions: write # for styfle/cancel-workflow-action to cancel/stop running workflows
+ contents: read # for actions/checkout to fetch code
+ name: "${{ matrix.root-pom }} on JDK ${{ matrix.java }} on ${{ matrix.os }}"
strategy:
matrix:
- java: [ 8, 11 ]
+ os: [ ubuntu-latest ]
+ java: [ 8, 11, 17 ]
root-pom: [ 'pom.xml', 'android/pom.xml' ]
- runs-on: ubuntu-latest
+ include:
+ - os: windows-latest
+ java: 17
+ root-pom: pom.xml
+ runs-on: ${{ matrix.os }}
env:
ROOT_POM: ${{ matrix.root-pom }}
steps:
# Cancel any previous runs for the same branch that are still running.
- name: 'Cancel previous runs'
- uses: styfle/cancel-workflow-action@0.9.1
+ uses: styfle/cancel-workflow-action@b173b6ec0100793626c2d9e6b90435061f4fc3e5
with:
access_token: ${{ github.token }}
- name: 'Check out repository'
- uses: actions/checkout@v2.4.0
- - name: 'Cache local Maven repository'
- uses: actions/cache@v2.1.7
- with:
- path: ~/.m2/repository
- key: maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- maven-
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9
- name: 'Set up JDK ${{ matrix.java }}'
- uses: actions/setup-java@v2
+ uses: actions/setup-java@cd89f46ac9d01407894225f350157564c9c7cee2
+
with:
java-version: ${{ matrix.java }}
distribution: 'zulu'
+ cache: 'maven'
- name: 'Install'
shell: bash
run: mvn -B -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn install -U -DskipTests=true -f $ROOT_POM
@@ -49,6 +55,10 @@ jobs:
if: ${{ failure() }}
shell: bash
run: ./util/print_surefire_reports.sh
+ - name: 'Integration Test'
+ if: matrix.java == 11
+ shell: bash
+ run: util/gradle_integration_tests.sh
publish_snapshot:
name: 'Publish snapshot'
@@ -57,22 +67,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Check out repository'
- uses: actions/checkout@v2.4.0
- - name: 'Cache local Maven repository'
- uses: actions/cache@v2.1.7
- with:
- path: ~/.m2/repository
- key: maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- maven-
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9
- name: 'Set up JDK 11'
- uses: actions/setup-java@v2
+ uses: actions/setup-java@cd89f46ac9d01407894225f350157564c9c7cee2
+
with:
java-version: 11
distribution: 'zulu'
server-id: sonatype-nexus-snapshots
server-username: CI_DEPLOY_USERNAME
server-password: CI_DEPLOY_PASSWORD
+ cache: 'maven'
- name: 'Publish'
env:
CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }}
@@ -80,25 +85,22 @@ jobs:
run: ./util/deploy_snapshot.sh
generate_docs:
+ permissions:
+ contents: write
name: 'Generate latest docs'
needs: test
if: github.event_name == 'push' && github.repository == 'google/guava'
runs-on: ubuntu-latest
steps:
- name: 'Check out repository'
- uses: actions/checkout@v2.4.0
- - name: 'Cache local Maven repository'
- uses: actions/cache@v2.1.7
- with:
- path: ~/.m2/repository
- key: maven-${{ hashFiles('**/pom.xml') }}
- restore-keys: |
- maven-
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9
- name: 'Set up JDK 11'
- uses: actions/setup-java@v2
+ uses: actions/setup-java@cd89f46ac9d01407894225f350157564c9c7cee2
+
with:
java-version: 11
distribution: 'zulu'
+ cache: 'maven'
- name: 'Generate latest docs'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml
new file mode 100644
index 000000000..6cd21417d
--- /dev/null
+++ b/.github/workflows/gradle-wrapper-validation.yml
@@ -0,0 +1,13 @@
+name: "Validate Gradle Wrapper"
+on: [push, pull_request]
+
+permissions:
+ contents: read
+
+jobs:
+ validation:
+ name: "Validation"
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9
+ - uses: gradle/wrapper-validation-action@56b90f209b02bf6d1deae490e9ef18b21a389cd4
diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml
new file mode 100644
index 000000000..f41e051c8
--- /dev/null
+++ b/.github/workflows/scorecard.yml
@@ -0,0 +1,72 @@
+# This workflow uses actions that are not certified by GitHub. They are provided
+# by a third-party and are governed by separate terms of service, privacy
+# policy, and support documentation.
+
+name: Scorecard supply-chain security
+on:
+ # For Branch-Protection check. Only the default branch is supported. See
+ # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
+ branch_protection_rule:
+ # To guarantee Maintained check is occasionally updated. See
+ # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
+ schedule:
+ - cron: '45 9 * * 0'
+ push:
+ branches: [ "master" ]
+
+# Declare default permissions as read only.
+permissions: read-all
+
+jobs:
+ analysis:
+ name: Scorecard analysis
+ runs-on: ubuntu-latest
+ permissions:
+ # Needed to upload the results to code-scanning dashboard.
+ security-events: write
+ # Needed to publish results and get a badge (see publish_results below).
+ id-token: write
+ # Uncomment the permissions below if installing in a private repository.
+ # contents: read
+ # actions: read
+
+ steps:
+ - name: "Checkout code"
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
+ with:
+ persist-credentials: false
+
+ - name: "Run analysis"
+ uses: ossf/scorecard-action@08b4669551908b1024bb425080c797723083c031 # v2.2.0
+ with:
+ results_file: results.sarif
+ results_format: sarif
+ # (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
+ # - you want to enable the Branch-Protection check on a *public* repository, or
+ # - you are installing Scorecard on a *private* repository
+ # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat.
+ # repo_token: ${{ secrets.SCORECARD_TOKEN }}
+
+ # Public repositories:
+ # - Publish results to OpenSSF REST API for easy access by consumers
+ # - Allows the repository to include the Scorecard badge.
+ # - See https://github.com/ossf/scorecard-action#publishing-results.
+ # For private repositories:
+ # - `publish_results` will always be set to `false`, regardless
+ # of the value entered here.
+ publish_results: true
+
+ # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
+ # format to the repository Actions tab.
+ - name: "Upload artifact"
+ uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
+ with:
+ name: SARIF file
+ path: results.sarif
+ retention-days: 5
+
+ # Upload the results to GitHub's code scanning dashboard.
+ - name: "Upload to code-scanning"
+ uses: github/codeql-action/upload-sarif@1813ca74c3faaa3a2da2070b9b8a0b3e7373a0d8 # v2.21.0
+ with:
+ sarif_file: results.sarif
diff --git a/Android.bp b/Android.bp
index 6a861aa81..5d79915a8 100644
--- a/Android.bp
+++ b/Android.bp
@@ -44,7 +44,6 @@ license {
"legacy_unencumbered",
],
license_text: [
- "COPYING",
"NOTICE",
],
}
@@ -176,18 +175,24 @@ java_library {
}
// Compile guava testlib
-java_library {
- name: "guava-android-testlib",
+java_library_host {
+ name: "guava-android-testlib-host",
srcs: ["android/guava-testlib/src/**/*.java"],
libs: [
"error_prone_annotations",
- "guava-android",
"guava-android-annotation-stubs",
+ "guava-android-host",
"junit",
],
+ java_version: "1.8",
errorprone: {
javacflags: [
"-Xep:ReturnValueIgnored:WARN",
],
},
}
+
+java_host_for_device {
+ name: "guava-android-testlib",
+ libs: ["guava-android-testlib-host"],
+}
diff --git a/COPYING b/LICENSE
index d64569567..d64569567 100644
--- a/COPYING
+++ b/LICENSE
diff --git a/METADATA b/METADATA
index 5b12c4896..d0267190d 100644
--- a/METADATA
+++ b/METADATA
@@ -9,11 +9,11 @@ third_party {
type: GIT
value: "https://github.com/google/guava.git"
}
- version: "31.1"
+ version: "v32.1.2"
license_type: NOTICE
last_upgrade_date {
- year: 2022
- month: 6
- day: 7
+ year: 2023
+ month: 8
+ day: 29
}
}
diff --git a/README.md b/README.md
index 8afda8fbb..ea6219ae4 100644
--- a/README.md
+++ b/README.md
@@ -2,13 +2,18 @@
[![Latest release](https://img.shields.io/github/release/google/guava.svg)](https://github.com/google/guava/releases/latest)
[![Build Status](https://github.com/google/guava/workflows/CI/badge.svg?branch=master)](https://github.com/google/guava/actions)
+[![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/7197/badge)](https://bestpractices.coreinfrastructure.org/projects/7197)
-Guava is a set of core Java libraries from Google that includes new collection types
-(such as multimap and multiset), immutable collections, a graph library, and
-utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! It
+
+
+Guava is a set of core Java libraries from Google that includes new collection
+types (such as multimap and multiset), immutable collections, a graph library,
+and utilities for concurrency, I/O, hashing, primitives, strings, and more! It
is widely used on most Java projects within Google, and widely used by many
other companies as well.
+
+
Guava comes in two flavors:
* The JRE flavor requires JDK 1.8 or higher.
@@ -22,8 +27,8 @@ Guava comes in two flavors:
Guava's Maven group ID is `com.google.guava`, and its artifact ID is `guava`.
Guava provides two different "flavors": one for use on a (Java 8+) JRE and one
for use on Android or by any library that wants to be compatible with Android.
-These flavors are specified in the Maven version field as either `31.1-jre` or
-`31.1-android`. For more about depending on Guava, see
+These flavors are specified in the Maven version field as either `32.1.2-jre` or
+`32.1.2-android`. For more about depending on Guava, see
[using Guava in your build].
To add a dependency on Guava using Maven, use the following:
@@ -32,9 +37,9 @@ To add a dependency on Guava using Maven, use the following:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
<!-- or, for Android: -->
- <version>31.1-android</version>
+ <version>32.1.2-android</version>
</dependency>
```
@@ -45,16 +50,16 @@ dependencies {
// Pick one:
// 1. Use Guava in your implementation only:
- implementation("com.google.guava:guava:31.1-jre")
+ implementation("com.google.guava:guava:32.1.2-jre")
// 2. Use Guava types in your public API:
- api("com.google.guava:guava:31.1-jre")
+ api("com.google.guava:guava:32.1.2-jre")
// 3. Android - Use Guava in your implementation only:
- implementation("com.google.guava:guava:31.1-android")
+ implementation("com.google.guava:guava:32.1.2-android")
// 4. Android - Use Guava types in your public API:
- api("com.google.guava:guava:31.1-android")
+ api("com.google.guava:guava:32.1.2-android")
}
```
@@ -113,10 +118,11 @@ flavor.
5. Our classes are not designed to protect against a malicious caller. You
should not use them for communication between trusted and untrusted code.
-6. For the mainline flavor, we test the libraries using only OpenJDK 8 and
- OpenJDK 11 on Linux. Some features, especially in `com.google.common.io`,
- may not work correctly in other environments. For the Android flavor, our
- unit tests also run on API level 15 (Ice Cream Sandwich).
+6. For the mainline flavor, we test the libraries using OpenJDK 8, 11, and 17
+ on Linux, with some additional testing on newer JDKs and on Windows. Some
+ features, especially in `com.google.common.io`, may not work correctly in
+ non-Linux environments. For the Android flavor, our unit tests also run on
+ API level 15 (Ice Cream Sandwich).
[guava-snapshot-api-docs]: https://guava.dev/releases/snapshot-jre/api/docs/
[guava-snapshot-api-diffs]: https://guava.dev/releases/snapshot-jre/api/diffs/
diff --git a/android/guava-bom/pom.xml b/android/guava-bom/pom.xml
index 736c02fd8..3ebb0bd92 100644
--- a/android/guava-bom/pom.xml
+++ b/android/guava-bom/pom.xml
@@ -8,7 +8,7 @@
<groupId>com.google.guava</groupId>
<artifactId>guava-bom</artifactId>
- <version>31.1-android</version>
+ <version>32.1.2-android</version>
<packaging>pom</packaging>
<parent>
diff --git a/android/guava-testlib/pom.xml b/android/guava-testlib/pom.xml
index 1fcf05867..84df803fc 100644
--- a/android/guava-testlib/pom.xml
+++ b/android/guava-testlib/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-android</version>
+ <version>32.1.2-android</version>
</parent>
<artifactId>guava-testlib</artifactId>
<name>Guava Testing Library</name>
@@ -19,6 +19,10 @@
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
+ <groupId>org.checkerframework</groupId>
+ <artifactId>checker-qual</artifactId>
+ </dependency>
+ <dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
</dependency>
@@ -34,7 +38,8 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <scope>compile</scope><!-- testlib must carry these transitively -->
+ <!-- *not* <scope>test</scope>; <scope>compile</scope> is right so that guava-testlib users get junit transitively. -->
+ <version>4.13.2</version>
</dependency>
<dependency>
<!--
@@ -42,7 +47,15 @@
-->
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
+ <version>${truth.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <!-- use the guava we're building. -->
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
</dependencies>
<build>
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java
index c5191be96..23420c375 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
import org.junit.Ignore;
@@ -41,6 +42,7 @@ public abstract class AbstractCollectionTester<E>
// TODO: dispose of this once collection is encapsulated.
@Override
+ @CanIgnoreReturnValue
protected Collection<E> resetContainer(Collection<E> newContents) {
collection = super.resetContainer(newContents);
return collection;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java
index b86ef1750..a3d0de047 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper;
import java.util.ArrayList;
import java.util.Arrays;
@@ -61,6 +62,7 @@ public abstract class AbstractContainerTester<C, E>
* @see #resetContainer(Object) resetContainer(C)
* @return the new container instance.
*/
+ @CanIgnoreReturnValue
protected C resetContainer() {
return resetContainer(getSubjectGenerator().createTestSubject());
}
@@ -75,6 +77,7 @@ public abstract class AbstractContainerTester<C, E>
* @return the new container instance
* @param newValue the new container instance
*/
+ @CanIgnoreReturnValue
protected C resetContainer(C newValue) {
container = newValue;
return container;
@@ -207,7 +210,7 @@ public abstract class AbstractContainerTester<C, E>
/**
* Returns the {@linkplain #getSampleElements() sample elements} as ordered by {@link
- * TestContainerGenerator#order(List)}. Tests should used this method only if they declare
+ * TestContainerGenerator#order(List)}. Tests should use this method only if they declare
* requirement {@link com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}.
*/
protected List<E> getOrderedElements() {
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java
index 5e6a583c4..b4e5b35e8 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java
@@ -31,6 +31,7 @@ import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Most of the logic for {@link IteratorTester} and {@link ListIteratorTester}.
@@ -146,9 +147,9 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
* {@link #previousElements} if the reverse is true, or -- overriding both of these -- {@code
* null} if {@code remove()} or {@code add()} has been called more recently than either. We use
* this to determine which stack to pop from on a call to {@code remove()} (or to pop from and
- * push to on a call to {@code set()}.
+ * push to on a call to {@code set()}).
*/
- Stack<E> stackWithLastReturnedElementAtTop = null;
+ @Nullable Stack<E> stackWithLastReturnedElementAtTop = null;
MultiExceptionListIterator(List<E> expectedElements) {
Helpers.addAll(nextElements, Helpers.reverse(expectedElements));
@@ -363,7 +364,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
}
private interface IteratorOperation {
- Object execute(Iterator<?> iterator);
+ @Nullable Object execute(Iterator<?> iterator);
}
/**
@@ -449,7 +450,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
private static final IteratorOperation REMOVE_METHOD =
new IteratorOperation() {
@Override
- public Object execute(Iterator<?> iterator) {
+ public @Nullable Object execute(Iterator<?> iterator) {
iterator.remove();
return null;
}
@@ -475,7 +476,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
final Object toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
- public Object execute(Iterator<?> iterator) {
+ public @Nullable Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<Object> rawIterator = (ListIterator<Object>) iterator;
rawIterator.add(toInsert);
@@ -488,7 +489,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
final E toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
- public Object execute(Iterator<?> iterator) {
+ public @Nullable Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<E> li = (ListIterator<E>) iterator;
li.set(toInsert);
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java
index 5e0de3ccc..2f3229717 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java
@@ -23,6 +23,7 @@ import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Ignore;
/**
@@ -167,7 +168,7 @@ public abstract class AbstractMapTester<K, V>
}
}
- private static boolean equal(Object a, Object b) {
+ private static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java
index dc1e1a067..adbc8dcc6 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java
@@ -18,6 +18,7 @@ package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* This abstract base class for testers allows the framework to inject needed information after
@@ -34,8 +35,8 @@ import junit.framework.TestCase;
public class AbstractTester<G> extends TestCase {
private G subjectGenerator;
private String suiteName;
- private Runnable setUp;
- private Runnable tearDown;
+ private @Nullable Runnable setUp;
+ private @Nullable Runnable tearDown;
// public so that it can be referenced in generated GWT tests.
@Override
@@ -54,7 +55,8 @@ public class AbstractTester<G> extends TestCase {
}
// public so that it can be referenced in generated GWT tests.
- public final void init(G subjectGenerator, String suiteName, Runnable setUp, Runnable tearDown) {
+ public final void init(
+ G subjectGenerator, String suiteName, @Nullable Runnable setUp, @Nullable Runnable tearDown) {
this.subjectGenerator = subjectGenerator;
this.suiteName = suiteName;
this.setUp = setUp;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java b/android/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
index 384770989..cf3a11eab 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
@@ -18,6 +18,7 @@ package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Simple base class to verify that we handle generics correctly.
@@ -38,7 +39,7 @@ public class BaseComparable implements Comparable<BaseComparable>, Serializable
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
if (other == null) {
return false;
} else if (other instanceof BaseComparable) {
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java b/android/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java
index d80f5a93c..b96e1d07b 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java
@@ -24,7 +24,7 @@ import com.google.common.annotations.GwtCompatible;
* collection generator.
*
* <p>{@code GwtTestSuiteGenerator} expects every {@code DerivedIterator} implementation to provide
- * a one-arg constructor accepting its inner generator as an argument). This requirement enables it
+ * a one-arg constructor accepting its inner generator as an argument. This requirement enables it
* to generate source code (since GWT cannot use reflection to generate the suites).
*
* @author Chris Povirk
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java b/android/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java
new file mode 100644
index 000000000..80379ccb8
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2021 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.testing;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.google.common.annotations.GwtCompatible;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import javax.annotation.Nonnull;
+import javax.annotation.meta.TypeQualifierDefault;
+
+/**
+ * Marks all "top-level" types as non-null in a way that is recognized by Kotlin. Note that this
+ * unfortunately includes type-variable usages, so we also provide {@link ParametricNullness} to
+ * "undo" it as best we can.
+ */
+@GwtCompatible
+@Retention(RUNTIME)
+@Target(TYPE)
+@TypeQualifierDefault({FIELD, METHOD, PARAMETER})
+@Nonnull
+@interface ElementTypesAreNonnullByDefault {}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java b/android/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java
index db086aa30..bf15135dc 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java
@@ -24,6 +24,7 @@ import com.google.common.collect.testing.features.ConflictingRequirementsExcepti
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import com.google.common.collect.testing.features.TesterRequirements;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@@ -38,6 +39,7 @@ import java.util.logging.Logger;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests the object generated
@@ -61,12 +63,13 @@ public abstract class FeatureSpecificTestSuiteBuilder<
// Test Data
- private G subjectGenerator;
+ private @Nullable G subjectGenerator;
// Gets run before every test.
private Runnable setUp;
// Gets run at the conclusion of every test.
private Runnable tearDown;
+ @CanIgnoreReturnValue
protected B usingGenerator(G subjectGenerator) {
this.subjectGenerator = subjectGenerator;
return self();
@@ -76,6 +79,7 @@ public abstract class FeatureSpecificTestSuiteBuilder<
return subjectGenerator;
}
+ @CanIgnoreReturnValue
public B withSetUp(Runnable setUp) {
this.setUp = setUp;
return self();
@@ -85,6 +89,7 @@ public abstract class FeatureSpecificTestSuiteBuilder<
return setUp;
}
+ @CanIgnoreReturnValue
public B withTearDown(Runnable tearDown) {
this.tearDown = tearDown;
return self();
@@ -102,10 +107,12 @@ public abstract class FeatureSpecificTestSuiteBuilder<
* Configures this builder to produce tests appropriate for the given features. This method may be
* called more than once to add features in multiple groups.
*/
+ @CanIgnoreReturnValue
public B withFeatures(Feature<?>... features) {
return withFeatures(Arrays.asList(features));
}
+ @CanIgnoreReturnValue
public B withFeatures(Iterable<? extends Feature<?>> features) {
for (Feature<?> feature : features) {
this.features.add(feature);
@@ -119,9 +126,10 @@ public abstract class FeatureSpecificTestSuiteBuilder<
// Name
- private String name;
+ private @Nullable String name;
/** Configures this builder produce a TestSuite with the given name. */
+ @CanIgnoreReturnValue
public B named(String name) {
if (name.contains("(")) {
throw new IllegalArgumentException(
@@ -147,10 +155,12 @@ public abstract class FeatureSpecificTestSuiteBuilder<
* semantics of an implementation disagree in unforeseen ways with the semantics expected by a
* test, or to keep dependent builds clean in spite of an erroneous test.
*/
+ @CanIgnoreReturnValue
public B suppressing(Method... methods) {
return suppressing(Arrays.asList(methods));
}
+ @CanIgnoreReturnValue
public B suppressing(Collection<Method> methods) {
suppressedTests.addAll(methods);
return self();
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/Helpers.java b/android/guava-testlib/src/com/google/common/collect/testing/Helpers.java
index aac71cc4e..290e8e300 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/Helpers.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/Helpers.java
@@ -23,8 +23,11 @@ import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Method;
+import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -39,38 +42,41 @@ import java.util.Map.Entry;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class Helpers {
// Clone of Objects.equal
- static boolean equal(Object a, Object b) {
+ static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
// Clone of Lists.newArrayList
- public static <E> List<E> copyToList(Iterable<? extends E> elements) {
+ public static <E extends @Nullable Object> List<E> copyToList(Iterable<? extends E> elements) {
List<E> list = new ArrayList<>();
addAll(list, elements);
return list;
}
- public static <E> List<E> copyToList(E[] elements) {
+ public static <E extends @Nullable Object> List<E> copyToList(E[] elements) {
return copyToList(Arrays.asList(elements));
}
// Clone of Sets.newLinkedHashSet
- public static <E> Set<E> copyToSet(Iterable<? extends E> elements) {
+ public static <E extends @Nullable Object> Set<E> copyToSet(Iterable<? extends E> elements) {
Set<E> set = new LinkedHashSet<>();
addAll(set, elements);
return set;
}
- public static <E> Set<E> copyToSet(E[] elements) {
+ public static <E extends @Nullable Object> Set<E> copyToSet(E[] elements) {
return copyToSet(Arrays.asList(elements));
}
// Would use Maps.immutableEntry
- public static <K, V> Entry<K, V> mapEntry(K key, V value) {
+ public static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> mapEntry(
+ K key, V value) {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
@@ -180,7 +186,9 @@ public class Helpers {
}
}
- public static <E> boolean addAll(Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
+ @CanIgnoreReturnValue
+ public static <E extends @Nullable Object> boolean addAll(
+ Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
boolean modified = false;
for (E e : elementsToAdd) {
modified |= addTo.add(e);
@@ -250,17 +258,26 @@ public class Helpers {
throw assertionFailedError;
}
- public static <K, V> Comparator<Entry<K, V>> entryComparator(
- Comparator<? super K> keyComparator) {
- return new Comparator<Entry<K, V>>() {
- @Override
- @SuppressWarnings("unchecked") // no less safe than putting it in the map!
- public int compare(Entry<K, V> a, Entry<K, V> b) {
+ private static class EntryComparator<K extends @Nullable Object, V extends @Nullable Object>
+ implements Comparator<Entry<K, V>> {
+ final @Nullable Comparator<? super K> keyComparator;
+
+ public EntryComparator(@Nullable Comparator<? super K> keyComparator) {
+ this.keyComparator = keyComparator;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked") // no less safe than putting it in the map!
+ public int compare(Entry<K, V> a, Entry<K, V> b) {
return (keyComparator == null)
? ((Comparable) a.getKey()).compareTo(b.getKey())
: keyComparator.compare(a.getKey(), b.getKey());
- }
- };
+ }
+ }
+
+ public static <K, V> Comparator<Entry<K, V>> entryComparator(
+ @Nullable Comparator<? super K> keyComparator) {
+ return new EntryComparator<K, V>(keyComparator);
}
/**
@@ -290,7 +307,7 @@ public class Helpers {
* valuesInExpectedOrder.get(i)} and {@code tj = valuesInExpectedOrder.get(j)}.
* </ul>
*/
- public static <T> void testComparator(
+ public static <T extends @Nullable Object> void testComparator(
Comparator<? super T> comparator, List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
@@ -345,14 +362,47 @@ public class Helpers {
* @param delta the difference between the true size of the collection and the values returned by
* the size method
*/
- public static <T> Collection<T> misleadingSizeCollection(int delta) {
+ public static <T extends @Nullable Object> Collection<T> misleadingSizeCollection(int delta) {
// It would be nice to be able to return a real concurrent
// collection like ConcurrentLinkedQueue, so that e.g. concurrent
// iteration would work, but that would not be GWT-compatible.
- return new ArrayList<T>() {
+ // We are not "just" inheriting from ArrayList here as this doesn't work for J2kt.
+ return new AbstractList<T>() {
+ ArrayList<T> data = new ArrayList<>();
+
@Override
public int size() {
- return Math.max(0, super.size() + delta);
+ return Math.max(0, data.size() + delta);
+ }
+
+ @Override
+ public T get(int index) {
+ return data.get(index);
+ }
+
+ @Override
+ public T set(int index, T element) {
+ return data.set(index, element);
+ }
+
+ @Override
+ public boolean add(T element) {
+ return data.add(element);
+ }
+
+ @Override
+ public void add(int index, T element) {
+ data.add(index, element);
+ }
+
+ @Override
+ public T remove(int index) {
+ return data.remove(index);
+ }
+
+ @Override
+ public @Nullable Object[] toArray() {
+ return data.toArray();
}
};
}
@@ -363,7 +413,8 @@ public class Helpers {
* equals. This is used for testing unmodifiable collections of map entries; for example, it
* should not be possible to access the raw (modifiable) map entry via a nefarious equals method.
*/
- public static <K, V> Entry<K, V> nefariousMapEntry(K key, V value) {
+ public static <K extends @Nullable Object, V extends @Nullable Object>
+ Entry<K, V> nefariousMapEntry(K key, V value) {
return new Entry<K, V>() {
@Override
public K getKey() {
@@ -382,7 +433,7 @@ public class Helpers {
@SuppressWarnings("unchecked")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof Entry) {
Entry<K, V> e = (Entry<K, V>) o;
e.setValue(value); // muhahaha!
@@ -406,7 +457,7 @@ public class Helpers {
};
}
- static <E> List<E> castOrCopyToList(Iterable<E> iterable) {
+ static <E extends @Nullable Object> List<E> castOrCopyToList(Iterable<E> iterable) {
if (iterable instanceof List) {
return (List<E>) iterable;
}
@@ -426,6 +477,7 @@ public class Helpers {
}
};
+ @J2ktIncompatible
public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey(
List<Entry<K, V>> insertionOrder) {
sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER));
@@ -444,7 +496,7 @@ public class Helpers {
* values, it lies outside the submap/submultiset ranges we test, and the variety of tests that
* exercise null handling fail on those subcollections.
*/
- public abstract static class NullsBefore implements Comparator<String>, Serializable {
+ public abstract static class NullsBefore implements Comparator<@Nullable String>, Serializable {
/*
* We don't serialize this class in GWT, so we don't care about whether GWT will serialize this
* field.
@@ -460,7 +512,7 @@ public class Helpers {
}
@Override
- public int compare(String lhs, String rhs) {
+ public int compare(@Nullable String lhs, @Nullable String rhs) {
if (lhs == rhs) {
return 0;
}
@@ -484,7 +536,7 @@ public class Helpers {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof NullsBefore) {
NullsBefore other = (NullsBefore) obj;
return justAfterNull.equals(other.justAfterNull);
@@ -514,6 +566,7 @@ public class Helpers {
}
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public static Method getMethod(Class<?> clazz, String name) {
try {
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java b/android/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java
index 15d48dbbd..816a97377 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code Iterable} which throws an exception on all invocations of the {@link
@@ -63,7 +64,7 @@ public final class MinimalIterable<E> implements Iterable<E> {
return (MinimalIterable) of(elements.toArray());
}
- private Iterator<E> iterator;
+ private @Nullable Iterator<E> iterator;
private MinimalIterable(Iterator<E> iterator) {
this.iterator = iterator;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java b/android/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java
index 9a87d244d..4027684b4 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java
@@ -22,6 +22,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A simplistic set which implements the bare minimum so that it can be used in tests without
@@ -63,7 +64,7 @@ public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> {
*/
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return (this.size() == that.size()) && this.containsAll(that);
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/Platform.java b/android/guava-testlib/src/com/google/common/collect/testing/Platform.java
index a2c020c91..cfc7ac3b2 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/Platform.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/Platform.java
@@ -34,7 +34,7 @@ final class Platform {
// Class.cast is not supported in GWT. This method is a no-op in GWT.
static void checkCast(Class<?> clazz, Object obj) {
- clazz.cast(obj);
+ Object unused = clazz.cast(obj);
}
static String format(String template, Object... args) {
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java b/android/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java
index ac62d44b6..c94b81998 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java
@@ -22,6 +22,7 @@ import com.google.common.collect.testing.testers.QueueOfferTester;
import com.google.common.collect.testing.testers.QueuePeekTester;
import com.google.common.collect.testing.testers.QueuePollTester;
import com.google.common.collect.testing.testers.QueueRemoveTester;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.List;
@@ -45,6 +46,7 @@ public final class QueueTestSuiteBuilder<E>
* collection that's both a queue and a list, to avoid running the common collection tests twice.
* By default, collection tests do run.
*/
+ @CanIgnoreReturnValue
public QueueTestSuiteBuilder<E> skipCollectionTests() {
runCollectionTests = false;
return this;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java b/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java
index 5856e3b54..c284619da 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtIncompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Collection;
@@ -28,6 +29,7 @@ import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A wrapper around {@code TreeMap} that aggressively checks to see if keys are mutually comparable.
@@ -75,12 +77,12 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> ceilingEntry(K key) {
+ public @Nullable Entry<K, V> ceilingEntry(K key) {
return delegate.ceilingEntry(checkValid(key));
}
@Override
- public K ceilingKey(K key) {
+ public @Nullable K ceilingKey(K key) {
return delegate.ceilingKey(checkValid(key));
}
@@ -162,7 +164,7 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> firstEntry() {
+ public @Nullable Entry<K, V> firstEntry() {
return delegate.firstEntry();
}
@@ -172,17 +174,17 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> floorEntry(K key) {
+ public @Nullable Entry<K, V> floorEntry(K key) {
return delegate.floorEntry(checkValid(key));
}
@Override
- public K floorKey(K key) {
+ public @Nullable K floorKey(K key) {
return delegate.floorKey(checkValid(key));
}
@Override
- public V get(Object key) {
+ public @Nullable V get(Object key) {
return delegate.get(checkValid(key));
}
@@ -197,12 +199,12 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> higherEntry(K key) {
+ public @Nullable Entry<K, V> higherEntry(K key) {
return delegate.higherEntry(checkValid(key));
}
@Override
- public K higherKey(K key) {
+ public @Nullable K higherKey(K key) {
return delegate.higherKey(checkValid(key));
}
@@ -217,7 +219,7 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> lastEntry() {
+ public @Nullable Entry<K, V> lastEntry() {
return delegate.lastEntry();
}
@@ -227,12 +229,12 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> lowerEntry(K key) {
+ public @Nullable Entry<K, V> lowerEntry(K key) {
return delegate.lowerEntry(checkValid(key));
}
@Override
- public K lowerKey(K key) {
+ public @Nullable K lowerKey(K key) {
return delegate.lowerKey(checkValid(key));
}
@@ -242,17 +244,17 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> pollFirstEntry() {
+ public @Nullable Entry<K, V> pollFirstEntry() {
return delegate.pollFirstEntry();
}
@Override
- public Entry<K, V> pollLastEntry() {
+ public @Nullable Entry<K, V> pollLastEntry() {
return delegate.pollLastEntry();
}
@Override
- public V put(K key, V value) {
+ public @Nullable V put(K key, V value) {
return delegate.put(checkValid(key), value);
}
@@ -265,7 +267,7 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public V remove(Object key) {
+ public @Nullable V remove(Object key) {
return delegate.remove(checkValid(key));
}
@@ -300,16 +302,17 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
return delegate.values();
}
+ @CanIgnoreReturnValue
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
K k = (K) t;
- comparator().compare(k, k);
+ int unused = comparator().compare(k, k);
return t;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return delegate.equals(obj);
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java b/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java
index 91d9fd9f7..ddb628656 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtIncompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
@@ -24,6 +25,7 @@ import java.util.Iterator;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A wrapper around {@code TreeSet} that aggressively checks to see if elements are mutually
@@ -81,7 +83,7 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E ceiling(E e) {
+ public @Nullable E ceiling(E e) {
return delegate.ceiling(checkValid(e));
}
@@ -126,7 +128,7 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E floor(E e) {
+ public @Nullable E floor(E e) {
return delegate.floor(checkValid(e));
}
@@ -141,7 +143,7 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E higher(E e) {
+ public @Nullable E higher(E e) {
return delegate.higher(checkValid(e));
}
@@ -161,17 +163,17 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E lower(E e) {
+ public @Nullable E lower(E e) {
return delegate.lower(checkValid(e));
}
@Override
- public E pollFirst() {
+ public @Nullable E pollFirst() {
return delegate.pollFirst();
}
@Override
- public E pollLast() {
+ public @Nullable E pollLast() {
return delegate.pollLast();
}
@@ -228,16 +230,17 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
return delegate.toArray(a);
}
+ @CanIgnoreReturnValue
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
E e = (E) t;
- comparator().compare(e, e);
+ int unused = comparator().compare(e, e);
return t;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return delegate.equals(obj);
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/SampleElements.java b/android/guava-testlib/src/com/google/common/collect/testing/SampleElements.java
index 400107dc5..9fed1fbe8 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/SampleElements.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/SampleElements.java
@@ -21,6 +21,7 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A container class for the five sample elements we need for testing.
@@ -143,7 +144,7 @@ public class SampleElements<E> implements Iterable<E> {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof Collider && ((Collider) obj).value == value;
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java b/android/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java
index 7944aaa6a..4a290860e 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java
@@ -30,6 +30,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests a SortedMap
@@ -88,12 +89,12 @@ public class SortedMapTestSuiteBuilder<K, V> extends MapTestSuiteBuilder<K, V> {
* To avoid infinite recursion, test suites with these marker features won't have derived suites
* created for them.
*/
- enum NoRecurse implements Feature<Void> {
+ enum NoRecurse implements Feature<@Nullable Void> {
SUBMAP,
DESCENDING;
@Override
- public Set<Feature<? super Void>> getImpliedFeatures() {
+ public Set<Feature<? super @Nullable Void>> getImpliedFeatures() {
return Collections.emptySet();
}
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java b/android/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java
index 69d263bda..3e1d3b4ee 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An unhashable object to be used in testing as values in our collections.
@@ -32,7 +33,7 @@ public class UnhashableObject implements Comparable<UnhashableObject> {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object instanceof UnhashableObject) {
UnhashableObject that = (UnhashableObject) object;
return this.value == that.value;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java b/android/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java
index 6203e5148..cc627bb5c 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java
@@ -24,6 +24,7 @@ import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* When describing the features of the collection produced by a given generator (i.e. in a call to
@@ -59,7 +60,7 @@ public enum CollectionSize implements Feature<Collection>, Comparable<Collection
ANY(ZERO, ONE, SEVERAL);
private final Set<Feature<? super Collection>> implied;
- private final Integer numElements;
+ private final @Nullable Integer numElements;
CollectionSize(int numElements) {
this.implied = Collections.emptySet();
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java b/android/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java
index 2d11a0863..ce5b73f47 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java
@@ -18,6 +18,7 @@ package com.google.common.collect.testing.features;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.Helpers;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
@@ -55,6 +56,7 @@ public class FeatureUtil {
* @param features the set of features to expand
* @return the same set of features, expanded with all implied features
*/
+ @CanIgnoreReturnValue
public static Set<Feature<?>> addImpliedFeatures(Set<Feature<?>> features) {
Queue<Feature<?>> queue = new ArrayDeque<>(features);
while (!queue.isEmpty()) {
@@ -254,6 +256,7 @@ public class FeatureUtil {
* @throws ConflictingRequirementsException if the additional requirements are inconsistent with
* the existing requirements
*/
+ @CanIgnoreReturnValue
private static TesterRequirements incorporateRequirements(
TesterRequirements requirements, TesterRequirements moreRequirements, Object source)
throws ConflictingRequirementsException {
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java b/android/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java
index 4780b1bf5..2290f296c 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import java.util.Collections;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Encapsulates the constraints that a class under test must satisfy in order for a tester method to
@@ -54,7 +55,7 @@ public final class TesterRequirements {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/features/package-info.java b/android/guava-testlib/src/com/google/common/collect/testing/features/package-info.java
new file mode 100644
index 000000000..88b611ca4
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/collect/testing/features/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.features;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java b/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java
index 7f649e757..92d82c6af 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java
@@ -23,6 +23,7 @@ import com.google.common.collect.Multimap;
import com.google.common.collect.testing.AbstractContainerTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
@@ -121,11 +122,13 @@ public abstract class AbstractMultimapTester<K, V, M extends Multimap<K, V>>
// TODO: dispose of this once collection is encapsulated.
@Override
+ @CanIgnoreReturnValue
protected M resetContainer(M newContents) {
multimap = super.resetContainer(newContents);
return multimap;
}
+ @CanIgnoreReturnValue
protected Multimap<K, V> resetContainer(Entry<K, V>... newContents) {
multimap = super.resetContainer(getSubjectGenerator().create((Object[]) newContents));
return multimap;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java b/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java
index 03039706b..67d29198f 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java
@@ -27,7 +27,7 @@ import org.junit.Ignore;
/**
* A generic JUnit test which tests multiset-specific serialization. Can't be invoked directly;
- * please see {@link com.google.common.collect.testing.MultisetTestSuiteBuilder}.
+ * please see {@link MultisetTestSuiteBuilder}.
*
* @author Louis Wasserman
*/
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java b/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java
index d5e69638f..878972c81 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java
@@ -24,6 +24,7 @@ import static java.util.Collections.nCopies;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.junit.Ignore;
/**
@@ -47,6 +48,7 @@ public class MultisetSetCountConditionallyTester<E> extends AbstractMultisetSetC
setCount(element, count);
}
+ @CanIgnoreReturnValue
private boolean setCount(E element, int count) {
return getMultiset().setCount(element, getMultiset().count(element), count);
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java b/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java
index ec5436dda..9cd7acee7 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.junit.Ignore;
/**
@@ -41,6 +42,7 @@ public class MultisetSetCountUnconditionallyTester<E> extends AbstractMultisetSe
setCount(element, count);
}
+ @CanIgnoreReturnValue
private int setCount(E element, int count) {
return getMultiset().setCount(element, count);
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/google/package-info.java b/android/guava-testlib/src/com/google/common/collect/testing/google/package-info.java
new file mode 100644
index 000000000..57c1a21bb
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/collect/testing/google/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.google;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/package-info.java b/android/guava-testlib/src/com/google/common/collect/testing/package-info.java
new file mode 100644
index 000000000..15086f3ae
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/collect/testing/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing;
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java
index 46bd52942..05f72dfd3 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java
@@ -23,6 +23,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Ignore;
/**
@@ -34,7 +35,7 @@ import org.junit.Ignore;
@Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
public abstract class AbstractListIndexOfTester<E> extends AbstractListTester<E> {
/** Override to call {@code indexOf()} or {@code lastIndexOf()}. */
- protected abstract int find(Object o);
+ protected abstract int find(@Nullable Object o);
/** Override to return "indexOf" or "lastIndexOf()" for use in failure messages. */
protected abstract String getMethodName();
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java
index 848fdd663..c2a0b68ef 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java
@@ -52,7 +52,8 @@ public class CollectionCreationTester<E> extends AbstractCollectionTester<E> {
E[] array = createArrayWithNullElement();
try {
- getSubjectGenerator().create(array);
+ // TODO(kak): remove unused capture
+ Object unused = getSubjectGenerator().create(array);
fail("Creating a collection containing null should fail");
} catch (NullPointerException expected) {
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java
index 0d5909737..75fc8b677 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java
@@ -29,6 +29,7 @@ import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
+import java.util.AbstractSet;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -92,7 +93,7 @@ public class CollectionRemoveAllTester<E> extends AbstractCollectionTester<E> {
}
}
- /** Trigger the {@code other.size() >= this.size()} case in {@link AbstractSet#removeAll()}. */
+ /** Trigger the {@code other.size() >= this.size()} case in {@link AbstractSet#removeAll}. */
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_somePresentLargeCollectionToRemove() {
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java
index 6cf5be232..955123658 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java
@@ -25,6 +25,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import org.junit.Ignore;
@@ -130,6 +131,7 @@ public class ConcurrentMapPutIfAbsentTester<K, V> extends AbstractMapTester<K, V
"Should not contain null after unsupported putIfAbsent(present, null)");
}
+ @CanIgnoreReturnValue
private V putIfAbsent(Entry<K, V> entry) {
return getMap().putIfAbsent(entry.getKey(), entry.getValue());
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java
index 553b69358..7a60add7c 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java
@@ -326,7 +326,7 @@ public class ListSubListTester<E> extends AbstractListTester<E> {
/**
* Returns the {@link Method} instance for {@link
- * #testSubList_originalListSetAffectsSubListLargeList()} ()} so that tests of {@link
+ * #testSubList_originalListSetAffectsSubListLargeList()} so that tests of {@link
* CopyOnWriteArrayList} can suppress them with {@code
* FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570631">Sun bug 6570631</a> is fixed.
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java
index c9a745d4a..b123f5bc5 100644
--- a/android/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java
@@ -28,6 +28,7 @@ import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -245,6 +246,7 @@ public class MapPutTester<K, V> extends AbstractMapTester<K, V> {
expectAdded(nullKeyValueEntry);
}
+ @CanIgnoreReturnValue
private V put(Entry<K, V> entry) {
return getMap().put(entry.getKey(), entry.getValue());
}
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java
new file mode 100644
index 000000000..fa9439065
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.testers;
diff --git a/android/guava-testlib/src/com/google/common/escape/testing/package-info.java b/android/guava-testlib/src/com/google/common/escape/testing/package-info.java
index 869884734..6b5061469 100644
--- a/android/guava-testlib/src/com/google/common/escape/testing/package-info.java
+++ b/android/guava-testlib/src/com/google/common/escape/testing/package-info.java
@@ -17,7 +17,7 @@
/**
* Testing utilities for use in tests of {@code com.google.common.escape}.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java b/android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
index 1e31bbfb4..67179415d 100644
--- a/android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
+++ b/android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
@@ -20,8 +20,8 @@ import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.testing.AbstractPackageSanityTests.Chopper.suffix;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
@@ -101,10 +101,10 @@ import org.junit.Test;
* @author Ben Yu
* @since 14.0
*/
-@Beta
// TODO: Switch to JUnit 4 and use @Parameterized and @BeforeClass
// Note: @Test annotations are deliberate, as some subclasses specify @RunWith(JUnit4).
@GwtIncompatible
+@J2ktIncompatible
@J2ObjCIncompatible // com.google.common.reflect.ClassPath
public abstract class AbstractPackageSanityTests extends TestCase {
@@ -325,7 +325,7 @@ public abstract class AbstractPackageSanityTests extends TestCase {
/**
* Finds the classes not ending with a test suffix and not covered by an explicit test whose name
- * is {@code explicitTestName}.
+ * is {@code explicitTestNames}.
*/
@VisibleForTesting
List<Class<?>> findClassesToTest(
diff --git a/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java b/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java
index 26f4df474..a52373d64 100644
--- a/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java
+++ b/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java
@@ -19,6 +19,7 @@ package com.google.common.testing;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Defaults;
@@ -142,7 +143,7 @@ import java.util.logging.Logger;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Supplies an arbitrary "default" instance for a wide range of types, often useful in testing
@@ -167,6 +168,8 @@ import javax.annotation.CheckForNull;
* @since 12.0
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
public final class ArbitraryInstances {
private static final Ordering<Field> BY_FIELD_NAME =
@@ -326,8 +329,7 @@ public final class ArbitraryInstances {
}
@SuppressWarnings("unchecked") // it's a subtype map
- @CheckForNull
- private static <T> Class<? extends T> getImplementation(Class<T> type) {
+ private static <T> @Nullable Class<? extends T> getImplementation(Class<T> type) {
return (Class<? extends T>) implementations.get(type);
}
@@ -337,8 +339,7 @@ public final class ArbitraryInstances {
* Returns an arbitrary instance for {@code type}, or {@code null} if no arbitrary instance can be
* determined.
*/
- @CheckForNull
- public static <T> T get(Class<T> type) {
+ public static <T> @Nullable T get(Class<T> type) {
T defaultValue = DEFAULTS.getInstance(type);
if (defaultValue != null) {
return defaultValue;
@@ -349,7 +350,7 @@ public final class ArbitraryInstances {
}
if (type.isEnum()) {
T[] enumConstants = type.getEnumConstants();
- return (enumConstants.length == 0) ? null : enumConstants[0];
+ return (enumConstants == null || enumConstants.length == 0) ? null : enumConstants[0];
}
if (type.isArray()) {
return createEmptyArray(type);
@@ -385,8 +386,7 @@ public final class ArbitraryInstances {
}
}
- @CheckForNull
- private static <T> T arbitraryConstantInstanceOrNull(Class<T> type) {
+ private static <T> @Nullable T arbitraryConstantInstanceOrNull(Class<T> type) {
Field[] fields = type.getDeclaredFields();
Arrays.sort(fields, BY_FIELD_NAME);
for (Field field : fields) {
@@ -497,11 +497,12 @@ public final class ArbitraryInstances {
}
// Always equal is a valid total ordering. And it works for any Object.
- private static final class AlwaysEqual extends Ordering<Object> implements Serializable {
+ private static final class AlwaysEqual extends Ordering<@Nullable Object>
+ implements Serializable {
private static final AlwaysEqual INSTANCE = new AlwaysEqual();
@Override
- public int compare(Object o1, Object o2) {
+ public int compare(@Nullable Object o1, @Nullable Object o2) {
return 0;
}
diff --git a/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java b/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
index 093178545..3a41a7fe1 100644
--- a/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
@@ -21,8 +21,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.testing.NullPointerTester.isNullable;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
@@ -41,6 +41,7 @@ import com.google.common.reflect.TypeToken;
import com.google.common.testing.NullPointerTester.Visibility;
import com.google.common.testing.RelationshipTester.Item;
import com.google.common.testing.RelationshipTester.ItemReporter;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@@ -50,9 +51,9 @@ import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
-import javax.annotation.CheckForNull;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester that runs automated sanity tests for any given class. A typical use case is to test static
@@ -78,8 +79,8 @@ import junit.framework.AssertionFailedError;
* @author Ben Yu
* @since 14.0
*/
-@Beta
@GwtIncompatible
+@J2ktIncompatible
public final class ClassSanityTester {
private static final Ordering<Invokable<?, ?>> BY_METHOD_NAME =
@@ -133,6 +134,7 @@ public final class ClassSanityTester {
* Object#equals} because more than one sample instances are needed for testing inequality. To set
* distinct values for equality testing, use {@link #setDistinctValues} instead.
*/
+ @CanIgnoreReturnValue
public <T> ClassSanityTester setDefault(Class<T> type, T value) {
nullPointerTester.setDefault(type, value);
defaultValues.putInstance(type, value);
@@ -154,6 +156,7 @@ public final class ClassSanityTester {
* @return this tester instance
* @since 17.0
*/
+ @CanIgnoreReturnValue
public <T> ClassSanityTester setDistinctValues(Class<T> type, T value1, T value2) {
checkNotNull(type);
checkNotNull(value1);
@@ -334,13 +337,14 @@ public final class ClassSanityTester {
* @return The instantiated instance, or {@code null} if the class has no non-private constructor
* or factory method to be constructed.
*/
- @CheckForNull
- <T> T instantiate(Class<T> cls)
- throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException,
+ <T> @Nullable T instantiate(Class<T> cls)
+ throws ParameterNotInstantiableException,
+ IllegalAccessException,
+ InvocationTargetException,
FactoryMethodReturnsNullException {
if (cls.isEnum()) {
T[] constants = cls.getEnumConstants();
- if (constants.length > 0) {
+ if (constants != null && constants.length > 0) {
return constants[0];
} else {
return null;
@@ -383,8 +387,7 @@ public final class ClassSanityTester {
* class, preventing its methods from being accessible.
* @throws InvocationTargetException if a static method threw exception.
*/
- @CheckForNull
- private <T> T instantiate(Invokable<?, ? extends T> factory)
+ private <T> @Nullable T instantiate(Invokable<?, ? extends T> factory)
throws ParameterNotInstantiableException, InvocationTargetException, IllegalAccessException {
return invoke(factory, getDummyArguments(factory));
}
@@ -429,6 +432,7 @@ public final class ClassSanityTester {
*
* @return this tester object
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester thatReturn(Class<?> returnType) {
this.returnTypeToTest = returnType;
return this;
@@ -442,6 +446,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testNulls() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
Object instance = instantiate(factory);
@@ -470,6 +475,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testEquals() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
try {
@@ -489,6 +495,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testSerializable() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
Object instance = instantiate(factory);
@@ -514,6 +521,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testEqualsAndSerializable() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
try {
@@ -568,7 +576,7 @@ public final class ClassSanityTester {
IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException {
List<Parameter> params = factory.getParameters();
List<FreshValueGenerator> argGenerators = Lists.newArrayListWithCapacity(params.size());
- List<Object> args = Lists.newArrayListWithCapacity(params.size());
+ List<@Nullable Object> args = Lists.newArrayListWithCapacity(params.size());
for (Parameter param : params) {
FreshValueGenerator generator = newFreshValueGenerator();
argGenerators.add(generator);
@@ -626,7 +634,7 @@ public final class ClassSanityTester {
Object shouldBeEqualArg = generateDummyArg(param, newFreshValueGenerator());
if (arg != shouldBeEqualArg
&& Objects.equal(arg, shouldBeEqualArg)
- && hashCodeInsensitiveToArgReference(factory, args, i, shouldBeEqualArg)
+ && hashCodeInsensitiveToArgReference(factory, args, i, checkNotNull(shouldBeEqualArg))
&& hashCodeInsensitiveToArgReference(
factory, args, i, generateDummyArg(param, newFreshValueGenerator()))) {
// If the implementation uses identityHashCode(), referential equality is
@@ -664,8 +672,7 @@ public final class ClassSanityTester {
return generator;
}
- @CheckForNull
- private static Object generateDummyArg(Parameter param, FreshValueGenerator generator)
+ private static @Nullable Object generateDummyArg(Parameter param, FreshValueGenerator generator)
throws ParameterNotInstantiableException {
if (isNullable(param)) {
return null;
@@ -708,9 +715,9 @@ public final class ClassSanityTester {
for (Invokable<?, ?> factory : factories) {
factory.setAccessible(true);
}
- // Sorts methods/constructors with least number of parameters first since it's likely easier to
- // fill dummy parameter values for them. Ties are broken by name then by the string form of the
- // parameter list.
+ // Sorts methods/constructors with the least number of parameters first since it's likely easier
+ // to fill dummy parameter values for them. Ties are broken by name then by the string form of
+ // the parameter list.
return BY_NUMBER_OF_PARAMETERS
.compound(BY_METHOD_NAME)
.compound(BY_PARAMETERS)
@@ -761,8 +768,7 @@ public final class ClassSanityTester {
return instance;
}
- @CheckForNull
- private static <T> T invoke(Invokable<?, ? extends T> factory, List<?> args)
+ private static <T> @Nullable T invoke(Invokable<?, ? extends T> factory, List<?> args)
throws InvocationTargetException, IllegalAccessException {
T returnValue = factory.invoke(null, args.toArray());
if (returnValue == null) {
@@ -828,7 +834,7 @@ public final class ClassSanityTester {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof SerializableDummyProxy;
}
diff --git a/android/guava-testlib/src/com/google/common/testing/ClusterException.java b/android/guava-testlib/src/com/google/common/testing/ClusterException.java
index 7665ab1d4..2b8d4eb77 100644
--- a/android/guava-testlib/src/com/google/common/testing/ClusterException.java
+++ b/android/guava-testlib/src/com/google/common/testing/ClusterException.java
@@ -59,20 +59,21 @@ import java.util.Collections;
* @author Luiz-Otavio Zorzella
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
final class ClusterException extends RuntimeException {
- public final Collection<? extends Throwable> exceptions;
+ final Collection<? extends Throwable> exceptions;
private ClusterException(Collection<? extends Throwable> exceptions) {
super(
exceptions.size() + " exceptions were thrown. The first exception is listed as a cause.",
exceptions.iterator().next());
- ArrayList<Throwable> temp = new ArrayList<>(exceptions);
+ ArrayList<? extends Throwable> temp = new ArrayList<>(exceptions);
this.exceptions = Collections.unmodifiableCollection(temp);
}
- /** @see #create(Collection) */
- public static RuntimeException create(Throwable... exceptions) {
+ /** See {@link #create(Collection)}. */
+ static RuntimeException create(Throwable... exceptions) {
ArrayList<Throwable> temp = new ArrayList<>(Arrays.asList(exceptions));
return create(temp);
}
@@ -96,7 +97,7 @@ final class ClusterException extends RuntimeException {
* @throws NullPointerException if {@code exceptions} is null
* @throws IllegalArgumentException if {@code exceptions} is empty
*/
- public static RuntimeException create(Collection<? extends Throwable> exceptions) {
+ static RuntimeException create(Collection<? extends Throwable> exceptions) {
if (exceptions.size() == 0) {
throw new IllegalArgumentException("Can't create an ExceptionCollection with no exceptions");
}
diff --git a/android/guava-testlib/src/com/google/common/testing/DummyProxy.java b/android/guava-testlib/src/com/google/common/testing/DummyProxy.java
index 85e229d51..7b2525c72 100644
--- a/android/guava-testlib/src/com/google/common/testing/DummyProxy.java
+++ b/android/guava-testlib/src/com/google/common/testing/DummyProxy.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.testing.NullPointerTester.isNullable;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.reflect.AbstractInvocationHandler;
@@ -30,6 +31,7 @@ import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Generates a dummy interface proxy that simply returns a dummy value for each method.
@@ -37,6 +39,8 @@ import java.util.Set;
* @author Ben Yu
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
abstract class DummyProxy {
/**
@@ -59,7 +63,7 @@ abstract class DummyProxy {
}
/** Returns the dummy return value for {@code returnType}. */
- abstract <R> R dummyReturnValue(TypeToken<R> returnType);
+ abstract <R> @Nullable R dummyReturnValue(TypeToken<R> returnType);
private class DummyHandler extends AbstractInvocationHandler implements Serializable {
private final TypeToken<?> interfaceType;
@@ -69,7 +73,7 @@ abstract class DummyProxy {
}
@Override
- protected Object handleInvocation(Object proxy, Method method, Object[] args) {
+ protected @Nullable Object handleInvocation(Object proxy, Method method, Object[] args) {
Invokable<?, ?> invokable = interfaceType.method(method);
ImmutableList<Parameter> params = invokable.getParameters();
for (int i = 0; i < args.length; i++) {
@@ -87,7 +91,7 @@ abstract class DummyProxy {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof DummyHandler) {
DummyHandler that = (DummyHandler) obj;
return identity().equals(that.identity());
diff --git a/android/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java b/android/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java
new file mode 100644
index 000000000..1362176b5
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2021 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.testing;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.google.common.annotations.GwtCompatible;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import javax.annotation.Nonnull;
+import javax.annotation.meta.TypeQualifierDefault;
+
+/**
+ * Marks all "top-level" types as non-null in a way that is recognized by Kotlin. Note that this
+ * unfortunately includes type-variable usages, so we also provide {@link ParametricNullness} to
+ * "undo" it as best we can.
+ */
+@GwtCompatible
+@Retention(RUNTIME)
+@Target(TYPE)
+@TypeQualifierDefault({FIELD, METHOD, PARAMETER})
+@Nonnull
+@interface ElementTypesAreNonnullByDefault {}
diff --git a/android/guava-testlib/src/com/google/common/testing/EqualsTester.java b/android/guava-testlib/src/com/google/common/testing/EqualsTester.java
index 9c93c9a49..d4484702a 100644
--- a/android/guava-testlib/src/com/google/common/testing/EqualsTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/EqualsTester.java
@@ -22,10 +22,12 @@ import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import java.util.ArrayList;
import java.util.List;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester for equals() and hashCode() methods of a class.
@@ -74,6 +76,7 @@ import java.util.List;
* @since 10.0
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public final class EqualsTester {
private static final int REPETITIONS = 3;
@@ -93,13 +96,23 @@ public final class EqualsTester {
* Adds {@code equalityGroup} with objects that are supposed to be equal to each other and not
* equal to any other equality groups added to this tester.
*/
- public EqualsTester addEqualityGroup(Object... equalityGroup) {
+ @CanIgnoreReturnValue
+ public EqualsTester addEqualityGroup(@Nullable Object @Nullable ... equalityGroup) {
checkNotNull(equalityGroup);
- equalityGroups.add(ImmutableList.copyOf(equalityGroup));
+ List<Object> list = new ArrayList<>(equalityGroup.length);
+ for (int i = 0; i < equalityGroup.length; i++) {
+ Object element = equalityGroup[i];
+ if (element == null) {
+ throw new NullPointerException("at index " + i);
+ }
+ list.add(element);
+ }
+ equalityGroups.add(list);
return this;
}
/** Run tests on equals method, throwing a failure on an invalid test */
+ @CanIgnoreReturnValue
public EqualsTester testEquals() {
RelationshipTester<Object> delegate =
new RelationshipTester<>(
diff --git a/android/guava-testlib/src/com/google/common/testing/EquivalenceTester.java b/android/guava-testlib/src/com/google/common/testing/EquivalenceTester.java
index 8de2625d0..ec34752c5 100644
--- a/android/guava-testlib/src/com/google/common/testing/EquivalenceTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/EquivalenceTester.java
@@ -25,6 +25,7 @@ import com.google.common.base.Equivalence;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.testing.RelationshipTester.ItemReporter;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.List;
/**
@@ -49,6 +50,7 @@ import java.util.List;
* @since 10.0
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public final class EquivalenceTester<T> {
private static final int REPETITIONS = 3;
@@ -69,11 +71,13 @@ public final class EquivalenceTester<T> {
* Adds a group of objects that are supposed to be equivalent to each other and not equivalent to
* objects in any other equivalence group added to this tester.
*/
+ @CanIgnoreReturnValue
public EquivalenceTester<T> addEquivalenceGroup(T first, T... rest) {
addEquivalenceGroup(Lists.asList(first, rest));
return this;
}
+ @CanIgnoreReturnValue
public EquivalenceTester<T> addEquivalenceGroup(Iterable<T> group) {
delegate.addRelatedGroup(group);
items.addAll(ImmutableList.copyOf(group));
@@ -81,6 +85,7 @@ public final class EquivalenceTester<T> {
}
/** Run tests on equivalence methods, throwing a failure on an invalid test */
+ @CanIgnoreReturnValue
public EquivalenceTester<T> test() {
for (int run = 0; run < REPETITIONS; run++) {
testItems();
diff --git a/android/guava-testlib/src/com/google/common/testing/FakeTicker.java b/android/guava-testlib/src/com/google/common/testing/FakeTicker.java
index 573635393..8c0e0026e 100644
--- a/android/guava-testlib/src/com/google/common/testing/FakeTicker.java
+++ b/android/guava-testlib/src/com/google/common/testing/FakeTicker.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ticker;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@@ -34,6 +35,7 @@ import java.util.concurrent.atomic.AtomicLong;
* @author Jige Yu
* @since 10.0
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible
public class FakeTicker extends Ticker {
@@ -42,12 +44,14 @@ public class FakeTicker extends Ticker {
/** Advances the ticker value by {@code time} in {@code timeUnit}. */
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public FakeTicker advance(long time, TimeUnit timeUnit) {
return advance(timeUnit.toNanos(time));
}
/** Advances the ticker value by {@code nanoseconds}. */
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public FakeTicker advance(long nanoseconds) {
nanos.addAndGet(nanoseconds);
return this;
@@ -60,6 +64,7 @@ public class FakeTicker extends Ticker {
* queried.
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public FakeTicker setAutoIncrementStep(long autoIncrementStep, TimeUnit timeUnit) {
checkArgument(autoIncrementStep >= 0, "May not auto-increment by a negative amount");
this.autoIncrementStepNanos = timeUnit.toNanos(autoIncrementStep);
diff --git a/android/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java b/android/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java
index 605d3a055..c0d2c6a01 100644
--- a/android/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java
@@ -23,17 +23,20 @@ import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Reflection;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester to ensure forwarding wrapper works by delegating calls to the corresponding method with
@@ -53,6 +56,8 @@ import java.util.concurrent.atomic.AtomicInteger;
* @since 14.0
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
public final class ForwardingWrapperTester {
private boolean testsEquals = false;
@@ -61,6 +66,7 @@ public final class ForwardingWrapperTester {
* Asks for {@link Object#equals} and {@link Object#hashCode} to be tested. That is, forwarding
* wrappers of equal instances should be equal.
*/
+ @CanIgnoreReturnValue
public ForwardingWrapperTester includingEquals() {
this.testsEquals = true;
return this;
@@ -171,9 +177,9 @@ public final class ForwardingWrapperTester {
wrapperFunction.apply(proxy).toString());
}
- private static Object[] getParameterValues(Method method) {
+ private static @Nullable Object[] getParameterValues(Method method) {
FreshValueGenerator paramValues = new FreshValueGenerator();
- List<Object> passedArgs = Lists.newArrayList();
+ List<@Nullable Object> passedArgs = Lists.newArrayList();
for (Class<?> paramType : method.getParameterTypes()) {
passedArgs.add(paramValues.generateFresh(paramType));
}
@@ -185,8 +191,8 @@ public final class ForwardingWrapperTester {
private final Class<T> interfaceType;
private final Method method;
- private final Object[] passedArgs;
- private final Object returnValue;
+ private final @Nullable Object[] passedArgs;
+ private final @Nullable Object returnValue;
private final AtomicInteger called = new AtomicInteger();
InteractionTester(Class<T> interfaceType, Method method) {
@@ -197,8 +203,8 @@ public final class ForwardingWrapperTester {
}
@Override
- protected Object handleInvocation(Object p, Method calledMethod, Object[] args)
- throws Throwable {
+ protected @Nullable Object handleInvocation(
+ Object p, Method calledMethod, @Nullable Object[] args) throws Throwable {
assertEquals(method, calledMethod);
assertEquals(method + " invoked more than once.", 0, called.get());
for (int i = 0; i < passedArgs.length; i++) {
diff --git a/android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java b/android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
index 259f50c45..41c8ee624 100644
--- a/android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
+++ b/android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Equivalence;
@@ -118,7 +119,7 @@ import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Generates fresh instances of types that are different from each other (if possible).
@@ -126,6 +127,7 @@ import javax.annotation.CheckForNull;
* @author Ben Yu
*/
@GwtIncompatible
+@J2ktIncompatible
class FreshValueGenerator {
private static final ImmutableMap<Class<?>, Method> GENERATORS;
@@ -175,8 +177,7 @@ class FreshValueGenerator {
* <li>null if no value can be generated.
* </ul>
*/
- @CheckForNull
- final Object generateFresh(TypeToken<?> type) {
+ final @Nullable Object generateFresh(TypeToken<?> type) {
Object generated = generate(type);
if (generated != null) {
freshness.incrementAndGet();
@@ -184,8 +185,7 @@ class FreshValueGenerator {
return generated;
}
- @CheckForNull
- final <T> T generateFresh(Class<T> type) {
+ final <T> @Nullable T generateFresh(Class<T> type) {
return Primitives.wrap(type).cast(generateFresh(TypeToken.of(type)));
}
@@ -199,7 +199,7 @@ class FreshValueGenerator {
* Generates an instance for {@code type} using the current {@link #freshness}. The generated
* instance may or may not be unique across different calls.
*/
- private Object generate(TypeToken<?> type) {
+ private @Nullable Object generate(TypeToken<?> type) {
Class<?> rawType = type.getRawType();
List<Object> samples = sampleInstances.get(rawType);
Object sample = pickInstance(samples, null);
@@ -210,7 +210,7 @@ class FreshValueGenerator {
return pickInstance(rawType.getEnumConstants(), null);
}
if (type.isArray()) {
- TypeToken<?> componentType = type.getComponentType();
+ TypeToken<?> componentType = checkNotNull(type.getComponentType());
Object array = Array.newInstance(componentType.getRawType(), 1);
Array.set(array, 0, generate(componentType));
return array;
@@ -256,7 +256,7 @@ class FreshValueGenerator {
return defaultGenerate(rawType);
}
- private <T> T defaultGenerate(Class<T> rawType) {
+ private <T> @Nullable T defaultGenerate(Class<T> rawType) {
if (rawType.isInterface()) {
// always create a new proxy
return newProxy(rawType);
@@ -289,7 +289,7 @@ class FreshValueGenerator {
}
@Override
- protected Object handleInvocation(Object proxy, Method method, Object[] args) {
+ protected Object handleInvocation(Object proxy, Method method, @Nullable Object[] args) {
return interfaceMethodCalled(interfaceType, method);
}
@@ -299,7 +299,7 @@ class FreshValueGenerator {
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof FreshInvocationHandler) {
FreshInvocationHandler that = (FreshInvocationHandler) obj;
return identity == that.identity;
@@ -620,7 +620,7 @@ class FreshValueGenerator {
}
@Generates
- <T> Ordering<T> generateOrdering() {
+ <T extends @Nullable Object> Ordering<T> generateOrdering() {
return new Ordering<T>() {
@Override
public int compare(T left, T right) {
@@ -647,29 +647,29 @@ class FreshValueGenerator {
}
@Generates
- static <E> Iterable<E> generateIterable(@CheckForNull E freshElement) {
+ static <E> Iterable<E> generateIterable(@Nullable E freshElement) {
return generateList(freshElement);
}
@Generates
- static <E> Collection<E> generateCollection(@CheckForNull E freshElement) {
+ static <E> Collection<E> generateCollection(@Nullable E freshElement) {
return generateList(freshElement);
}
@Generates
- static <E> List<E> generateList(@CheckForNull E freshElement) {
+ static <E> List<E> generateList(@Nullable E freshElement) {
return generateArrayList(freshElement);
}
@Generates
- static <E> ArrayList<E> generateArrayList(@CheckForNull E freshElement) {
+ static <E> ArrayList<E> generateArrayList(@Nullable E freshElement) {
ArrayList<E> list = Lists.newArrayList();
list.add(freshElement);
return list;
}
@Generates
- static <E> LinkedList<E> generateLinkedList(@CheckForNull E freshElement) {
+ static <E> LinkedList<E> generateLinkedList(@Nullable E freshElement) {
LinkedList<E> list = Lists.newLinkedList();
list.add(freshElement);
return list;
@@ -686,17 +686,17 @@ class FreshValueGenerator {
}
@Generates
- static <E> Set<E> generateSet(@CheckForNull E freshElement) {
+ static <E> Set<E> generateSet(@Nullable E freshElement) {
return generateHashSet(freshElement);
}
@Generates
- static <E> HashSet<E> generateHashSet(@CheckForNull E freshElement) {
+ static <E> HashSet<E> generateHashSet(@Nullable E freshElement) {
return generateLinkedHashSet(freshElement);
}
@Generates
- static <E> LinkedHashSet<E> generateLinkedHashSet(@CheckForNull E freshElement) {
+ static <E> LinkedHashSet<E> generateLinkedHashSet(@Nullable E freshElement) {
LinkedHashSet<E> set = Sets.newLinkedHashSet();
set.add(freshElement);
return set;
@@ -731,19 +731,19 @@ class FreshValueGenerator {
}
@Generates
- static <E> Multiset<E> generateMultiset(@CheckForNull E freshElement) {
+ static <E> Multiset<E> generateMultiset(@Nullable E freshElement) {
return generateHashMultiset(freshElement);
}
@Generates
- static <E> HashMultiset<E> generateHashMultiset(@CheckForNull E freshElement) {
+ static <E> HashMultiset<E> generateHashMultiset(@Nullable E freshElement) {
HashMultiset<E> multiset = HashMultiset.create();
multiset.add(freshElement);
return multiset;
}
@Generates
- static <E> LinkedHashMultiset<E> generateLinkedHashMultiset(@CheckForNull E freshElement) {
+ static <E> LinkedHashMultiset<E> generateLinkedHashMultiset(@Nullable E freshElement) {
LinkedHashMultiset<E> multiset = LinkedHashMultiset.create();
multiset.add(freshElement);
return multiset;
@@ -773,18 +773,17 @@ class FreshValueGenerator {
}
@Generates
- static <K, V> Map<K, V> generateMap(@CheckForNull K key, @CheckForNull V value) {
+ static <K, V> Map<K, V> generateMap(@Nullable K key, @Nullable V value) {
return generateHashdMap(key, value);
}
@Generates
- static <K, V> HashMap<K, V> generateHashdMap(@CheckForNull K key, @CheckForNull V value) {
+ static <K, V> HashMap<K, V> generateHashdMap(@Nullable K key, @Nullable V value) {
return generateLinkedHashMap(key, value);
}
@Generates
- static <K, V> LinkedHashMap<K, V> generateLinkedHashMap(
- @CheckForNull K key, @CheckForNull V value) {
+ static <K, V> LinkedHashMap<K, V> generateLinkedHashMap(@Nullable K key, @Nullable V value) {
LinkedHashMap<K, V> map = Maps.newLinkedHashMap();
map.put(key, value);
return map;
@@ -809,19 +808,19 @@ class FreshValueGenerator {
@Generates
static <K extends Comparable<? super K>, V> SortedMap<K, V> generateSortedMap(
- K key, @CheckForNull V value) {
+ K key, @Nullable V value) {
return generateNavigableMap(key, value);
}
@Generates
static <K extends Comparable<? super K>, V> NavigableMap<K, V> generateNavigableMap(
- K key, @CheckForNull V value) {
+ K key, @Nullable V value) {
return generateTreeMap(key, value);
}
@Generates
static <K extends Comparable<? super K>, V> TreeMap<K, V> generateTreeMap(
- K key, @CheckForNull V value) {
+ K key, @Nullable V value) {
TreeMap<K, V> map = Maps.newTreeMap();
map.put(key, value);
return map;
@@ -834,7 +833,7 @@ class FreshValueGenerator {
}
@Generates
- static <K, V> Multimap<K, V> generateMultimap(@CheckForNull K key, @CheckForNull V value) {
+ static <K, V> Multimap<K, V> generateMultimap(@Nullable K key, @Nullable V value) {
return generateListMultimap(key, value);
}
@@ -844,14 +843,13 @@ class FreshValueGenerator {
}
@Generates
- static <K, V> ListMultimap<K, V> generateListMultimap(
- @CheckForNull K key, @CheckForNull V value) {
+ static <K, V> ListMultimap<K, V> generateListMultimap(@Nullable K key, @Nullable V value) {
return generateArrayListMultimap(key, value);
}
@Generates
static <K, V> ArrayListMultimap<K, V> generateArrayListMultimap(
- @CheckForNull K key, @CheckForNull V value) {
+ @Nullable K key, @Nullable V value) {
ArrayListMultimap<K, V> multimap = ArrayListMultimap.create();
multimap.put(key, value);
return multimap;
@@ -863,13 +861,12 @@ class FreshValueGenerator {
}
@Generates
- static <K, V> SetMultimap<K, V> generateSetMultimap(@CheckForNull K key, @CheckForNull V value) {
+ static <K, V> SetMultimap<K, V> generateSetMultimap(@Nullable K key, @Nullable V value) {
return generateLinkedHashMultimap(key, value);
}
@Generates
- static <K, V> HashMultimap<K, V> generateHashMultimap(
- @CheckForNull K key, @CheckForNull V value) {
+ static <K, V> HashMultimap<K, V> generateHashMultimap(@Nullable K key, @Nullable V value) {
HashMultimap<K, V> multimap = HashMultimap.create();
multimap.put(key, value);
return multimap;
@@ -877,7 +874,7 @@ class FreshValueGenerator {
@Generates
static <K, V> LinkedHashMultimap<K, V> generateLinkedHashMultimap(
- @CheckForNull K key, @CheckForNull V value) {
+ @Nullable K key, @Nullable V value) {
LinkedHashMultimap<K, V> multimap = LinkedHashMultimap.create();
multimap.put(key, value);
return multimap;
@@ -889,12 +886,12 @@ class FreshValueGenerator {
}
@Generates
- static <K, V> BiMap<K, V> generateBimap(@CheckForNull K key, @CheckForNull V value) {
+ static <K, V> BiMap<K, V> generateBimap(@Nullable K key, @Nullable V value) {
return generateHashBiMap(key, value);
}
@Generates
- static <K, V> HashBiMap<K, V> generateHashBiMap(@CheckForNull K key, @CheckForNull V value) {
+ static <K, V> HashBiMap<K, V> generateHashBiMap(@Nullable K key, @Nullable V value) {
HashBiMap<K, V> bimap = HashBiMap.create();
bimap.put(key, value);
return bimap;
@@ -906,14 +903,12 @@ class FreshValueGenerator {
}
@Generates
- static <R, C, V> Table<R, C, V> generateTable(
- @CheckForNull R row, @CheckForNull C column, @CheckForNull V value) {
+ static <R, C, V> Table<R, C, V> generateTable(R row, C column, V value) {
return generateHashBasedTable(row, column, value);
}
@Generates
- static <R, C, V> HashBasedTable<R, C, V> generateHashBasedTable(
- @CheckForNull R row, @CheckForNull C column, @CheckForNull V value) {
+ static <R, C, V> HashBasedTable<R, C, V> generateHashBasedTable(R row, C column, V value) {
HashBasedTable<R, C, V> table = HashBasedTable.create();
table.put(row, column, value);
return table;
diff --git a/android/guava-testlib/src/com/google/common/testing/GcFinalization.java b/android/guava-testlib/src/com/google/common/testing/GcFinalization.java
index da6aa2211..cf3409ac3 100644
--- a/android/guava-testlib/src/com/google/common/testing/GcFinalization.java
+++ b/android/guava-testlib/src/com/google/common/testing/GcFinalization.java
@@ -19,6 +19,7 @@ package com.google.common.testing;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.lang.ref.WeakReference;
@@ -103,7 +104,9 @@ import java.util.concurrent.TimeoutException;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@J2ObjCIncompatible // gc
+@ElementTypesAreNonnullByDefault
public final class GcFinalization {
private GcFinalization() {}
diff --git a/android/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java b/android/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java
new file mode 100644
index 000000000..2203162bf
--- /dev/null
+++ b/android/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2019 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.testing;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@interface IgnoreJRERequirement {}
diff --git a/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java b/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java
index 4c24c65e1..73c5705ba 100644
--- a/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Objects;
import com.google.common.collect.ClassToInstanceMap;
@@ -32,8 +33,9 @@ import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Annotation;
-import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
@@ -41,18 +43,19 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
-import javax.annotation.CheckForNull;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A test utility that verifies that your methods and constructors throw {@link
* NullPointerException} or {@link UnsupportedOperationException} whenever null is passed to a
- * parameter that isn't annotated with an annotation with the simple name {@code Nullable}, {@code
- * CheckForNull}, {@link NullableType}, or {@link NullableDecl}.
+ * parameter whose declaration or type isn't annotated with an annotation with the simple name
+ * {@code Nullable}, {@code CheckForNull}, {@code NullableType}, or {@code NullableDecl}.
*
* <p>The tested methods and constructors are invoked -- each time with one parameter being null and
* the rest not null -- and the test fails if no expected exception is thrown. {@code
@@ -66,6 +69,8 @@ import junit.framework.AssertionFailedError;
* @since 10.0
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
public final class NullPointerTester {
private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create();
@@ -73,10 +78,27 @@ public final class NullPointerTester {
private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE;
+ public NullPointerTester() {
+ try {
+ /*
+ * Converter.apply has a non-nullable parameter type but doesn't throw for null arguments. For
+ * more information, see the comments in that class.
+ *
+ * We already know that that's how it behaves, and subclasses of Converter can't change that
+ * behavior. So there's no sense in making all subclass authors exclude the method from any
+ * NullPointerTester tests that they have.
+ */
+ ignoredMembers.add(Converter.class.getMethod("apply", Object.class));
+ } catch (NoSuchMethodException shouldBeImpossible) {
+ // OK, fine: If it doesn't exist, then there's chance that we're going to be asked to test it.
+ }
+ }
+
/**
* Sets a default value that can be used for any parameter of type {@code type}. Returns this
* object.
*/
+ @CanIgnoreReturnValue
public <T> NullPointerTester setDefault(Class<T> type, T value) {
defaults.putInstance(type, checkNotNull(value));
return this;
@@ -87,6 +109,7 @@ public final class NullPointerTester {
*
* @since 13.0
*/
+ @CanIgnoreReturnValue
public NullPointerTester ignore(Method method) {
ignoredMembers.add(checkNotNull(method));
return this;
@@ -97,6 +120,7 @@ public final class NullPointerTester {
*
* @since 22.0
*/
+ @CanIgnoreReturnValue
public NullPointerTester ignore(Constructor<?> constructor) {
ignoredMembers.add(checkNotNull(constructor));
return this;
@@ -174,7 +198,7 @@ public final class NullPointerTester {
*
* @param instance the instance to invoke {@code method} on, or null if {@code method} is static
*/
- public void testMethod(@CheckForNull Object instance, Method method) {
+ public void testMethod(@Nullable Object instance, Method method) {
Class<?>[] types = method.getParameterTypes();
for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
testMethodParameter(instance, method, nullIndex);
@@ -205,8 +229,7 @@ public final class NullPointerTester {
*
* @param instance the instance to invoke {@code method} on, or null if {@code method} is static
*/
- public void testMethodParameter(
- @CheckForNull final Object instance, final Method method, int paramIndex) {
+ public void testMethodParameter(@Nullable Object instance, Method method, int paramIndex) {
method.setAccessible(true);
testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass());
}
@@ -304,7 +327,7 @@ public final class NullPointerTester {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof Signature) {
Signature that = (Signature) obj;
return name.equals(that.name) && parameterTypes.equals(that.parameterTypes);
@@ -327,11 +350,18 @@ public final class NullPointerTester {
* static
*/
private void testParameter(
- Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
+ @Nullable Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
+ /*
+ * com.google.common is starting to rely on type-use annotations, which aren't visible under
+ * Android VMs. So we skip testing there.
+ */
+ if (isAndroid() && Reflection.getPackageName(testedClass).startsWith("com.google.common")) {
+ return;
+ }
if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
return; // there's nothing to test
}
- Object[] params = buildParamList(invokable, paramIndex);
+ @Nullable Object[] params = buildParamList(invokable, paramIndex);
try {
@SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong.
Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
@@ -367,9 +397,10 @@ public final class NullPointerTester {
}
}
- private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
+ private @Nullable Object[] buildParamList(
+ Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
ImmutableList<Parameter> params = invokable.getParameters();
- Object[] args = new Object[params.size()];
+ @Nullable Object[] args = new Object[params.size()];
for (int i = 0; i < args.length; i++) {
Parameter param = params.get(i);
@@ -385,7 +416,7 @@ public final class NullPointerTester {
return args;
}
- private <T> T getDefaultValue(TypeToken<T> type) {
+ private <T> @Nullable T getDefaultValue(TypeToken<T> type) {
// We assume that all defaults are generics-safe, even if they aren't,
// we take the risk.
@SuppressWarnings("unchecked")
@@ -453,13 +484,13 @@ public final class NullPointerTester {
private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
return new DummyProxy() {
@Override
- <R> R dummyReturnValue(TypeToken<R> returnType) {
+ <R> @Nullable R dummyReturnValue(TypeToken<R> returnType) {
return getDefaultValue(returnType);
}
}.newProxy(type);
}
- private static Invokable<?, ?> invokable(@CheckForNull Object instance, Method method) {
+ private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
if (instance == null) {
return Invokable.from(method);
} else {
@@ -472,11 +503,18 @@ public final class NullPointerTester {
}
private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES =
- ImmutableSet.of(
- "CheckForNull", "Nullable", "NullableDecl", "NullableType", "ParametricNullness");
+ ImmutableSet.of("CheckForNull", "Nullable", "NullableDecl", "NullableType");
- static boolean isNullable(AnnotatedElement e) {
- for (Annotation annotation : e.getAnnotations()) {
+ static boolean isNullable(Invokable<?, ?> invokable) {
+ return NULLNESS_ANNOTATION_READER.isNullable(invokable);
+ }
+
+ static boolean isNullable(Parameter param) {
+ return NULLNESS_ANNOTATION_READER.isNullable(param);
+ }
+
+ private static boolean containsNullable(Annotation[] annotations) {
+ for (Annotation annotation : annotations) {
if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) {
return true;
}
@@ -547,4 +585,87 @@ public final class NullPointerTester {
public abstract boolean isExpectedType(Throwable cause);
}
+
+ private static boolean annotatedTypeExists() {
+ try {
+ Class.forName("java.lang.reflect.AnnotatedType");
+ } catch (ClassNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
+
+ private static final NullnessAnnotationReader NULLNESS_ANNOTATION_READER =
+ annotatedTypeExists()
+ ? NullnessAnnotationReader.FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS
+ : NullnessAnnotationReader.FROM_DECLARATION_ANNOTATIONS_ONLY;
+
+ /**
+ * Looks for declaration nullness annotations and, if supported, type-use nullness annotations.
+ *
+ * <p>Under Android VMs, the methods for retrieving type-use annotations don't exist. This means
+ * that {@link NullPointerException} may misbehave under Android when used on classes that rely on
+ * type-use annotations.
+ *
+ * <p>Under j2objc, the necessary APIs exist, but some (perhaps all) return stub values, like
+ * empty arrays. Presumably {@link NullPointerException} could likewise misbehave under j2objc,
+ * but I don't know that anyone uses it there, anyway.
+ */
+ private enum NullnessAnnotationReader {
+ // Usages (which are unsafe only for Android) are guarded by the annotatedTypeExists() check.
+ @SuppressWarnings({"Java7ApiChecker", "AndroidApiChecker", "DoNotCall", "deprecation"})
+ FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS {
+ @Override
+ @IgnoreJRERequirement
+ boolean isNullable(Invokable<?, ?> invokable) {
+ return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(invokable)
+ || containsNullable(invokable.getAnnotatedReturnType().getAnnotations());
+ // TODO(cpovirk): Should we also check isNullableTypeVariable?
+ }
+
+ @Override
+ @IgnoreJRERequirement
+ boolean isNullable(Parameter param) {
+ return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(param)
+ || containsNullable(param.getAnnotatedType().getAnnotations())
+ || isNullableTypeVariable(param.getAnnotatedType().getType());
+ }
+
+ @IgnoreJRERequirement
+ boolean isNullableTypeVariable(Type type) {
+ if (!(type instanceof TypeVariable)) {
+ return false;
+ }
+ TypeVariable<?> typeVar = (TypeVariable<?>) type;
+ for (AnnotatedType bound : typeVar.getAnnotatedBounds()) {
+ // Until Java 15, the isNullableTypeVariable case here won't help:
+ // https://bugs.openjdk.java.net/browse/JDK-8202469
+ if (containsNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) {
+ return true;
+ }
+ }
+ return false;
+ }
+ },
+ FROM_DECLARATION_ANNOTATIONS_ONLY {
+ @Override
+ boolean isNullable(Invokable<?, ?> invokable) {
+ return containsNullable(invokable.getAnnotations());
+ }
+
+ @Override
+ boolean isNullable(Parameter param) {
+ return containsNullable(param.getAnnotations());
+ }
+ };
+
+ abstract boolean isNullable(Invokable<?, ?> invokable);
+
+ abstract boolean isNullable(Parameter param);
+ }
+
+ private static boolean isAndroid() {
+ // Arguably it would make more sense to test "can we see type-use annotations" directly....
+ return checkNotNull(System.getProperty("java.runtime.name", "")).contains("Android");
+ }
}
diff --git a/android/guava-testlib/src/com/google/common/testing/Platform.java b/android/guava-testlib/src/com/google/common/testing/Platform.java
index b107966ec..bbad5598d 100644
--- a/android/guava-testlib/src/com/google/common/testing/Platform.java
+++ b/android/guava-testlib/src/com/google/common/testing/Platform.java
@@ -31,6 +31,7 @@ import java.io.ObjectOutputStream;
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
final class Platform {
/** Serializes and deserializes the specified object. */
@SuppressWarnings("unchecked")
diff --git a/android/guava-testlib/src/com/google/common/testing/RelationshipTester.java b/android/guava-testlib/src/com/google/common/testing/RelationshipTester.java
index d5b9b6a18..d1caedd4e 100644
--- a/android/guava-testlib/src/com/google/common/testing/RelationshipTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/RelationshipTester.java
@@ -22,6 +22,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.List;
import junit.framework.AssertionFailedError;
@@ -32,6 +33,7 @@ import junit.framework.AssertionFailedError;
* @author Gregory Kick
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
final class RelationshipTester<T> {
static class ItemReporter {
@@ -66,6 +68,7 @@ final class RelationshipTester<T> {
}
// TODO(cpovirk): should we reject null items, since the tests already check null automatically?
+ @CanIgnoreReturnValue
public RelationshipTester<T> addRelatedGroup(Iterable<? extends T> group) {
groups.add(ImmutableList.copyOf(group));
return this;
diff --git a/android/guava-testlib/src/com/google/common/testing/SerializableTester.java b/android/guava-testlib/src/com/google/common/testing/SerializableTester.java
index c4e6d236e..c2f8cc169 100644
--- a/android/guava-testlib/src/com/google/common/testing/SerializableTester.java
+++ b/android/guava-testlib/src/com/google/common/testing/SerializableTester.java
@@ -17,6 +17,7 @@
package com.google.common.testing;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
@@ -32,6 +33,7 @@ import junit.framework.AssertionFailedError;
* @since 10.0
*/
@GwtCompatible // but no-op!
+@ElementTypesAreNonnullByDefault
public final class SerializableTester {
private SerializableTester() {}
@@ -50,6 +52,7 @@ public final class SerializableTester {
* @throws RuntimeException if the specified object was not successfully serialized or
* deserialized
*/
+ @CanIgnoreReturnValue
public static <T> T reserialize(T object) {
return Platform.reserialize(object);
}
@@ -81,6 +84,7 @@ public final class SerializableTester {
* @throws AssertionFailedError if the re-serialized object is not equal to the original object,
* or if the hashcodes are different.
*/
+ @CanIgnoreReturnValue
public static <T> T reserializeAndAssert(T object) {
T copy = reserialize(object);
new EqualsTester().addEqualityGroup(object, copy).testEquals();
diff --git a/android/guava-testlib/src/com/google/common/testing/SloppyTearDown.java b/android/guava-testlib/src/com/google/common/testing/SloppyTearDown.java
index 95ff34e33..10d9dc04e 100644
--- a/android/guava-testlib/src/com/google/common/testing/SloppyTearDown.java
+++ b/android/guava-testlib/src/com/google/common/testing/SloppyTearDown.java
@@ -16,7 +16,6 @@
package com.google.common.testing;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -30,8 +29,8 @@ import java.util.logging.Logger;
* @author Luiz-Otavio Zorzella
* @since 10.0
*/
-@Beta
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public abstract class SloppyTearDown implements TearDown {
private static final Logger logger = Logger.getLogger(SloppyTearDown.class.getName());
diff --git a/android/guava-testlib/src/com/google/common/testing/TearDown.java b/android/guava-testlib/src/com/google/common/testing/TearDown.java
index 50485348f..45aebe2a2 100644
--- a/android/guava-testlib/src/com/google/common/testing/TearDown.java
+++ b/android/guava-testlib/src/com/google/common/testing/TearDown.java
@@ -16,7 +16,6 @@
package com.google.common.testing;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
@@ -25,8 +24,8 @@ import com.google.common.annotations.GwtCompatible;
* @author Kevin Bourrillion
* @since 10.0
*/
-@Beta
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public interface TearDown {
/**
* Performs a <b>single</b> tear-down operation. See test-libraries-for-java's {@code
diff --git a/android/guava-testlib/src/com/google/common/testing/TearDownAccepter.java b/android/guava-testlib/src/com/google/common/testing/TearDownAccepter.java
index bad1f1997..ec4319bab 100644
--- a/android/guava-testlib/src/com/google/common/testing/TearDownAccepter.java
+++ b/android/guava-testlib/src/com/google/common/testing/TearDownAccepter.java
@@ -16,9 +16,8 @@
package com.google.common.testing;
-import com.google.common.annotations.Beta;
-import com.google.errorprone.annotations.DoNotMock;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.DoNotMock;
/**
* Any object which can accept registrations of {@link TearDown} instances.
@@ -26,9 +25,9 @@ import com.google.common.annotations.GwtCompatible;
* @author Kevin Bourrillion
* @since 10.0
*/
-@Beta
@DoNotMock("Implement with a lambda")
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public interface TearDownAccepter {
/**
* Registers a TearDown implementor which will be run after the test proper.
diff --git a/android/guava-testlib/src/com/google/common/testing/TearDownStack.java b/android/guava-testlib/src/com/google/common/testing/TearDownStack.java
index bab025a61..c22b54c40 100644
--- a/android/guava-testlib/src/com/google/common/testing/TearDownStack.java
+++ b/android/guava-testlib/src/com/google/common/testing/TearDownStack.java
@@ -18,7 +18,6 @@ package com.google.common.testing;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.errorprone.annotations.concurrent.GuardedBy;
@@ -36,8 +35,8 @@ import java.util.logging.Logger;
* @author Kevin Bourrillion
* @since 10.0
*/
-@Beta
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public class TearDownStack implements TearDownAccepter {
private static final Logger logger = Logger.getLogger(TearDownStack.class.getName());
diff --git a/android/guava-testlib/src/com/google/common/testing/TestLogHandler.java b/android/guava-testlib/src/com/google/common/testing/TestLogHandler.java
index 263f8908a..e481a2f19 100644
--- a/android/guava-testlib/src/com/google/common/testing/TestLogHandler.java
+++ b/android/guava-testlib/src/com/google/common/testing/TestLogHandler.java
@@ -16,13 +16,14 @@
package com.google.common.testing;
+
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests may use this to intercept messages that are logged by the code under test. Example:
@@ -52,14 +53,17 @@ import javax.annotation.CheckForNull;
* @since 10.0
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public class TestLogHandler extends Handler {
/** We will keep a private list of all logged records */
private final List<LogRecord> list = new ArrayList<>();
/** Adds the most recently logged record to our list. */
@Override
- public synchronized void publish(@CheckForNull LogRecord record) {
- list.add(record);
+ public synchronized void publish(@Nullable LogRecord record) {
+ if (record != null) {
+ list.add(record);
+ }
}
@Override
diff --git a/android/guava-testlib/src/com/google/common/testing/package-info.java b/android/guava-testlib/src/com/google/common/testing/package-info.java
index e6762f98c..3c0849ffc 100644
--- a/android/guava-testlib/src/com/google/common/testing/package-info.java
+++ b/android/guava-testlib/src/com/google/common/testing/package-info.java
@@ -15,8 +15,9 @@
*/
/**
- * This package contains testing utilities. It is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Testing utilities. This package is a part of the open-source <a
+ * href="https://github.com/google/guava">Guava</a> library.
*/
+@com.google.errorprone.annotations.CheckReturnValue
@javax.annotation.ParametersAreNonnullByDefault
package com.google.common.testing;
diff --git a/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java b/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java
index b5bec2c09..abe419e05 100644
--- a/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java
+++ b/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java
@@ -19,7 +19,6 @@ package com.google.common.util.concurrent.testing;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.CancellationException;
@@ -31,6 +30,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Abstract test case parent for anything implementing {@link ListenableFuture}. Tests the two get
@@ -39,7 +39,6 @@ import junit.framework.TestCase;
* @author Sven Mawson
* @since 10.0
*/
-@Beta
@GwtIncompatible
public abstract class AbstractListenableFutureTest extends TestCase {
@@ -63,7 +62,7 @@ public abstract class AbstractListenableFutureTest extends TestCase {
/** Constructs a listenable future with a value available after the latch has counted down. */
protected abstract <V> ListenableFuture<V> createListenableFuture(
- V value, Exception except, CountDownLatch waitOn);
+ V value, @Nullable Exception except, CountDownLatch waitOn);
/** Tests that the {@link Future#get()} method blocks until a value is available. */
public void testGetBlocksUntilValueAvailable() throws Throwable {
diff --git a/android/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java b/android/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java
index a2fe4f447..87eb73aa9 100644
--- a/android/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java
+++ b/android/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java
@@ -19,7 +19,6 @@ package com.google.common.util.concurrent.testing;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.CountDownLatch;
@@ -32,7 +31,6 @@ import junit.framework.Assert;
* @author Nishant Thakkar
* @since 10.0
*/
-@Beta
@GwtIncompatible
public class MockFutureListener implements Runnable {
private final CountDownLatch countDownLatch;
diff --git a/android/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java b/android/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java
index dc2c40d37..ffbf3842f 100644
--- a/android/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java
+++ b/android/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java
@@ -30,7 +30,10 @@ import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
/**
@@ -39,7 +42,6 @@ import java.util.concurrent.TimeUnit;
* @author Chris Nokleberg
* @since 14.0
*/
-@Beta
@GwtIncompatible
public final class TestingExecutors {
private TestingExecutors() {}
@@ -88,9 +90,10 @@ public final class TestingExecutors {
* invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the tasks may
* already have been executed.
*
- * @since 15.0
+ * @since 32.0.0 (taking the place of a method with a different return type from 15.0)
*/
- public static SameThreadScheduledExecutorService sameThreadScheduledExecutor() {
+ @Beta
+ public static ListeningScheduledExecutorService sameThreadScheduledExecutor() {
return new SameThreadScheduledExecutorService();
}
diff --git a/android/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java b/android/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java
index 4d617d64d..92ee857d9 100644
--- a/android/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java
+++ b/android/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java
@@ -22,32 +22,16 @@ import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestResult;
-import org.junit.Ignore;
-/** @author Max Ross */
+/**
+ * @author Max Ross
+ */
public class FeatureSpecificTestSuiteBuilderTest extends TestCase {
-
- private static boolean testWasRun;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- testWasRun = false;
- }
-
- @Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
- public static final class MyAbstractTester extends AbstractTester<Void> {
- public void testNothing() {
- testWasRun = true;
- }
- }
-
private static final class MyTestSuiteBuilder
extends FeatureSpecificTestSuiteBuilder<MyTestSuiteBuilder, String> {
-
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
- return Collections.<Class<? extends AbstractTester>>singletonList(MyAbstractTester.class);
+ return Collections.<Class<? extends AbstractTester>>singletonList(MyTester.class);
}
}
@@ -80,8 +64,9 @@ public class FeatureSpecificTestSuiteBuilderTest extends TestCase {
.withTearDown(tearDownRunnable)
.createTestSuite();
TestResult result = new TestResult();
+ int timesMyTesterWasRunBeforeSuite = MyTester.timesTestClassWasRun;
test.run(result);
- assertTrue(testWasRun);
+ assertEquals(timesMyTesterWasRunBeforeSuite + 1, MyTester.timesTestClassWasRun);
assertTrue(setUp[0]);
assertTrue(tearDown[0]);
}
diff --git a/android/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java b/android/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java
index 283f51efe..b44811e33 100644
--- a/android/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java
@@ -233,7 +233,7 @@ public class IteratorTesterTest extends TestCase {
@Override
public Integer next() {
// We should throw here, but we won't!
- return null;
+ return 0;
}
@Override
diff --git a/android/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java b/android/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java
index a4d216d15..7b56959a8 100644
--- a/android/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java
+++ b/android/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java
@@ -45,6 +45,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests {@link MapTestSuiteBuilder} by using it against maps that have various negative behaviors.
@@ -106,7 +107,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public String put(String key, String value) {
+ public @Nullable String put(String key, String value) {
checkNotNull(key);
return map.put(key, value);
}
@@ -138,7 +139,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return map.equals(o);
}
@@ -148,7 +149,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public String remove(Object key) {
+ public @Nullable String remove(Object key) {
return map.remove(key);
}
@@ -194,7 +195,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return next.equals(obj);
}
@@ -238,7 +239,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return map.entrySet().equals(o);
}
@@ -249,7 +250,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public String put(String key, String value) {
+ public @Nullable String put(String key, String value) {
checkNotNull(value);
return map.put(key, value);
}
diff --git a/android/guava-testlib/test/com/google/common/collect/testing/MyTester.java b/android/guava-testlib/test/com/google/common/collect/testing/MyTester.java
new file mode 100644
index 000000000..de79059a6
--- /dev/null
+++ b/android/guava-testlib/test/com/google/common/collect/testing/MyTester.java
@@ -0,0 +1,38 @@
+/*
+ * 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.testing;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.junit.Ignore;
+
+/** Support class added to a suite as part of {@link FeatureSpecificTestSuiteBuilderTest}. */
+/*
+ * @Ignore affects the Android test runner (and only the Android test runner): It respects JUnit 4
+ * annotations even on JUnit 3 tests.
+ *
+ * TODO(b/225350400): Remove @Ignore, which doesn't seem like it should be necessary and probably
+ * soon won't be.
+ */
+@SuppressWarnings("JUnit4ClassUsedInJUnit3")
+@Ignore
+public final class MyTester extends AbstractTester<@Nullable Void> {
+ static int timesTestClassWasRun = 0;
+
+ public void testNothing() {
+ timesTestClassWasRun++;
+ }
+}
diff --git a/android/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java b/android/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java
new file mode 100644
index 000000000..46d76a353
--- /dev/null
+++ b/android/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2010 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.testing;
+
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.testing.SerializableTester;
+import java.util.NavigableMap;
+import java.util.SortedMap;
+
+@GwtIncompatible // SerializableTester
+public class ReserializedSafeTreeMapMapInterfaceTest
+ extends SortedMapInterfaceTest<String, Integer> {
+ public ReserializedSafeTreeMapMapInterfaceTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ NavigableMap<String, Integer> map = new SafeTreeMap<>();
+ map.put("one", 1);
+ map.put("two", 2);
+ map.put("three", 3);
+ return SerializableTester.reserialize(map);
+ }
+
+ @Override
+ protected SortedMap<String, Integer> makeEmptyMap() throws UnsupportedOperationException {
+ NavigableMap<String, Integer> map = new SafeTreeMap<>();
+ return SerializableTester.reserialize(map);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java b/android/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java
index f03ff0a09..67aa9f7f9 100644
--- a/android/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java
+++ b/android/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java
@@ -110,36 +110,4 @@ public class SafeTreeMapTest extends TestCase {
Lists.newArrayList(map.values()),
Lists.newArrayList(SerializableTester.reserialize(map.values())));
}
-
- @GwtIncompatible // SerializableTester
- public static class ReserializedMapTests extends SortedMapInterfaceTest<String, Integer> {
- public ReserializedMapTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- NavigableMap<String, Integer> map = new SafeTreeMap<>();
- map.put("one", 1);
- map.put("two", 2);
- map.put("three", 3);
- return SerializableTester.reserialize(map);
- }
-
- @Override
- protected SortedMap<String, Integer> makeEmptyMap() throws UnsupportedOperationException {
- NavigableMap<String, Integer> map = new SafeTreeMap<>();
- return SerializableTester.reserialize(map);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
- }
}
diff --git a/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java b/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
index b47672f83..4dc80848f 100644
--- a/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
@@ -127,6 +127,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ArbitraryInstances}.
@@ -473,7 +474,7 @@ public class ArbitraryInstancesTest extends TestCase {
}
public static class WithNullConstant {
- public static final WithNullConstant NULL = null;
+ public static final @Nullable WithNullConstant NULL = null;
private WithNullConstant() {}
}
@@ -496,7 +497,7 @@ public class ArbitraryInstancesTest extends TestCase {
private static class FirstConstantIsNull {
// To test that null constant is ignored
@SuppressWarnings("unused")
- public static final FirstConstantIsNull FIRST = null;
+ public static final @Nullable FirstConstantIsNull FIRST = null;
public static final FirstConstantIsNull SECOND = new FirstConstantIsNull();
}
diff --git a/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java b/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
index be1752d47..fee11890b 100644
--- a/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
@@ -34,15 +34,16 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link ClassSanityTester}.
*
* @author Ben Yu
*/
+@AndroidIncompatible // NullPointerTester refuses to run for c.g.c under Android
public class ClassSanityTesterTest extends TestCase {
private final ClassSanityTester tester = new ClassSanityTester();
@@ -58,7 +59,7 @@ public class ClassSanityTesterTest extends TestCase {
// oneConstantOnly doesn't matter since it's not nullable and can be only 1 value.
@SuppressWarnings("unused") OneConstantEnum oneConstantOnly,
// noConstant doesn't matter since it can only be null
- @SuppressWarnings("unused") @CheckForNull NoConstantEnum noConstant) {
+ @SuppressWarnings("unused") @Nullable NoConstantEnum noConstant) {
return new GoodEquals(a, b);
}
// instance method ignored
@@ -106,7 +107,7 @@ public class ClassSanityTesterTest extends TestCase {
private static class BadEqualsFactory {
/** oneConstantOnly matters now since it can be either null or the constant. */
@SuppressWarnings("unused") // Called by reflection
- public static Object bad(String a, int b, @CheckForNull OneConstantEnum oneConstantOnly) {
+ public static Object bad(String a, int b, @Nullable OneConstantEnum oneConstantOnly) {
return new GoodEquals(a, b);
}
}
@@ -210,11 +211,11 @@ public class ClassSanityTesterTest extends TestCase {
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface
public void testEqualsAndSerializableOnReturnValues_good() throws Exception {
tester
- .forAllPublicStaticMethods(GoodEqualsAndSerialiableFactory.class)
+ .forAllPublicStaticMethods(GoodEqualsAndSerializableFactory.class)
.testEqualsAndSerializable();
}
- public static class GoodEqualsAndSerialiableFactory {
+ public static class GoodEqualsAndSerializableFactory {
public static Object good(AnInterface s) {
return Functions.constant(s);
}
@@ -287,8 +288,7 @@ public class ClassSanityTesterTest extends TestCase {
}
public static class FactoryThatReturnsNullAndAnnotated {
- @CheckForNull
- public static Object bad() {
+ public static @Nullable Object bad() {
return null;
}
}
@@ -313,7 +313,7 @@ public class ClassSanityTesterTest extends TestCase {
try {
tester.testEquals(BadEquals.class);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains("create(null)");
+ assertThat(expected).hasMessageThat().contains("create(null)");
return;
}
fail("should have failed");
@@ -323,7 +323,7 @@ public class ClassSanityTesterTest extends TestCase {
try {
tester.testEquals(BadEqualsWithParameterizedType.class);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains("create([[1]])");
+ assertThat(expected).hasMessageThat().contains("create([[1]])");
return;
}
fail("should have failed");
@@ -362,7 +362,7 @@ public class ClassSanityTesterTest extends TestCase {
try {
tester.testEquals(cls);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains(cls.getSimpleName() + "(");
+ assertThat(expected).hasMessageThat().contains(cls.getSimpleName() + "(");
return;
}
fail("should have failed for " + cls);
@@ -427,8 +427,8 @@ public class ClassSanityTesterTest extends TestCase {
tester.testNulls(GoodNulls.class);
}
- public void testNoNullCheckNeededDespitNotInstantiable() throws Exception {
- tester.doTestNulls(NoNullCheckNeededDespitNotInstantiable.class, Visibility.PACKAGE);
+ public void testNoNullCheckNeededDespiteNotInstantiable() throws Exception {
+ tester.doTestNulls(NoNullCheckNeededDespiteNotInstantiable.class, Visibility.PACKAGE);
}
public void testNulls_interface() {
@@ -477,9 +477,10 @@ public class ClassSanityTesterTest extends TestCase {
public void testInstantiate_factoryMethodReturnsNullButNotAnnotated() throws Exception {
try {
- tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class);
+ FactoryMethodReturnsNullButNotAnnotated unused =
+ tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains("@Nullable");
+ assertThat(expected).hasMessageThat().contains("@Nullable");
return;
}
fail("should have failed");
@@ -616,7 +617,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof HasAnInterface) {
HasAnInterface that = (HasAnInterface) obj;
return i.equals(that.i);
@@ -673,7 +674,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
// In general getClass().isInstance() is bad for equals.
// But here we fully control the subclasses to ensure symmetry.
if (getClass().isInstance(obj)) {
@@ -753,13 +754,12 @@ public class ClassSanityTesterTest extends TestCase {
// keep trying
@SuppressWarnings("unused")
- @CheckForNull
- public static GoodEquals createMayReturnNull(int a, int b) {
+ public static @Nullable GoodEquals createMayReturnNull(int a, int b) {
return null;
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof GoodEquals) {
GoodEquals that = (GoodEquals) obj;
return a.equals(that.a) && b == that.b;
@@ -778,12 +778,12 @@ public class ClassSanityTesterTest extends TestCase {
public BadEquals() {} // ignored by testEquals() since it has less parameters.
- public static BadEquals create(@SuppressWarnings("unused") @CheckForNull String s) {
+ public static BadEquals create(@SuppressWarnings("unused") @Nullable String s) {
return new BadEquals();
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof BadEquals;
}
@@ -806,8 +806,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameIntegerInstance) {
SameIntegerInstance that = (SameIntegerInstance) obj;
return i == that.i;
@@ -829,8 +829,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameLongInstance) {
SameLongInstance that = (SameLongInstance) obj;
return i == that.i;
@@ -852,8 +852,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameFloatInstance) {
SameFloatInstance that = (SameFloatInstance) obj;
return i == that.i;
@@ -875,8 +875,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameDoubleInstance) {
SameDoubleInstance that = (SameDoubleInstance) obj;
return i == that.i;
@@ -898,8 +898,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameShortInstance) {
SameShortInstance that = (SameShortInstance) obj;
return i == that.i;
@@ -921,8 +921,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameByteInstance) {
SameByteInstance that = (SameByteInstance) obj;
return i == that.i;
@@ -944,7 +944,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ @SuppressWarnings("BoxedPrimitiveEquality")
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameCharacterInstance) {
SameCharacterInstance that = (SameCharacterInstance) obj;
return i == that.i;
@@ -966,7 +967,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ @SuppressWarnings("BoxedPrimitiveEquality")
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameBooleanInstance) {
SameBooleanInstance that = (SameBooleanInstance) obj;
return i == that.i;
@@ -988,7 +990,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameStringInstance) {
SameStringInstance that = (SameStringInstance) obj;
return s == that.s;
@@ -1010,7 +1012,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameObjectInstance) {
SameObjectInstance that = (SameObjectInstance) obj;
return s == that.s;
@@ -1032,7 +1034,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameInterfaceInstance) {
SameInterfaceInstance that = (SameInterfaceInstance) obj;
return s == that.s;
@@ -1054,7 +1056,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameListInstance) {
SameListInstance that = (SameListInstance) obj;
return s == that.s;
@@ -1076,7 +1078,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof UsesReferentialEquality) {
UsesReferentialEquality that = (UsesReferentialEquality) obj;
return s == that.s;
@@ -1098,7 +1100,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof UsesEnum) {
UsesEnum that = (UsesEnum) obj;
return s == that.s;
@@ -1122,7 +1124,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof BadEqualsWithParameterizedType;
}
@@ -1146,9 +1148,9 @@ public class ClassSanityTesterTest extends TestCase {
public void failsToRejectNull(@SuppressWarnings("unused") String s) {}
}
- public static class NoNullCheckNeededDespitNotInstantiable {
+ public static class NoNullCheckNeededDespiteNotInstantiable {
- public NoNullCheckNeededDespitNotInstantiable(NotInstantiable x) {
+ public NoNullCheckNeededDespiteNotInstantiable(NotInstantiable x) {
checkNotNull(x);
}
@@ -1156,12 +1158,12 @@ public class ClassSanityTesterTest extends TestCase {
void primitiveOnly(int i) {}
@SuppressWarnings("unused") // reflected
- void nullableOnly(@CheckForNull String s) {}
+ void nullableOnly(@Nullable String s) {}
public void noParameter() {}
@SuppressWarnings("unused") // reflected
- void primitiveAndNullable(@CheckForNull String s, int i) {}
+ void primitiveAndNullable(@Nullable String s, int i) {}
}
static class FactoryMethodReturnsNullButNotAnnotated {
@@ -1175,8 +1177,7 @@ public class ClassSanityTesterTest extends TestCase {
static class FactoryMethodReturnsNullAndAnnotated {
private FactoryMethodReturnsNullAndAnnotated() {}
- @CheckForNull
- public static FactoryMethodReturnsNullAndAnnotated returnsNull() {
+ public static @Nullable FactoryMethodReturnsNullAndAnnotated returnsNull() {
return null;
}
}
@@ -1189,7 +1190,7 @@ public class ClassSanityTesterTest extends TestCase {
this.name = name;
}
- static FactoryMethodAcceptsNull create(@CheckForNull String name) {
+ static FactoryMethodAcceptsNull create(@Nullable String name) {
return new FactoryMethodAcceptsNull(name);
}
}
@@ -1211,7 +1212,7 @@ public class ClassSanityTesterTest extends TestCase {
final String name;
- public ConstructorAcceptsNull(@CheckForNull String name) {
+ public ConstructorAcceptsNull(@Nullable String name) {
this.name = name;
}
}
@@ -1237,7 +1238,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof ConstructorParameterMapOfNotInstantiable) {
return m.equals(((ConstructorParameterMapOfNotInstantiable) obj).m);
} else {
@@ -1258,7 +1259,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object obj) {
+ public boolean equals(@Nullable Object obj) {
throw new UnsupportedOperationException();
}
@@ -1272,7 +1273,7 @@ public class ClassSanityTesterTest extends TestCase {
public ConstructorParameterSingleValue(@SuppressWarnings("unused") Singleton s) {}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof ConstructorParameterSingleValue;
}
diff --git a/android/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java b/android/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java
index d615af663..b6b1914eb 100644
--- a/android/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java
@@ -23,6 +23,7 @@ import com.google.common.collect.Sets;
import java.util.Set;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link EqualsTester}.
@@ -114,7 +115,7 @@ public class EqualsTesterTest extends TestCase {
}
/** Test proper handling of case where an object is not equal to itself */
- public void testNonreflexiveEquals() {
+ public void testNonReflexiveEquals() {
Object obj = new NonReflexiveObject();
equalsTester.addEqualityGroup(obj);
try {
@@ -302,7 +303,7 @@ public class EqualsTesterTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (!(o instanceof ValidTestObject)) {
return false;
}
@@ -337,7 +338,7 @@ public class EqualsTesterTest extends TestCase {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (!(o instanceof InvalidHashCodeObject)) {
return false;
}
@@ -356,7 +357,7 @@ public class EqualsTesterTest extends TestCase {
private static class NonReflexiveObject {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return false;
}
@@ -370,7 +371,7 @@ public class EqualsTesterTest extends TestCase {
private static class InvalidEqualsNullObject {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return o == this || o == null;
}
@@ -384,7 +385,7 @@ public class EqualsTesterTest extends TestCase {
private static class InvalidEqualsIncompatibleClassObject {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return o != null;
}
@@ -413,7 +414,7 @@ public class EqualsTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof NamedObject) {
NamedObject that = (NamedObject) obj;
return name.equals(that.name) || peerNames.contains(that.name);
@@ -440,7 +441,7 @@ public class EqualsTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj != null && obj.toString().equals(toString());
}
diff --git a/android/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java b/android/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java
index 865c198e7..fedc36088 100644
--- a/android/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java
@@ -113,7 +113,7 @@ public class EquivalenceTesterTest extends TestCase {
fail();
}
- public void testTest_trasitive() {
+ public void testTest_transitive() {
Object group1Item1 = new TestObject(1, 1);
Object group1Item2 = new TestObject(1, 2);
Object group1Item3 = new TestObject(1, 3);
diff --git a/android/guava-testlib/test/com/google/common/testing/FakeTickerTest.java b/android/guava-testlib/test/com/google/common/testing/FakeTickerTest.java
index 654304b19..5810524d0 100644
--- a/android/guava-testlib/test/com/google/common/testing/FakeTickerTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/FakeTickerTest.java
@@ -26,6 +26,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link FakeTicker}.
@@ -108,9 +109,9 @@ public class FakeTickerTest extends TestCase {
int numberOfThreads = 64;
runConcurrentTest(
numberOfThreads,
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
// adds two nanoseconds to the ticker
ticker.advance(1L);
Thread.sleep(10);
@@ -132,10 +133,10 @@ public class FakeTickerTest extends TestCase {
int numberOfThreads = 64;
runConcurrentTest(
numberOfThreads,
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
- ticker.read();
+ public @Nullable Void call() throws Exception {
+ long unused = ticker.read();
return null;
}
});
@@ -145,7 +146,7 @@ public class FakeTickerTest extends TestCase {
/** Runs {@code callable} concurrently {@code numberOfThreads} times. */
@GwtIncompatible // concurrency
- private void runConcurrentTest(int numberOfThreads, final Callable<Void> callable)
+ private void runConcurrentTest(int numberOfThreads, final Callable<@Nullable Void> callable)
throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
final CountDownLatch startLatch = new CountDownLatch(numberOfThreads);
@@ -154,9 +155,9 @@ public class FakeTickerTest extends TestCase {
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError =
executorService.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
startLatch.countDown();
startLatch.await();
callable.call();
diff --git a/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java b/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java
index 164ac5a0c..f100ef483 100644
--- a/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java
@@ -25,6 +25,7 @@ import java.util.WeakHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link GcFinalization}.
@@ -32,6 +33,7 @@ import junit.framework.TestCase;
* @author Martin Buchholz
* @author mike nonemacher
*/
+@AndroidIncompatible // depends on details of gc
public class GcFinalizationTest extends TestCase {
@@ -54,7 +56,7 @@ public class GcFinalizationTest extends TestCase {
}
public void testAwaitDone_Future() {
- final SettableFuture<Void> future = SettableFuture.create();
+ final SettableFuture<@Nullable Void> future = SettableFuture.create();
Object x =
new Object() {
@Override
@@ -69,7 +71,7 @@ public class GcFinalizationTest extends TestCase {
}
public void testAwaitDone_Future_Cancel() {
- final SettableFuture<Void> future = SettableFuture.create();
+ final SettableFuture<@Nullable Void> future = SettableFuture.create();
Object x =
new Object() {
@Override
@@ -159,7 +161,7 @@ public class GcFinalizationTest extends TestCase {
public void testAwaitDone_Future_Interrupted_Interrupted() {
Interruptenator interruptenator = new Interruptenator(Thread.currentThread());
try {
- final SettableFuture<Void> future = SettableFuture.create();
+ final SettableFuture<@Nullable Void> future = SettableFuture.create();
try {
GcFinalization.awaitDone(future);
fail("should throw");
diff --git a/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java b/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
index 218edef0a..d7344abf6 100644
--- a/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
@@ -37,6 +37,7 @@ import com.google.common.collect.Table;
import com.google.common.reflect.TypeToken;
import com.google.common.testing.NullPointerTester.Visibility;
import com.google.common.testing.anotherpackage.SomeClassThatDoesNotUseNullable;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
@@ -44,9 +45,9 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
-import javax.annotation.CheckForNull;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link NullPointerTester}.
@@ -55,6 +56,7 @@ import junit.framework.TestCase;
* @author Mick Killianey
*/
@SuppressWarnings("CheckReturnValue")
+@AndroidIncompatible // NullPointerTester refuses to run for c.g.c under Android
public class NullPointerTesterTest extends TestCase {
/** Non-NPE RuntimeException. */
@@ -86,11 +88,12 @@ public class NullPointerTesterTest extends TestCase {
// null? no problem
}
- public static void staticOneArgJsr305NullableCorrectlyDoesNotThrowNPE(@CheckForNull String s) {
+ public static void staticOneArgJsr305NullableCorrectlyDoesNotThrowNPE(
+ @javax.annotation.Nullable String s) {
// null? no problem
}
- public static void staticOneArgNullableCorrectlyDoesNotThrowNPE(@CheckForNull String s) {
+ public static void staticOneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) {
// null? no problem
}
@@ -99,7 +102,7 @@ public class NullPointerTesterTest extends TestCase {
throw new FooException(); // ok, as long as it's not NullPointerException
}
- public static void staticOneArgNullableCorrectlyThrowsOtherThanNPE(@CheckForNull String s) {
+ public static void staticOneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) {
throw new FooException(); // ok, as long as it's not NullPointerException
}
@@ -107,7 +110,7 @@ public class NullPointerTesterTest extends TestCase {
checkNotNull(s); // doesn't check if you said you'd accept null, but you don't
}
- public static void staticOneArgNullableThrowsNPE(@CheckForNull String s) {
+ public static void staticOneArgNullableThrowsNPE(@Nullable String s) {
checkNotNull(s); // doesn't check if you said you'd accept null, but you don't
}
@@ -128,7 +131,7 @@ public class NullPointerTesterTest extends TestCase {
// null? no problem
}
- public void oneArgNullableCorrectlyDoesNotThrowNPE(@CheckForNull String s) {
+ public void oneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) {
// null? no problem
}
@@ -137,7 +140,7 @@ public class NullPointerTesterTest extends TestCase {
throw new FooException(); // ok, as long as it's not NullPointerException
}
- public void oneArgNullableCorrectlyThrowsOtherThanNPE(@CheckForNull String s) {
+ public void oneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) {
throw new FooException(); // ok, as long as it's not NullPointerException
}
@@ -145,7 +148,7 @@ public class NullPointerTesterTest extends TestCase {
checkNotNull(s); // doesn't check if you said you'd accept null, but you don't
}
- public void oneArgNullableThrowsNPE(@CheckForNull String s) {
+ public void oneArgNullableThrowsNPE(@Nullable String s) {
checkNotNull(s); // doesn't check if you said you'd accept null, but you don't
}
}
@@ -330,7 +333,7 @@ public class NullPointerTesterTest extends TestCase {
}
/** Method that decides how to react to parameters. */
- public void reactToNullParameters(Object first, Object second) {
+ public void reactToNullParameters(@Nullable Object first, @Nullable Object second) {
if (first == null) {
actionWhenFirstParamIsNull.act();
}
@@ -347,19 +350,19 @@ public class NullPointerTesterTest extends TestCase {
/** Two-arg method with the second param Nullable. */
@SuppressWarnings("GoodTime") // false positive; b/122617528
- public void normalNullable(String first, @CheckForNull Integer second) {
+ public void normalNullable(String first, @Nullable Integer second) {
reactToNullParameters(first, second);
}
/** Two-arg method with the first param Nullable. */
@SuppressWarnings("GoodTime") // false positive; b/122617528
- public void nullableNormal(@CheckForNull String first, Integer second) {
+ public void nullableNormal(@Nullable String first, Integer second) {
reactToNullParameters(first, second);
}
/** Two-arg method with the both params Nullable. */
@SuppressWarnings("GoodTime") // false positive; b/122617528
- public void nullableNullable(@CheckForNull String first, @CheckForNull Integer second) {
+ public void nullableNullable(@Nullable String first, @Nullable Integer second) {
reactToNullParameters(first, second);
}
@@ -473,9 +476,9 @@ public class NullPointerTesterTest extends TestCase {
checkNotNull(s);
}
- public void oneNullableArg(@CheckForNull String s) {}
+ public void oneNullableArg(@Nullable String s) {}
- public void oneNullableArgThrows(@CheckForNull String s) {
+ public void oneNullableArgThrows(@Nullable String s) {
doThrow(s);
}
@@ -484,31 +487,31 @@ public class NullPointerTesterTest extends TestCase {
i.intValue();
}
- public void twoMixedArgs(String s, @CheckForNull Integer i) {
+ public void twoMixedArgs(String s, @Nullable Integer i) {
checkNotNull(s);
}
- public void twoMixedArgs(@CheckForNull Integer i, String s) {
+ public void twoMixedArgs(@Nullable Integer i, String s) {
checkNotNull(s);
}
- public void twoMixedArgsThrows(String s, @CheckForNull Integer i) {
+ public void twoMixedArgsThrows(String s, @Nullable Integer i) {
checkNotNull(s);
doThrow(i);
}
- public void twoMixedArgsThrows(@CheckForNull Integer i, String s) {
+ public void twoMixedArgsThrows(@Nullable Integer i, String s) {
checkNotNull(s);
doThrow(i);
}
- public void twoNullableArgs(@CheckForNull String s, @CheckForNull Integer i) {}
+ public void twoNullableArgs(@Nullable String s, @javax.annotation.Nullable Integer i) {}
- public void twoNullableArgsThrowsFirstArg(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgsThrowsFirstArg(@Nullable String s, @Nullable Integer i) {
doThrow(s);
}
- public void twoNullableArgsThrowsSecondArg(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgsThrowsSecondArg(@Nullable String s, @Nullable Integer i) {
doThrow(i);
}
@@ -516,9 +519,9 @@ public class NullPointerTesterTest extends TestCase {
checkNotNull(s);
}
- public static void staticOneNullableArg(@CheckForNull String s) {}
+ public static void staticOneNullableArg(@Nullable String s) {}
- public static void staticOneNullableArgThrows(@CheckForNull String s) {
+ public static void staticOneNullableArgThrows(@Nullable String s) {
doThrow(s);
}
}
@@ -551,7 +554,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassOneNullableArgThrowsNPE extends PassObject {
@Override
- public void oneNullableArg(@CheckForNull String s) {
+ public void oneNullableArg(@Nullable String s) {
checkNotNull(s); // ok to throw NPE
}
}
@@ -610,7 +613,7 @@ public class NullPointerTesterTest extends TestCase {
private static class FailTwoMixedArgsFirstArgDoesntThrowNPE extends PassObject {
@Override
- public void twoMixedArgs(String s, @CheckForNull Integer i) {
+ public void twoMixedArgs(String s, @Nullable Integer i) {
// Fail: missing NPE for s
}
}
@@ -621,7 +624,7 @@ public class NullPointerTesterTest extends TestCase {
private static class FailTwoMixedArgsFirstArgThrowsWrongType extends PassObject {
@Override
- public void twoMixedArgs(String s, @CheckForNull Integer i) {
+ public void twoMixedArgs(String s, @Nullable Integer i) {
doThrow(s); // Fail: throwing non-NPE exception for null s
}
}
@@ -632,7 +635,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoMixedArgsNullableArgThrowsNPE extends PassObject {
@Override
- public void twoMixedArgs(String s, @CheckForNull Integer i) {
+ public void twoMixedArgs(String s, @Nullable Integer i) {
checkNotNull(s);
i.intValue(); // ok to throw NPE?
}
@@ -644,7 +647,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoMixedArgSecondNullableArgThrowsOther extends PassObject {
@Override
- public void twoMixedArgs(String s, @CheckForNull Integer i) {
+ public void twoMixedArgs(String s, @Nullable Integer i) {
checkNotNull(s);
doThrow(i); // ok to throw non-NPE exception for null i
}
@@ -656,7 +659,7 @@ public class NullPointerTesterTest extends TestCase {
private static class FailTwoMixedArgsSecondArgDoesntThrowNPE extends PassObject {
@Override
- public void twoMixedArgs(@CheckForNull Integer i, String s) {
+ public void twoMixedArgs(@Nullable Integer i, String s) {
// Fail: missing NPE for null s
}
}
@@ -667,7 +670,7 @@ public class NullPointerTesterTest extends TestCase {
private static class FailTwoMixedArgsSecondArgThrowsWrongType extends PassObject {
@Override
- public void twoMixedArgs(@CheckForNull Integer i, String s) {
+ public void twoMixedArgs(@Nullable Integer i, String s) {
doThrow(s); // Fail: throwing non-NPE exception for null s
}
}
@@ -678,7 +681,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoNullableArgsFirstThrowsNPE extends PassObject {
@Override
- public void twoNullableArgs(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgs(@Nullable String s, @Nullable Integer i) {
checkNotNull(s); // ok to throw NPE?
}
}
@@ -689,7 +692,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoNullableArgsFirstThrowsOther extends PassObject {
@Override
- public void twoNullableArgs(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgs(@Nullable String s, @Nullable Integer i) {
doThrow(s); // ok to throw non-NPE exception for null s
}
}
@@ -700,7 +703,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoNullableArgsSecondThrowsNPE extends PassObject {
@Override
- public void twoNullableArgs(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgs(@Nullable String s, @Nullable Integer i) {
i.intValue(); // ok to throw NPE?
}
}
@@ -711,7 +714,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoNullableArgsSecondThrowsOther extends PassObject {
@Override
- public void twoNullableArgs(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgs(@Nullable String s, @Nullable Integer i) {
doThrow(i); // ok to throw non-NPE exception for null i
}
}
@@ -722,7 +725,7 @@ public class NullPointerTesterTest extends TestCase {
private static class PassTwoNullableArgsNeitherThrowsAnything extends PassObject {
@Override
- public void twoNullableArgs(@CheckForNull String s, @CheckForNull Integer i) {
+ public void twoNullableArgs(@Nullable String s, @Nullable Integer i) {
// ok to do nothing
}
}
@@ -768,7 +771,7 @@ public class NullPointerTesterTest extends TestCase {
private static class SubclassThatOverridesBadSuperclassMethod extends BaseClassThatFailsToThrow {
@Override
- public void oneArg(@CheckForNull String s) {}
+ public void oneArg(@Nullable String s) {}
}
public void testSubclassThatOverridesBadSuperclassMethod() {
@@ -777,7 +780,7 @@ public class NullPointerTesterTest extends TestCase {
@SuppressWarnings("unused") // for NullPointerTester
private static class SubclassOverridesTheWrongMethod extends BaseClassThatFailsToThrow {
- public void oneArg(@CheckForNull CharSequence s) {}
+ public void oneArg(@Nullable CharSequence s) {}
}
public void testSubclassOverridesTheWrongMethod() {
@@ -801,7 +804,7 @@ public class NullPointerTesterTest extends TestCase {
private static class SubclassThatTriesToOverrideBadStaticMethod
extends ClassThatFailsToThrowForStatic {
- static void staticOneArg(@CheckForNull String s) {}
+ static void staticOneArg(@Nullable String s) {}
}
public void testSubclassThatTriesToOverrideBadStaticMethod() {
@@ -814,7 +817,7 @@ public class NullPointerTesterTest extends TestCase {
@SuppressWarnings("unused") // used by reflection
private static class CanCreateDefault {
- public void foo(@CheckForNull HardToCreate ignored, String required) {
+ public void foo(@Nullable HardToCreate ignored, String required) {
checkNotNull(required);
}
}
@@ -877,7 +880,7 @@ public class NullPointerTesterTest extends TestCase {
@SuppressWarnings("unused") // used by reflection
private static class PrivateClassWithPrivateConstructor {
- private PrivateClassWithPrivateConstructor(@CheckForNull Integer argument) {}
+ private PrivateClassWithPrivateConstructor(@Nullable Integer argument) {}
}
public void testPrivateClass() {
@@ -909,6 +912,7 @@ public class NullPointerTesterTest extends TestCase {
private final Map<Integer, Object> arguments = Maps.newHashMap();
+ @CanIgnoreReturnValue
final DefaultValueChecker runTester() {
new NullPointerTester().testInstanceMethods(this, Visibility.PACKAGE);
return this;
@@ -1391,7 +1395,7 @@ public class NullPointerTesterTest extends TestCase {
static class OverridesEquals {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return true;
}
}
diff --git a/android/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java b/android/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
index 753c4ab63..e950c9968 100644
--- a/android/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
@@ -19,6 +19,7 @@ package com.google.common.testing;
import java.io.Serializable;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link SerializableTester}.
@@ -82,7 +83,7 @@ public class SerializableTesterTest extends TestCase {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return (other instanceof ClassWhichIsAlwaysEqualButHasDifferentHashcodes);
}
}
@@ -91,7 +92,7 @@ public class SerializableTesterTest extends TestCase {
private static final long serialVersionUID = 1L;
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm);
}
@@ -106,7 +107,7 @@ public class SerializableTesterTest extends TestCase {
private static class OtherForm implements Serializable {
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm);
}
diff --git a/android/guava-testlib/test/com/google/common/testing/TearDownStackTest.java b/android/guava-testlib/test/com/google/common/testing/TearDownStackTest.java
index 5a4f9ede4..63e162f75 100644
--- a/android/guava-testlib/test/com/google/common/testing/TearDownStackTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/TearDownStackTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** @author Luiz-Otavio "Z" Zorzella */
@GwtCompatible
@@ -146,7 +147,7 @@ public class TearDownStackTest extends TestCase {
private static final class SimpleTearDown implements TearDown {
boolean ran = false;
- Callback callback = null;
+ @Nullable Callback callback = null;
public SimpleTearDown() {}
diff --git a/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java b/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java
index 6e3bf2397..bd823f8f6 100644
--- a/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java
+++ b/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java
@@ -28,12 +28,14 @@ import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.common.testing.ForwardingWrapperTester;
import com.google.common.testing.NullPointerTester;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ForwardingWrapperTester}. Live in a different package to detect reflection
@@ -119,7 +121,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof ForwardingRunnable) {
ForwardingRunnable that = (ForwardingRunnable) o;
return runnable.equals(that.runnable);
@@ -141,7 +143,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
public Runnable apply(final Runnable runnable) {
return new ForwardingRunnable(runnable) {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof ForwardingRunnable) {
ForwardingRunnable that = (ForwardingRunnable) o;
return runnable.equals(that.runnable);
@@ -255,7 +257,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
new Function<Adder, Adder>() {
@Override
public Adder apply(Adder adder) {
- return new FailsToPropagageException(adder);
+ return new FailsToPropagateException(adder);
}
},
"add(",
@@ -373,10 +375,10 @@ public class ForwardingWrapperTesterTest extends TestCase {
}
}
- private static class FailsToPropagageException implements Adder {
+ private static class FailsToPropagateException implements Adder {
private final Adder adder;
- FailsToPropagageException(Adder adder) {
+ FailsToPropagateException(Adder adder) {
this.adder = adder;
}
@@ -530,7 +532,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
private interface Equals {
@Override
- boolean equals(Object obj);
+ boolean equals(@Nullable Object obj);
@Override
int hashCode();
@@ -579,6 +581,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
/** An interface for the 2 ways that a chaining call might be defined. */
private interface ChainingCalls {
// A method that is defined to 'return this'
+ @CanIgnoreReturnValue
ChainingCalls chainingCall();
// A method that just happens to return a ChainingCalls object
ChainingCalls nonChainingCall();
@@ -591,6 +594,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
this.delegate = delegate;
}
+ @CanIgnoreReturnValue
@Override
public ForwardingChainingCalls chainingCall() {
delegate.chainingCall();
diff --git a/android/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java b/android/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java
index 9dee99b7a..73a9da53a 100644
--- a/android/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java
@@ -130,9 +130,9 @@ public class CharMatcherBenchmark {
list.set(list.indexOf(0), list.get(0));
list.set(0, 0);
}
- // Get threshold in the range [0, length], rounding up to ensure that non
- // zero percent values result in a non-zero threshold (so we always have at
- // least one matching character).
+ // Get threshold in the range [0, length], rounding up to ensure that
+ // non-zero percent values result in a non-zero threshold (so we always
+ // have at least one matching character).
int threshold = ((percent * length) + 99) / 100;
StringBuilder builder = new StringBuilder(length);
for (int n = 0; n < length; n++) {
diff --git a/android/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java b/android/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java
index 43fc75cff..592e80b64 100644
--- a/android/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java
@@ -20,12 +20,14 @@ import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.cache.LocalCache.Segment;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Benchmark for {@code LocalCache.Segment.removeEntryFromChain}.
*
* @author Charles Fry
*/
+@SuppressWarnings("CheckReturnValue")
public class ChainBenchmark {
@Param({"1", "2", "3", "4", "5", "6"})
@@ -33,7 +35,7 @@ public class ChainBenchmark {
private Segment<Object, Object> segment;
private ReferenceEntry<Object, Object> head;
- private ReferenceEntry<Object, Object> chain;
+ private @Nullable ReferenceEntry<Object, Object> chain;
@SuppressWarnings("GuardedBy")
@BeforeExperiment
diff --git a/android/guava-tests/benchmark/com/google/common/collect/ConcurrentHashMultisetBenchmark.java b/android/guava-tests/benchmark/com/google/common/collect/ConcurrentHashMultisetBenchmark.java
index 086a63493..322dd547f 100644
--- a/android/guava-tests/benchmark/com/google/common/collect/ConcurrentHashMultisetBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/collect/ConcurrentHashMultisetBenchmark.java
@@ -37,7 +37,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Benchmarks for {@link ConcurrentHashMultiset}.
@@ -192,7 +192,7 @@ public class ConcurrentHashMultisetBenchmark {
* @return the nonnegative number of occurrences of the element
*/
@Override
- public int count(@CheckForNull Object element) {
+ public int count(@Nullable Object element) {
try {
return unbox(countMap.get(element));
} catch (NullPointerException | ClassCastException e) {
@@ -295,7 +295,7 @@ public class ConcurrentHashMultisetBenchmark {
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
@Override
- public int remove(@CheckForNull Object element, int occurrences) {
+ public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
@@ -330,7 +330,7 @@ public class ConcurrentHashMultisetBenchmark {
* @param element the element whose occurrences should all be removed
* @return the number of occurrences successfully removed, possibly zero
*/
- private int removeAllOccurrences(@CheckForNull Object element) {
+ private int removeAllOccurrences(@Nullable Object element) {
try {
return unbox(countMap.remove(element));
} catch (NullPointerException | ClassCastException e) {
@@ -349,7 +349,7 @@ public class ConcurrentHashMultisetBenchmark {
* @param occurrences the number of occurrences of {@code element} to remove
* @return {@code true} if the removal was possible (including if {@code occurrences} is zero)
*/
- public boolean removeExactly(@CheckForNull Object element, int occurrences) {
+ public boolean removeExactly(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return true;
}
@@ -543,7 +543,7 @@ public class ConcurrentHashMultisetBenchmark {
}
/** We use a special form of unboxing that treats null as zero. */
- private static int unbox(@CheckForNull Integer i) {
+ private static int unbox(@Nullable Integer i) {
return (i == null) ? 0 : i;
}
}
diff --git a/android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java b/android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
index 2b7ef36c7..2b6a8c011 100644
--- a/android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
@@ -28,7 +28,7 @@ public class InternersBenchmark {
int weakInterner(int reps) {
Interner<String> interner = Interners.newWeakInterner();
for (int i = 0; i < reps; i++) {
- interner.intern(Double.toHexString(Math.random()));
+ String unused = interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
@@ -37,7 +37,7 @@ public class InternersBenchmark {
int strongInterner(int reps) {
Interner<String> interner = Interners.newStrongInterner();
for (int i = 0; i < reps; i++) {
- interner.intern(Double.toHexString(Math.random()));
+ String unused = interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
diff --git a/android/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java b/android/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
index 239a033f7..08755044c 100644
--- a/android/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
@@ -25,6 +25,7 @@ import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Benchmarks to compare performance of MinMaxPriorityQueue and PriorityQueue.
@@ -90,7 +91,7 @@ public class MinMaxPriorityQueueBenchmark {
}
@Override
- public T poll() {
+ public @Nullable T poll() {
return mmHeap.pollLast();
}
}
diff --git a/android/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java b/android/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java
index 0fa3e2a88..925db1a02 100644
--- a/android/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java
@@ -63,12 +63,19 @@ public class ChecksumBenchmark {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
CRC32 checksum = new CRC32();
- checksum.update(testBytes);
+ checksum.update(testBytes, 0, testBytes.length);
result = (byte) (result ^ checksum.getValue());
}
return result;
}
+ // CRC32C
+
+ @Benchmark
+ byte crc32cHashFunction(int reps) {
+ return runHashFunction(reps, Hashing.crc32c());
+ }
+
// Adler32
@Benchmark
@@ -81,7 +88,7 @@ public class ChecksumBenchmark {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
Adler32 checksum = new Adler32();
- checksum.update(testBytes);
+ checksum.update(testBytes, 0, testBytes.length);
result = (byte) (result ^ checksum.getValue());
}
return result;
diff --git a/android/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java b/android/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java
index ee81ea125..f82a0c3e6 100644
--- a/android/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java
@@ -78,7 +78,7 @@ public class ByteSourceAsCharSourceReadBenchmark {
return new String(buffer, 0, bufIndex);
}
// otherwise we got the size wrong. This can happen if the size changes between when
- // we called sizeIfKnown and when we started reading the file (or i guess if
+ // we called sizeIfKnown and when we started reading the file (or I guess if
// maxCharsPerByte is wrong)
// Fallback to an incremental approach
StringBuilder builder = new StringBuilder(bufIndex + 32);
diff --git a/android/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java b/android/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java
index 52532bb61..0b9c87489 100644
--- a/android/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java
@@ -21,6 +21,7 @@ import com.google.caliper.api.VmOptions;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
+import java.nio.Buffer;
import java.nio.CharBuffer;
import java.util.Random;
@@ -40,10 +41,10 @@ public class CharStreamsCopyBenchmark {
CharBuffer buf = CharStreams.createBuffer();
long total = 0;
while (from.read(buf) != -1) {
- buf.flip();
+ ((Buffer) buf).flip();
to.append(buf);
total += buf.remaining();
- buf.clear();
+ ((Buffer) buf).clear();
}
return total;
}
diff --git a/android/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java b/android/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java
index 6830482c2..d97c2d56d 100644
--- a/android/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java
@@ -50,7 +50,7 @@ public class QuantilesBenchmark {
}
private double[] dataset(int i) {
- // We must test on a fresh clone of the dataset each time. Doing sorts and quickselects on an
+ // We must test on a fresh clone of the dataset each time. Doing sorts and quickselects on a
// dataset which is already sorted or partially sorted is cheating.
return datasets[i & 0xFF].clone();
}
diff --git a/android/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java b/android/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
index 22053c8d6..946b85109 100644
--- a/android/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
@@ -38,7 +38,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Benchmarks for {@link ExecutionList}. */
@VmOptions({"-Xms8g", "-Xmx8g"})
@@ -440,7 +440,7 @@ public class ExecutionListBenchmark {
static final Logger log = Logger.getLogger(NewExecutionListWithoutReverse.class.getName());
@GuardedBy("this")
- private RunnableExecutorPair runnables;
+ private @Nullable RunnableExecutorPair runnables;
@GuardedBy("this")
private boolean executed;
@@ -488,7 +488,7 @@ public class ExecutionListBenchmark {
private static final class RunnableExecutorPair {
final Runnable runnable;
final Executor executor;
- @CheckForNull RunnableExecutorPair next;
+ @Nullable RunnableExecutorPair next;
RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
this.runnable = runnable;
@@ -504,10 +504,10 @@ public class ExecutionListBenchmark {
static final Logger log = Logger.getLogger(NewExecutionListQueue.class.getName());
@GuardedBy("this")
- private RunnableExecutorPair head;
+ private @Nullable RunnableExecutorPair head;
@GuardedBy("this")
- private RunnableExecutorPair tail;
+ private @Nullable RunnableExecutorPair tail;
@GuardedBy("this")
private boolean executed;
@@ -563,7 +563,7 @@ public class ExecutionListBenchmark {
private static final class RunnableExecutorPair {
Runnable runnable;
Executor executor;
- @CheckForNull RunnableExecutorPair next;
+ @Nullable RunnableExecutorPair next;
RunnableExecutorPair(Runnable runnable, Executor executor) {
this.runnable = runnable;
@@ -669,9 +669,9 @@ public class ExecutionListBenchmark {
final Runnable runnable;
final Executor executor;
// Volatile because this is written on one thread and read on another with no synchronization.
- @CheckForNull volatile RunnableExecutorPair next;
+ @Nullable volatile RunnableExecutorPair next;
- RunnableExecutorPair(Runnable runnable, Executor executor) {
+ RunnableExecutorPair(@Nullable Runnable runnable, @Nullable Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
diff --git a/android/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java b/android/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java
index bb764203f..9129bfc2a 100644
--- a/android/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java
+++ b/android/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java
@@ -33,7 +33,7 @@ import com.google.common.util.concurrent.FuturesGetChecked.GetCheckedTypeValidat
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
-import java.security.acl.NotOwnerException;
+import java.security.KeyException;
import java.util.List;
import java.util.TooManyListenersException;
import java.util.concurrent.BrokenBarrierException;
@@ -91,7 +91,7 @@ public class FuturesGetCheckedBenchmark {
ExecutionException.class,
GeneralSecurityException.class,
InvalidPreferencesFormatException.class,
- NotOwnerException.class,
+ KeyException.class,
RefreshFailedException.class,
TimeoutException.class,
TooManyListenersException.class,
diff --git a/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java b/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
index 2233fb47d..7b9be17ec 100644
--- a/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
+++ b/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
@@ -25,7 +25,7 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A bounded {@linkplain BlockingQueue blocking queue} backed by an array. This queue orders
@@ -51,7 +51,7 @@ import javax.annotation.CheckForNull;
* @author Justin T. Sampson
* @param <E> the type of elements held in this collection
*/
-@CanIgnoreReturnValue
+// TODO(kak): consider removing some of the @CanIgnoreReturnValue annotations as appropriate
public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E> {
@@ -213,6 +213,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws IllegalStateException if this queue is full
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue
@Override
public boolean add(E e) {
return super.add(e);
@@ -226,6 +227,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue
@Override
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
@@ -249,6 +251,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
+ @CanIgnoreReturnValue
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
@@ -285,8 +288,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
- public E poll() {
+ public @Nullable E poll() {
final Monitor monitor = this.monitor;
if (monitor.enterIf(notEmpty)) {
try {
@@ -299,8 +303,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
- public E poll(long timeout, TimeUnit unit) throws InterruptedException {
+ public @Nullable E poll(long timeout, TimeUnit unit) throws InterruptedException {
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notEmpty, timeout, unit)) {
try {
@@ -313,6 +318,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
public E take() throws InterruptedException {
final Monitor monitor = this.monitor;
@@ -324,8 +330,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
- public E peek() {
+ public @Nullable E peek() {
final Monitor monitor = this.monitor;
if (monitor.enterIf(notEmpty)) {
try {
@@ -345,6 +352,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @return the number of elements in this queue
*/
+ @CanIgnoreReturnValue
@Override
public int size() {
final Monitor monitor = this.monitor;
@@ -367,6 +375,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* inspecting {@code remainingCapacity} because it may be the case that another thread is about to
* insert or remove an element.
*/
+ @CanIgnoreReturnValue
@Override
public int remainingCapacity() {
final Monitor monitor = this.monitor;
@@ -387,8 +396,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
*/
+ @CanIgnoreReturnValue
@Override
- public boolean remove(@CheckForNull Object o) {
+ public boolean remove(@Nullable Object o) {
if (o == null) return false;
final E[] items = this.items;
final Monitor monitor = this.monitor;
@@ -417,8 +427,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
*/
+ @CanIgnoreReturnValue
@Override
- public boolean contains(@CheckForNull Object o) {
+ public boolean contains(@Nullable Object o) {
if (o == null) return false;
final E[] items = this.items;
final Monitor monitor = this.monitor;
@@ -447,6 +458,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @return an array containing all of the elements in this queue
*/
+ @CanIgnoreReturnValue
@Override
public Object[] toArray() {
final E[] items = this.items;
@@ -495,6 +507,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* the runtime type of every element in this queue
* @throws NullPointerException if the specified array is null
*/
+ @CanIgnoreReturnValue
@Override
public <T> T[] toArray(T[] a) {
final E[] items = this.items;
@@ -522,6 +535,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
public String toString() {
final Monitor monitor = this.monitor;
@@ -563,6 +577,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c) {
if (c == null) throw new NullPointerException();
@@ -597,6 +612,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null) throw new NullPointerException();
@@ -634,6 +650,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @return an iterator over the elements in this queue in proper sequence
*/
+ @CanIgnoreReturnValue
@Override
public Iterator<E> iterator() {
final Monitor monitor = this.monitor;
@@ -655,7 +672,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* we must return it in the following next() call even if it was in the process of being removed
* when hasNext() was called.
*/
- private E nextItem;
+ private @Nullable E nextItem;
/**
* Index of element returned by most recent call to next. Reset to -1 if this element is deleted
diff --git a/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java b/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
index f61885be2..25ec5812f 100644
--- a/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
+++ b/android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
@@ -30,7 +30,7 @@ import java.util.Queue;
import java.util.SortedSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An unbounded {@linkplain BlockingQueue blocking queue} that uses the same ordering rules as class
@@ -76,7 +76,6 @@ import javax.annotation.CheckForNull;
* @author Justin T. Sampson
* @param <E> the type of elements held in this collection
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E> {
@@ -124,7 +123,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @throws IllegalArgumentException if {@code initialCapacity} is less than 1
*/
public MonitorBasedPriorityBlockingQueue(
- int initialCapacity, @CheckForNull Comparator<? super E> comparator) {
+ int initialCapacity, @Nullable Comparator<? super E> comparator) {
q = new PriorityQueue<E>(initialCapacity, comparator);
}
@@ -152,6 +151,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* in the priority queue according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean add(E e) {
return offer(e);
@@ -166,6 +166,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* in the priority queue according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean offer(E e) {
final Monitor monitor = this.monitor;
@@ -193,6 +194,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* in the priority queue according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean offer(E e, long timeout, TimeUnit unit) {
checkNotNull(unit);
@@ -213,8 +215,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
offer(e); // never need to block
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public E poll() {
+ public @Nullable E poll() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
@@ -224,8 +227,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public E poll(long timeout, TimeUnit unit) throws InterruptedException {
+ public @Nullable E poll(long timeout, TimeUnit unit) throws InterruptedException {
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notEmpty, timeout, unit)) {
try {
@@ -238,6 +242,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public E take() throws InterruptedException {
final Monitor monitor = this.monitor;
@@ -249,8 +254,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public E peek() {
+ public @Nullable E peek() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
@@ -267,10 +273,12 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @return the comparator used to order the elements in this queue, or {@code null} if this queue
* uses the natural ordering of its elements
*/
+ @CanIgnoreReturnValue // pushed down from class to method
public Comparator<? super E> comparator() {
return q.comparator();
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int size() {
final Monitor monitor = this.monitor;
@@ -288,6 +296,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
*
* @return {@code Integer.MAX_VALUE}
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int remainingCapacity() {
return Integer.MAX_VALUE;
@@ -302,8 +311,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public boolean remove(@CheckForNull Object o) {
+ public boolean remove(@Nullable Object o) {
final Monitor monitor = this.monitor;
monitor.enter();
try {
@@ -321,8 +331,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public boolean contains(@CheckForNull Object o) {
+ public boolean contains(@Nullable Object o) {
final Monitor monitor = this.monitor;
monitor.enter();
try {
@@ -344,6 +355,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
*
* @return an array containing all of the elements in this queue
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public Object[] toArray() {
final Monitor monitor = this.monitor;
@@ -384,6 +396,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* the runtime type of every element in this queue
* @throws NullPointerException if the specified array is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public <T> T[] toArray(T[] a) {
final Monitor monitor = this.monitor;
@@ -395,6 +408,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public String toString() {
final Monitor monitor = this.monitor;
@@ -412,6 +426,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int drainTo(Collection<? super E> c) {
if (c == null) throw new NullPointerException();
@@ -437,6 +452,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null) throw new NullPointerException();
@@ -481,6 +497,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
*
* @return an iterator over the elements in this queue
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public Iterator<E> iterator() {
return new Itr(toArray());
@@ -497,11 +514,13 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
this.array = array;
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean hasNext() {
return cursor < array.length;
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public E next() {
if (cursor >= array.length) throw new NoSuchElementException();
diff --git a/android/guava-tests/pom.xml b/android/guava-tests/pom.xml
index 13a8d8dc1..be387bcbe 100644
--- a/android/guava-tests/pom.xml
+++ b/android/guava-tests/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-android</version>
+ <version>32.1.2-android</version>
</parent>
<artifactId>guava-tests</artifactId>
<name>Guava Unit Tests</name>
@@ -26,32 +26,42 @@
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
+ <groupId>org.checkerframework</groupId>
+ <artifactId>checker-qual</artifactId>
+ </dependency>
+ <dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
+ <version>4.13.2</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
+ <version>4.11.0</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
+ <version>${truth.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.jimfs</groupId>
<artifactId>jimfs</artifactId>
+ <version>1.2</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.caliper</groupId>
<artifactId>caliper</artifactId>
+ <version>1.0-beta-3</version>
+ <scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -76,13 +86,6 @@
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
- <id>default-jar</id>
- <goals><goal>jar</goal></goals>
- <configuration>
- <skipIfEmpty>true</skipIfEmpty>
- </configuration>
- </execution>
- <execution>
<id>create-test-jar</id>
<goals><goal>test-jar</goal></goals>
</execution>
diff --git a/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java b/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java
index ddb7d7097..b1cdae52e 100644
--- a/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java
+++ b/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.GcFinalization;
import java.lang.ref.WeakReference;
import java.util.Iterator;
@@ -50,8 +51,7 @@ public class AbstractIteratorTest extends TestCase {
case 2:
return endOfData();
default:
- fail("Should not have been invoked again");
- return null;
+ throw new AssertionError("Should not have been invoked again");
}
}
};
@@ -85,12 +85,12 @@ public class AbstractIteratorTest extends TestCase {
@Override
public Integer computeNext() {
if (haveBeenCalled) {
- fail("Should not have been called again");
+ throw new AssertionError("Should not have been called again");
} else {
haveBeenCalled = true;
sneakyThrow(new SomeCheckedException());
+ throw new AssertionError(); // unreachable
}
- return null; // never reached
}
};
@@ -173,6 +173,8 @@ public class AbstractIteratorTest extends TestCase {
@GwtIncompatible // weak references
+ @J2ktIncompatible
+ @AndroidIncompatible // depends on details of GC
public void testFreesNextReference() {
Iterator<Object> itr =
new AbstractIterator<Object>() {
@@ -191,7 +193,7 @@ public class AbstractIteratorTest extends TestCase {
@Override
protected Integer computeNext() {
boolean unused = hasNext();
- return null;
+ throw new AssertionError();
}
};
try {
diff --git a/android/guava-tests/test/com/google/common/base/AndroidIncompatible.java b/android/guava-tests/test/com/google/common/base/AndroidIncompatible.java
index 5e190a3e1..9ed987a26 100644
--- a/android/guava-tests/test/com/google/common/base/AndroidIncompatible.java
+++ b/android/guava-tests/test/com/google/common/base/AndroidIncompatible.java
@@ -30,7 +30,7 @@ import java.lang.annotation.Target;
/**
* Signifies that a test should not be run under Android. This annotation is respected only by our
* Google-internal Android suite generators. Note that those generators also suppress any test
- * annotated with MediumTest or LargeTest.
+ * annotated with LargeTest.
*
* <p>Why use a custom annotation instead of {@code android.test.suitebuilder.annotation.Suppress}?
* I'm not completely sure that this is the right choice, but it has various advantages:
diff --git a/android/guava-tests/test/com/google/common/base/AsciiTest.java b/android/guava-tests/test/com/google/common/base/AsciiTest.java
index 9e6b0e41a..371a6a304 100644
--- a/android/guava-tests/test/com/google/common/base/AsciiTest.java
+++ b/android/guava-tests/test/com/google/common/base/AsciiTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import junit.framework.TestCase;
/**
@@ -138,6 +139,7 @@ public class AsciiTest extends TestCase {
assertFalse(Ascii.equalsIgnoreCase("[", "{"));
}
+ @J2ktIncompatible
@GwtIncompatible // String.toUpperCase() has browser semantics
public void testEqualsIgnoreCaseUnicodeEquivalence() {
// Note that it's possible in future that the JDK's idea to toUpperCase() or equalsIgnoreCase()
diff --git a/android/guava-tests/test/com/google/common/base/CaseFormatTest.java b/android/guava-tests/test/com/google/common/base/CaseFormatTest.java
index f08d9f936..57c7e1725 100644
--- a/android/guava-tests/test/com/google/common/base/CaseFormatTest.java
+++ b/android/guava-tests/test/com/google/common/base/CaseFormatTest.java
@@ -24,6 +24,7 @@ import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
@@ -46,6 +47,7 @@ public class CaseFormatTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullArguments() {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/base/CharMatcherTest.java b/android/guava-tests/test/com/google/common/base/CharMatcherTest.java
index 49bdbbaff..d78327ef0 100644
--- a/android/guava-tests/test/com/google/common/base/CharMatcherTest.java
+++ b/android/guava-tests/test/com/google/common/base/CharMatcherTest.java
@@ -27,6 +27,7 @@ import static com.google.common.base.CharMatcher.whitespace;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Sets;
import com.google.common.testing.NullPointerTester;
import java.util.Arrays;
@@ -43,8 +44,10 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class CharMatcherTest extends TestCase {
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStaticNullPointers() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -90,6 +93,7 @@ public class CharMatcherTest extends TestCase {
// The next tests require ICU4J and have, at least for now, been sliced out
// of the open-source view of the tests.
+ @J2ktIncompatible
@GwtIncompatible // Character.isISOControl
public void testJavaIsoControl() {
for (int c = 0; c <= Character.MAX_VALUE; c++) {
@@ -108,6 +112,7 @@ public class CharMatcherTest extends TestCase {
// method, but by overall "scenario". Also, the variety of actual tests we
// do borders on absurd overkill. Better safe than sorry, though?
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
public void testSetBits() {
doTestSetBits(CharMatcher.any());
@@ -128,6 +133,7 @@ public class CharMatcherTest extends TestCase {
doTestSetBits(inRange('A', 'Z').and(inRange('F', 'K').negate()));
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
private void doTestSetBits(CharMatcher matcher) {
BitSet bitset = new BitSet();
@@ -151,6 +157,7 @@ public class CharMatcherTest extends TestCase {
doTestEmpty(forPredicate(Predicates.equalTo('c')));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNull() throws Exception {
doTestNull(CharMatcher.any());
@@ -196,6 +203,7 @@ public class CharMatcherTest extends TestCase {
assertEquals(0, matcher.countIn(""));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
private static void doTestNull(CharMatcher matcher) throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -644,6 +652,14 @@ public class CharMatcherTest extends TestCase {
assertEquals("12 &gt; 5", is('>').replaceFrom("12 > 5", "&gt;"));
}
+ public void testRetainFrom() {
+ assertEquals("aaa", is('a').retainFrom("bazaar"));
+ assertEquals("z", is('z').retainFrom("bazaar"));
+ assertEquals("!", is('!').retainFrom("!@#$%^&*()-="));
+ assertEquals("", is('x').retainFrom("bazaar"));
+ assertEquals("", is('a').retainFrom(""));
+ }
+
public void testPrecomputedOptimizations() {
// These are testing behavior that's never promised by the API.
// Some matchers are so efficient that it is a waste of effort to
@@ -664,11 +680,13 @@ public class CharMatcherTest extends TestCase {
assertSame(CharMatcher.any(), CharMatcher.any().precomputed());
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
private static BitSet bitSet(String chars) {
return bitSet(chars.toCharArray());
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
private static BitSet bitSet(char[] chars) {
BitSet tmp = new BitSet();
@@ -678,6 +696,7 @@ public class CharMatcherTest extends TestCase {
return tmp;
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.Random, java.util.BitSet
public void testSmallCharMatcher() {
CharMatcher len1 = SmallCharMatcher.from(bitSet("#"), "#");
diff --git a/android/guava-tests/test/com/google/common/base/CharsetsTest.java b/android/guava-tests/test/com/google/common/base/CharsetsTest.java
index c968c8d39..8ff80d0f7 100644
--- a/android/guava-tests/test/com/google/common/base/CharsetsTest.java
+++ b/android/guava-tests/test/com/google/common/base/CharsetsTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.charset.Charset;
import java.util.Arrays;
import junit.framework.TestCase;
@@ -30,11 +31,13 @@ import junit.framework.TestCase;
@GwtCompatible(emulated = true)
public class CharsetsTest extends TestCase {
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUsAscii() {
assertEquals(Charset.forName("US-ASCII"), Charsets.US_ASCII);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testIso88591() {
assertEquals(Charset.forName("ISO-8859-1"), Charsets.ISO_8859_1);
@@ -44,21 +47,25 @@ public class CharsetsTest extends TestCase {
assertEquals(Charset.forName("UTF-8"), Charsets.UTF_8);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16be() {
assertEquals(Charset.forName("UTF-16BE"), Charsets.UTF_16BE);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16le() {
assertEquals(Charset.forName("UTF-16LE"), Charsets.UTF_16LE);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16() {
assertEquals(Charset.forName("UTF-16"), Charsets.UTF_16);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testWhyUsAsciiIsDangerous() {
byte[] b1 = "朝日新聞".getBytes(Charsets.US_ASCII);
diff --git a/android/guava-tests/test/com/google/common/base/EnumsTest.java b/android/guava-tests/test/com/google/common/base/EnumsTest.java
index d8b13af75..66dfe591a 100644
--- a/android/guava-tests/test/com/google/common/base/EnumsTest.java
+++ b/android/guava-tests/test/com/google/common/base/EnumsTest.java
@@ -20,8 +20,8 @@ import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.common.truth.Truth.assertThat;
-import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.GcFinalization;
@@ -44,7 +44,8 @@ import junit.framework.TestCase;
*
* @author Steve McKay
*/
-@GwtCompatible(emulated = true)
+@GwtIncompatible
+@J2ktIncompatible
public class EnumsTest extends TestCase {
private enum TestEnum {
@@ -80,7 +81,9 @@ public class EnumsTest extends TestCase {
}
+ @J2ktIncompatible
@GwtIncompatible // weak references
+ @AndroidIncompatible // depends on details of GC and classloading
public void testGetIfPresent_doesNotPreventClassUnloading() throws Exception {
WeakReference<?> shadowLoaderReference = doTestClassUnloading();
GcFinalization.awaitClear(shadowLoaderReference);
@@ -91,6 +94,7 @@ public class EnumsTest extends TestCase {
// new ClassLoader. If Enums.getIfPresent does caching that prevents the shadow TestEnum
// (and therefore its ClassLoader) from being unloaded, then this WeakReference will never be
// cleared.
+ @J2ktIncompatible
@GwtIncompatible // weak references
private WeakReference<?> doTestClassUnloading() throws Exception {
URLClassLoader shadowLoader = new URLClassLoader(getClassPathUrls(), null);
@@ -112,6 +116,7 @@ public class EnumsTest extends TestCase {
return new WeakReference<>(shadowLoader);
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_convert() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertEquals(TestEnum.CHEETO, converter.convert("CHEETO"));
@@ -121,6 +126,7 @@ public class EnumsTest extends TestCase {
assertNull(converter.reverse().convert(null));
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_convertError() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
try {
@@ -130,6 +136,7 @@ public class EnumsTest extends TestCase {
}
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_reverse() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertEquals("CHEETO", converter.reverse().convert(TestEnum.CHEETO));
@@ -137,19 +144,22 @@ public class EnumsTest extends TestCase {
assertEquals("POODLE", converter.reverse().convert(TestEnum.POODLE));
}
- @GwtIncompatible // NullPointerTester
+ @J2ktIncompatible
+ @GwtIncompatible // stringConverter
public void testStringConverter_nullPointerTester() throws Exception {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicInstanceMethods(converter);
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_nullConversions() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertNull(converter.convert(null));
assertNull(converter.reverse().convert(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Class.getName()
public void testStringConverter_toString() {
assertEquals(
@@ -157,10 +167,12 @@ public class EnumsTest extends TestCase {
Enums.stringConverter(TestEnum.class).toString());
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_serialization() {
SerializableTester.reserializeAndAssert(Enums.stringConverter(TestEnum.class));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
@@ -176,6 +188,7 @@ public class EnumsTest extends TestCase {
BAR
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testGetField() {
Field foo = Enums.getField(AnEnum.FOO);
@@ -187,6 +200,7 @@ public class EnumsTest extends TestCase {
assertFalse(bar.isAnnotationPresent(ExampleAnnotation.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Class.getClassLoader()
private URL[] getClassPathUrls() {
ClassLoader classLoader = getClass().getClassLoader();
@@ -200,6 +214,7 @@ public class EnumsTest extends TestCase {
* System#getProperty system property}.
*/
// TODO(b/65488446): Make this a public API.
+ @J2ktIncompatible
@GwtIncompatible
private static ImmutableList<URL> parseJavaClassPath() {
ImmutableList.Builder<URL> urls = ImmutableList.builder();
diff --git a/android/guava-tests/test/com/google/common/base/EquivalenceTest.java b/android/guava-tests/test/com/google/common/base/EquivalenceTest.java
index 07c86eae8..46b191a22 100644
--- a/android/guava-tests/test/com/google/common/base/EquivalenceTest.java
+++ b/android/guava-tests/test/com/google/common/base/EquivalenceTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Equivalence.Wrapper;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.EqualsTester;
@@ -31,6 +32,7 @@ import junit.framework.TestCase;
*
* @author Jige Yu
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class EquivalenceTest extends TestCase {
@SuppressWarnings("unchecked") // varargs
@@ -81,6 +83,7 @@ public class EquivalenceTest extends TestCase {
assertSame(test, wrapper.get());
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
SerializableTester.reserializeAndAssert(LENGTH_EQUIVALENCE.wrap("hello"));
@@ -157,10 +160,16 @@ public class EquivalenceTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
- public void testNulls() {
- new NullPointerTester().testAllPublicStaticMethods(Equivalence.class);
- new NullPointerTester().testAllPublicInstanceMethods(Equivalence.equals());
- new NullPointerTester().testAllPublicInstanceMethods(Equivalence.identity());
+ public void testNulls() throws NoSuchMethodException {
+ NullPointerTester tester = new NullPointerTester();
+ // Necessary until JDK15:
+ // https://bugs.openjdk.org/browse/JDK-8202469
+ tester.ignore(Equivalence.class.getMethod("wrap", Object.class));
+
+ tester.testAllPublicStaticMethods(Equivalence.class);
+ tester.testAllPublicInstanceMethods(Equivalence.equals());
+ tester.testAllPublicInstanceMethods(Equivalence.identity());
}
}
diff --git a/android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java b/android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
index 3e9912280..7838f371a 100644
--- a/android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
+++ b/android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
@@ -25,15 +25,20 @@ import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collections;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link FinalizableReferenceQueue}.
*
* @author Bob Lee
*/
+// - depends on details of GC and classloading
+// - .class files aren't available
+// - possibly no real concept of separate ClassLoaders?
+@AndroidIncompatible
public class FinalizableReferenceQueueTest extends TestCase {
- private FinalizableReferenceQueue frq;
+ private @Nullable FinalizableReferenceQueue frq;
@Override
protected void tearDown() throws Exception {
@@ -79,7 +84,7 @@ public class FinalizableReferenceQueueTest extends TestCase {
}
/** If we don't keep a strong reference to the reference object, it won't be enqueued. */
- FinalizableWeakReference<Object> reference;
+ @Nullable FinalizableWeakReference<Object> reference;
/** Create the FRQ in a method that goes out of scope so that we're sure it will be reclaimed. */
private void weaklyReferenceQueue() {
@@ -101,7 +106,6 @@ public class FinalizableReferenceQueueTest extends TestCase {
};
}
- @AndroidIncompatible // no concept of separate ClassLoaders
public void testDecoupledLoader() {
FinalizableReferenceQueue.DecoupledLoader decoupledLoader =
new FinalizableReferenceQueue.DecoupledLoader() {
@@ -141,7 +145,6 @@ public class FinalizableReferenceQueueTest extends TestCase {
}
}
- @AndroidIncompatible // TODO(cpovirk): How significant is this failure?
public void testGetFinalizerUrl() {
assertNotNull(getClass().getResource("internal/Finalizer.class"));
}
diff --git a/android/guava-tests/test/com/google/common/base/FunctionsTest.java b/android/guava-tests/test/com/google/common/base/FunctionsTest.java
index 1411c192b..75b7a9d56 100644
--- a/android/guava-tests/test/com/google/common/base/FunctionsTest.java
+++ b/android/guava-tests/test/com/google/common/base/FunctionsTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.testing.ClassSanityTester;
@@ -27,6 +28,7 @@ import com.google.common.testing.SerializableTester;
import java.io.Serializable;
import java.util.Map;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Functions}.
@@ -35,6 +37,7 @@ import junit.framework.TestCase;
* @author Vlad Patryshev
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class FunctionsTest extends TestCase {
public void testIdentity_same() {
@@ -48,6 +51,7 @@ public class FunctionsTest extends TestCase {
assertNotSame(new Long(135135L), identity.apply(new Long(135135L)));
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIdentitySerializable() {
checkCanReserializeSingleton(Functions.identity());
@@ -73,11 +77,13 @@ public class FunctionsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testToStringFunctionSerializable() {
checkCanReserializeSingleton(Functions.toStringFunction());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
@@ -107,6 +113,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithoutDefaultSerializable() {
checkCanReserialize(Functions.forMap(ImmutableMap.of(1, 2)));
@@ -132,6 +139,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithDefault_includeSerializable() {
Map<String, Integer> map = Maps.newHashMap();
@@ -152,6 +160,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithDefaultSerializable() {
checkCanReserialize(Functions.forMap(ImmutableMap.of(1, 2), 3));
@@ -171,6 +180,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithDefault_null_compareWithSerializable() {
ImmutableMap<String, Integer> map = ImmutableMap.of("One", 1);
@@ -235,6 +245,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testComposition_includeReserializabled() {
Map<String, Integer> mJapaneseToInteger = Maps.newHashMap();
@@ -273,9 +284,9 @@ public class FunctionsTest extends TestCase {
Functions.compose(numberToSpanish, japaneseToInteger);
}
- private static class HashCodeFunction implements Function<Object, Integer> {
+ private static class HashCodeFunction implements Function<@Nullable Object, Integer> {
@Override
- public Integer apply(Object o) {
+ public Integer apply(@Nullable Object o) {
return (o == null) ? 0 : o.hashCode();
}
}
@@ -332,6 +343,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForPredicateSerializable() {
checkCanReserialize(Functions.forPredicate(Predicates.equalTo(5)));
@@ -361,6 +373,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testConstantSerializable() {
checkCanReserialize(Functions.constant(5));
@@ -378,7 +391,7 @@ public class FunctionsTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof CountingSupplier) {
return this.value == ((CountingSupplier) obj).value;
}
@@ -406,16 +419,19 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForSupplierSerializable() {
checkCanReserialize(Functions.forSupplier(new CountingSupplier()));
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testNulls() throws Exception {
new ClassSanityTester().forAllPublicStaticMethods(Functions.class).testNulls();
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException: com.google.common.base.Function
// (I suspect that this and the other similar failures happen with ArbitraryInstances proxies.)
@@ -423,6 +439,7 @@ public class FunctionsTest extends TestCase {
new ClassSanityTester().forAllPublicStaticMethods(Functions.class).testEqualsAndSerializable();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
private static <Y> void checkCanReserialize(Function<? super Integer, Y> f) {
Function<? super Integer, Y> g = SerializableTester.reserializeAndAssert(f);
@@ -443,6 +460,7 @@ public class FunctionsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
private static <Y> void checkCanReserializeSingleton(Function<? super String, Y> f) {
Function<? super String, Y> g = SerializableTester.reserializeAndAssert(f);
diff --git a/android/guava-tests/test/com/google/common/base/JoinerTest.java b/android/guava-tests/test/com/google/common/base/JoinerTest.java
index d9ed34721..c5eb73d53 100644
--- a/android/guava-tests/test/com/google/common/base/JoinerTest.java
+++ b/android/guava-tests/test/com/google/common/base/JoinerTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
@@ -33,6 +34,7 @@ import java.util.Map.Entry;
import java.util.Set;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Joiner}.
@@ -40,6 +42,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class JoinerTest extends TestCase {
private static final Joiner J = Joiner.on("-");
@@ -162,12 +165,13 @@ public class JoinerTest extends TestCase {
private static final Appendable NASTY_APPENDABLE =
new Appendable() {
@Override
- public Appendable append(CharSequence csq) throws IOException {
+ public Appendable append(@Nullable CharSequence csq) throws IOException {
throw new IOException();
}
@Override
- public Appendable append(CharSequence csq, int start, int end) throws IOException {
+ public Appendable append(@Nullable CharSequence csq, int start, int end)
+ throws IOException {
throw new IOException();
}
@@ -359,6 +363,7 @@ public class JoinerTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // StringBuilder.append in GWT invokes Object.toString(), unlike the JRE version.
public void testDontConvertCharSequenceToString() {
assertEquals("foo,foo", Joiner.on(",").join(new DontStringMeBro(), new DontStringMeBro()));
@@ -367,6 +372,7 @@ public class JoinerTest extends TestCase {
Joiner.on(",").useForNull("bar").join(new DontStringMeBro(), null, new DontStringMeBro()));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java b/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java
new file mode 100644
index 000000000..6a7149d17
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java
@@ -0,0 +1,497 @@
+/*
+ * Copyright (C) 2014 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.base;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.testing.NullPointerTester;
+import java.util.Arrays;
+import java.util.Map;
+import junit.framework.TestCase;
+
+/** Tests for {@link MoreObjects}. */
+@GwtCompatible(emulated = true)
+public class MoreObjectsTest extends TestCase {
+ public void testFirstNonNull_withNonNull() {
+ String s1 = "foo";
+ String s2 = MoreObjects.firstNonNull(s1, "bar");
+ assertSame(s1, s2);
+
+ Long n1 = 42L;
+ Long n2 = MoreObjects.firstNonNull(null, n1);
+ assertSame(n1, n2);
+
+ Boolean b1 = true;
+ Boolean b2 = MoreObjects.firstNonNull(b1, null);
+ assertSame(b1, b2);
+ }
+
+ public void testFirstNonNull_throwsNullPointerException() {
+ try {
+ MoreObjects.firstNonNull(null, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testToStringHelperWithArrays() {
+ String[] strings = {"hello", "world"};
+ int[] ints = {2, 42};
+ Object[] objects = {"obj"};
+ String[] arrayWithNull = {null};
+ Object[] empty = {};
+ String toTest =
+ MoreObjects.toStringHelper("TSH")
+ .add("strings", strings)
+ .add("ints", ints)
+ .add("objects", objects)
+ .add("arrayWithNull", arrayWithNull)
+ .add("empty", empty)
+ .toString();
+ assertEquals(
+ "TSH{strings=[hello, world], ints=[2, 42], objects=[obj], arrayWithNull=[null], empty=[]}",
+ toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_instance() {
+ String toTest = MoreObjects.toStringHelper(this).toString();
+ assertEquals("MoreObjectsTest{}", toTest);
+ }
+
+ public void testConstructorLenient_instance() {
+ String toTest = MoreObjects.toStringHelper(this).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_innerClass() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ public void testConstructorLenient_innerClass() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_anonymousClass() {
+ String toTest = MoreObjects.toStringHelper(new Object() {}).toString();
+ assertEquals("{}", toTest);
+ }
+
+ public void testConstructorLenient_anonymousClass() {
+ String toTest = MoreObjects.toStringHelper(new Object() {}).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_classObject() {
+ String toTest = MoreObjects.toStringHelper(TestClass.class).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ public void testConstructorLenient_classObject() {
+ String toTest = MoreObjects.toStringHelper(TestClass.class).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ public void testConstructor_stringObject() {
+ String toTest = MoreObjects.toStringHelper("FooBar").toString();
+ assertEquals("FooBar{}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringHelper_localInnerClass() {
+ // Local inner classes have names ending like "Outer.$1Inner"
+ class LocalInnerClass {}
+ String toTest = MoreObjects.toStringHelper(new LocalInnerClass()).toString();
+ assertEquals("LocalInnerClass{}", toTest);
+ }
+
+ public void testToStringHelperLenient_localInnerClass() {
+ class LocalInnerClass {}
+ String toTest = MoreObjects.toStringHelper(new LocalInnerClass()).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringHelper_localInnerNestedClass() {
+ class LocalInnerClass {
+ class LocalInnerNestedClass {}
+ }
+ String toTest =
+ MoreObjects.toStringHelper(new LocalInnerClass().new LocalInnerNestedClass()).toString();
+ assertEquals("LocalInnerNestedClass{}", toTest);
+ }
+
+ public void testToStringHelperLenient_localInnerNestedClass() {
+ class LocalInnerClass {
+ class LocalInnerNestedClass {}
+ }
+ String toTest =
+ MoreObjects.toStringHelper(new LocalInnerClass().new LocalInnerNestedClass()).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringHelper_moreThanNineAnonymousClasses() {
+ // The nth anonymous class has a name ending like "Outer.$n"
+ Object o1 = new Object() {};
+ Object o2 = new Object() {};
+ Object o3 = new Object() {};
+ Object o4 = new Object() {};
+ Object o5 = new Object() {};
+ Object o6 = new Object() {};
+ Object o7 = new Object() {};
+ Object o8 = new Object() {};
+ Object o9 = new Object() {};
+ Object o10 = new Object() {};
+ String toTest = MoreObjects.toStringHelper(o10).toString();
+ assertEquals("{}", toTest);
+ }
+
+ public void testToStringHelperLenient_moreThanNineAnonymousClasses() {
+ // The nth anonymous class has a name ending like "Outer.$n"
+ Object o1 = new Object() {};
+ Object o2 = new Object() {};
+ Object o3 = new Object() {};
+ Object o4 = new Object() {};
+ Object o5 = new Object() {};
+ Object o6 = new Object() {};
+ Object o7 = new Object() {};
+ Object o8 = new Object() {};
+ Object o9 = new Object() {};
+ Object o10 = new Object() {};
+ String toTest = MoreObjects.toStringHelper(o10).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ // all remaining test are on an inner class with various fields
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_oneField() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString();
+ assertEquals("TestClass{field1=Hello}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_oneIntegerField() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", new Integer(42)).toString();
+ assertEquals("TestClass{field1=42}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_nullInteger() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", (Integer) null).toString();
+ assertEquals("TestClass{field1=null}", toTest);
+ }
+
+ public void testToStringLenient_oneField() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString();
+ assertTrue(toTest, toTest.matches(".*\\{field1\\=Hello\\}"));
+ }
+
+ public void testToStringLenient_oneIntegerField() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", new Integer(42)).toString();
+ assertTrue(toTest, toTest.matches(".*\\{field1\\=42\\}"));
+ }
+
+ public void testToStringLenient_nullInteger() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", (Integer) null).toString();
+ assertTrue(toTest, toTest.matches(".*\\{field1\\=null\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_complexFields() {
+ Map<String, Integer> map =
+ ImmutableMap.<String, Integer>builder().put("abc", 1).put("def", 2).put("ghi", 3).build();
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", "This is string.")
+ .add("field2", Arrays.asList("abc", "def", "ghi"))
+ .add("field3", map)
+ .toString();
+ final String expected =
+ "TestClass{"
+ + "field1=This is string., field2=[abc, def, ghi], field3={abc=1, def=2, ghi=3}}";
+
+ assertEquals(expected, toTest);
+ }
+
+ public void testToStringLenient_complexFields() {
+ Map<String, Integer> map =
+ ImmutableMap.<String, Integer>builder().put("abc", 1).put("def", 2).put("ghi", 3).build();
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", "This is string.")
+ .add("field2", Arrays.asList("abc", "def", "ghi"))
+ .add("field3", map)
+ .toString();
+ final String expectedRegex =
+ ".*\\{"
+ + "field1\\=This is string\\., "
+ + "field2\\=\\[abc, def, ghi\\], "
+ + "field3=\\{abc\\=1, def\\=2, ghi\\=3\\}\\}";
+
+ assertTrue(toTest, toTest.matches(expectedRegex));
+ }
+
+ public void testToString_addWithNullName() {
+ MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass());
+ try {
+ helper.add(null, "Hello");
+ fail("No exception was thrown.");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_addWithNullValue() {
+ final String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString();
+
+ assertEquals("TestClass{Hello=null}", result);
+ }
+
+ public void testToStringLenient_addWithNullValue() {
+ final String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString();
+ assertTrue(result, result.matches(".*\\{Hello\\=null\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_ToStringTwice() {
+ MoreObjects.ToStringHelper helper =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", 1)
+ .addValue("value1")
+ .add("field2", "value2");
+ final String expected = "TestClass{field1=1, value1, field2=value2}";
+
+ assertEquals(expected, helper.toString());
+ // Call toString again
+ assertEquals(expected, helper.toString());
+
+ // Make sure the cached value is reset when we modify the helper at all
+ final String expected2 = "TestClass{field1=1, value1, field2=value2, 2}";
+ helper.addValue(2);
+ assertEquals(expected2, helper.toString());
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_addValue() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", 1)
+ .addValue("value1")
+ .add("field2", "value2")
+ .addValue(2)
+ .toString();
+ final String expected = "TestClass{field1=1, value1, field2=value2, 2}";
+
+ assertEquals(expected, toTest);
+ }
+
+ public void testToStringLenient_addValue() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", 1)
+ .addValue("value1")
+ .add("field2", "value2")
+ .addValue(2)
+ .toString();
+ final String expected = ".*\\{field1\\=1, value1, field2\\=value2, 2\\}";
+
+ assertTrue(toTest, toTest.matches(expected));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_addValueWithNullValue() {
+ final String result =
+ MoreObjects.toStringHelper(new TestClass())
+ .addValue(null)
+ .addValue("Hello")
+ .addValue(null)
+ .toString();
+ final String expected = "TestClass{null, Hello, null}";
+
+ assertEquals(expected, result);
+ }
+
+ public void testToStringLenient_addValueWithNullValue() {
+ final String result =
+ MoreObjects.toStringHelper(new TestClass())
+ .addValue(null)
+ .addValue("Hello")
+ .addValue(null)
+ .toString();
+ final String expected = ".*\\{null, Hello, null\\}";
+
+ assertTrue(result, result.matches(expected));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_oneField() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).omitNullValues().add("field1", null).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyFieldsFirstNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .add("field1", null)
+ .add("field2", "Googley")
+ .add("field3", "World")
+ .toString();
+ assertEquals("TestClass{field2=Googley, field3=World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyFieldsOmitAfterNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", null)
+ .add("field2", "Googley")
+ .add("field3", "World")
+ .omitNullValues()
+ .toString();
+ assertEquals("TestClass{field2=Googley, field3=World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyFieldsLastNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .add("field1", "Hello")
+ .add("field2", "Googley")
+ .add("field3", null)
+ .toString();
+ assertEquals("TestClass{field1=Hello, field2=Googley}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_oneValue() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).omitNullValues().addValue(null).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyValuesFirstNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .addValue(null)
+ .addValue("Googley")
+ .addValue("World")
+ .toString();
+ assertEquals("TestClass{Googley, World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyValuesLastNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .addValue("Hello")
+ .addValue("Googley")
+ .addValue(null)
+ .toString();
+ assertEquals("TestClass{Hello, Googley}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_differentOrder() {
+ String expected = "TestClass{field1=Hello, field2=Googley, field3=World}";
+ String toTest1 =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .add("field1", "Hello")
+ .add("field2", "Googley")
+ .add("field3", "World")
+ .toString();
+ String toTest2 =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", "Hello")
+ .add("field2", "Googley")
+ .omitNullValues()
+ .add("field3", "World")
+ .toString();
+ assertEquals(expected, toTest1);
+ assertEquals(expected, toTest2);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_canBeCalledManyTimes() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .omitNullValues()
+ .add("field1", "Hello")
+ .omitNullValues()
+ .add("field2", "Googley")
+ .omitNullValues()
+ .add("field3", "World")
+ .toString();
+ assertEquals("TestClass{field1=Hello, field2=Googley, field3=World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible("NullPointerTester")
+ public void testNulls() throws Exception {
+ NullPointerTester tester = new NullPointerTester();
+ tester.ignore(MoreObjects.class.getMethod("firstNonNull", Object.class, Object.class));
+ tester.testAllPublicStaticMethods(MoreObjects.class);
+ tester.testAllPublicInstanceMethods(MoreObjects.toStringHelper(new TestClass()));
+ }
+
+ /** Test class for testing formatting of inner classes. */
+ private static class TestClass {}
+}
diff --git a/android/guava-tests/test/com/google/common/base/ObjectsTest.java b/android/guava-tests/test/com/google/common/base/ObjectsTest.java
index 03881402a..34428e223 100644
--- a/android/guava-tests/test/com/google/common/base/ObjectsTest.java
+++ b/android/guava-tests/test/com/google/common/base/ObjectsTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import junit.framework.TestCase;
@@ -58,6 +59,7 @@ public class ObjectsTest extends TestCase {
assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(2, 3, 1));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/base/OptionalTest.java b/android/guava-tests/test/com/google/common/base/OptionalTest.java
index ba6ace7e9..ea930dc21 100644
--- a/android/guava-tests/test/com/google/common/base/OptionalTest.java
+++ b/android/guava-tests/test/com/google/common/base/OptionalTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.EqualsTester;
@@ -29,12 +30,14 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Optional}.
*
* @author Kurt Alfred Kluever
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public final class OptionalTest extends TestCase {
public void testAbsent() {
@@ -183,12 +186,13 @@ public final class OptionalTest extends TestCase {
Optional<String> unused =
Optional.of("a")
.transform(
- new Function<String, String>() {
- @Override
- public String apply(String input) {
- return null;
- }
- });
+ (Function<String, String>)
+ new Function<String, @Nullable String>() {
+ @Override
+ public @Nullable String apply(String input) {
+ return null;
+ }
+ });
fail("Should throw if Function returns null.");
} catch (NullPointerException expected) {
}
@@ -199,12 +203,13 @@ public final class OptionalTest extends TestCase {
Optional.absent(),
Optional.absent()
.transform(
- new Function<Object, Object>() {
- @Override
- public Object apply(Object input) {
- return null;
- }
- }));
+ (Function<Object, Object>)
+ new Function<Object, @Nullable Object>() {
+ @Override
+ public @Nullable Object apply(Object input) {
+ return null;
+ }
+ }));
}
public void testEqualsAndHashCode() {
@@ -298,6 +303,7 @@ public final class OptionalTest extends TestCase {
Number value = first.or(0.5); // fine
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester npTester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/base/PreconditionsTest.java b/android/guava-tests/test/com/google/common/base/PreconditionsTest.java
index 1add44d32..6209d3a06 100644
--- a/android/guava-tests/test/com/google/common/base/PreconditionsTest.java
+++ b/android/guava-tests/test/com/google/common/base/PreconditionsTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
@@ -31,6 +32,7 @@ import java.util.Arrays;
import java.util.List;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Preconditions}.
@@ -38,6 +40,9 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
* @author Jared Levy
*/
+@ElementTypesAreNonnullByDefault
+@J2ktIncompatible // TODO(b/278877942): Enable
+@SuppressWarnings("LenientFormatStringValidation") // Intentional for testing
@GwtCompatible(emulated = true)
public class PreconditionsTest extends TestCase {
public void testCheckArgument_simple_success() {
@@ -384,6 +389,7 @@ public class PreconditionsTest extends TestCase {
}
@GwtIncompatible("Reflection")
+ @J2ktIncompatible
public void testAllOverloads_checkArgument() throws Exception {
for (ImmutableList<Class<?>> sig : allSignatures(boolean.class)) {
Method checkArgumentMethod =
@@ -401,6 +407,7 @@ public class PreconditionsTest extends TestCase {
}
@GwtIncompatible("Reflection")
+ @J2ktIncompatible
public void testAllOverloads_checkState() throws Exception {
for (ImmutableList<Class<?>> sig : allSignatures(boolean.class)) {
Method checkArgumentMethod =
@@ -418,6 +425,7 @@ public class PreconditionsTest extends TestCase {
}
@GwtIncompatible("Reflection")
+ @J2ktIncompatible
public void testAllOverloads_checkNotNull() throws Exception {
for (ImmutableList<Class<?>> sig : allSignatures(Object.class)) {
Method checkArgumentMethod =
@@ -461,7 +469,9 @@ public class PreconditionsTest extends TestCase {
* @param sig The method signature
*/
@GwtIncompatible("ArbitraryInstances")
- private Object[] getParametersForSignature(Object firstParam, ImmutableList<Class<?>> sig) {
+ @J2ktIncompatible
+ private Object[] getParametersForSignature(
+ @Nullable Object firstParam, ImmutableList<Class<?>> sig) {
Object[] params = new Object[sig.size()];
params[0] = firstParam;
if (params.length > 1) {
@@ -536,6 +546,7 @@ public class PreconditionsTest extends TestCase {
Preconditions.checkState(boxedBoolean.booleanValue(), "", s);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
/*
diff --git a/android/guava-tests/test/com/google/common/base/PredicatesTest.java b/android/guava-tests/test/com/google/common/base/PredicatesTest.java
index 8f8647f4d..24b4e108b 100644
--- a/android/guava-tests/test/com/google/common/base/PredicatesTest.java
+++ b/android/guava-tests/test/com/google/common/base/PredicatesTest.java
@@ -21,6 +21,7 @@ import static com.google.common.collect.Lists.newArrayList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.EqualsTester;
@@ -36,12 +37,15 @@ import java.util.List;
import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Predicates}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
+@J2ktIncompatible // TODO(b/278877942): Enable
@GwtCompatible(emulated = true)
public class PredicatesTest extends TestCase {
private static final Predicate<Integer> TRUE = Predicates.alwaysTrue();
@@ -69,7 +73,7 @@ public class PredicatesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof IsOdd;
}
@@ -105,6 +109,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testAlwaysTrue_serialization() {
checkSerialization(Predicates.alwaysTrue());
@@ -126,6 +131,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testAlwaysFalse_serialization() {
checkSerialization(Predicates.alwaysFalse());
@@ -175,6 +181,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testNot_serialization() {
checkSerialization(Predicates.not(isOdd()));
@@ -198,6 +205,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationNoArgs() {
@@ -221,6 +229,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationOneArg() {
@@ -243,6 +252,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testAnd_serializationBinary() {
checkSerialization(Predicates.and(TRUE, isOdd()));
@@ -268,6 +278,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationTernary() {
@@ -295,6 +306,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationIterable() {
@@ -351,6 +363,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationNoArgs() {
@@ -374,6 +387,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationOneArg() {
@@ -400,6 +414,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testOr_serializationBinary() {
checkSerialization(Predicates.or(isOdd(), TRUE));
@@ -424,6 +439,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationTernary() {
@@ -457,6 +473,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationIterable() {
@@ -517,6 +534,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIsEqualTo_serialization() {
checkSerialization(Predicates.equalTo(1));
@@ -536,6 +554,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIsEqualToNull_serialization() {
checkSerialization(Predicates.equalTo(null));
@@ -546,6 +565,7 @@ public class PredicatesTest extends TestCase {
* stripper to remove comments properly. Currently, all tests before the comments are removed as
* well.
*/
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_apply() {
Predicate<Object> isInteger = Predicates.instanceOf(Integer.class);
@@ -556,6 +576,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isInteger.apply(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_subclass() {
Predicate<Object> isNumber = Predicates.instanceOf(Number.class);
@@ -566,6 +587,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isNumber.apply(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_interface() {
Predicate<Object> isComparable = Predicates.instanceOf(Comparable.class);
@@ -576,6 +598,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isComparable.apply(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_equality() {
new EqualsTester()
@@ -586,11 +609,13 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf, SerializableTester
public void testIsInstanceOf_serialization() {
checkSerialization(Predicates.instanceOf(Integer.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_apply() {
Predicate<Class<?>> isInteger = Predicates.subtypeOf(Integer.class);
@@ -605,6 +630,7 @@ public class PredicatesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_subclass() {
Predicate<Class<?>> isNumber = Predicates.subtypeOf(Number.class);
@@ -613,6 +639,7 @@ public class PredicatesTest extends TestCase {
assertTrue(isNumber.apply(Float.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_interface() {
Predicate<Class<?>> isComparable = Predicates.subtypeOf(Comparable.class);
@@ -621,6 +648,7 @@ public class PredicatesTest extends TestCase {
assertTrue(isComparable.apply(Float.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_equality() {
new EqualsTester()
@@ -630,6 +658,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf, SerializableTester
public void testSubtypeOf_serialization() {
Predicate<Class<?>> predicate = Predicates.subtypeOf(Integer.class);
@@ -657,6 +686,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIsNull_serialization() {
Predicate<String> pre = Predicates.isNull();
@@ -678,6 +708,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testNotNull_serialization() {
checkSerialization(Predicates.notNull());
@@ -709,6 +740,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIn_serialization() {
checkSerialization(Predicates.in(Arrays.asList(1, 2, 3, null)));
@@ -757,6 +789,7 @@ public class PredicatesTest extends TestCase {
// Predicate<Integer> p4 = Predicates.<Integer>in(nums);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
@@ -764,7 +797,8 @@ public class PredicatesTest extends TestCase {
}
@SuppressWarnings("unchecked") // varargs
- @GwtIncompatible // SerializbleTester
+ @J2ktIncompatible
+ @GwtIncompatible // SerializableTester
public void testCascadingSerialization() throws Exception {
// Eclipse says Predicate<Integer>; javac says Predicate<Object>.
Predicate<? super Integer> nasty =
@@ -815,6 +849,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testComposeSerialization() {
Function<String, String> trim = TrimStringFunction.INSTANCE;
@@ -828,6 +863,7 @@ public class PredicatesTest extends TestCase {
* works, so there are only trivial tests of that aspect. TODO: Fix comment style once annotation
* stripper is fixed.
*/
+ @J2ktIncompatible
@GwtIncompatible // Predicates.containsPattern
public void testContainsPattern_apply() {
Predicate<CharSequence> isFoobar = Predicates.containsPattern("^Fo.*o.*bar$");
@@ -835,6 +871,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isFoobar.apply("Foobarx"));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.containsPattern
public void testContains_apply() {
Predicate<CharSequence> isFoobar = Predicates.contains(Pattern.compile("^Fo.*o.*bar$"));
@@ -843,6 +880,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isFoobar.apply("Foobarx"));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testContainsPattern_nulls() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -851,6 +889,7 @@ public class PredicatesTest extends TestCase {
tester.testAllPublicInstanceMethods(isWooString);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testContains_nulls() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -859,6 +898,7 @@ public class PredicatesTest extends TestCase {
tester.testAllPublicInstanceMethods(isWooPattern);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testContainsPattern_serialization() {
Predicate<CharSequence> pre = Predicates.containsPattern("foo");
@@ -866,6 +906,7 @@ public class PredicatesTest extends TestCase {
assertEquals(pre.apply("foo"), post.apply("foo"));
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testContains_equals() {
new EqualsTester()
@@ -897,11 +938,13 @@ public class PredicatesTest extends TestCase {
assertTrue(Predicates.and(p1, p2).hashCode() != Predicates.or(p1, p2).hashCode());
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testNulls() throws Exception {
new ClassSanityTester().forAllPublicStaticMethods(Predicates.class).testNulls();
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException: com.google.common.base.Function
public void testEqualsAndSerializable() throws Exception {
@@ -956,6 +999,7 @@ public class PredicatesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
private static void checkSerialization(Predicate<? super Integer> predicate) {
Predicate<? super Integer> reserialized = SerializableTester.reserializeAndAssert(predicate);
diff --git a/android/guava-tests/test/com/google/common/base/SplitterTest.java b/android/guava-tests/test/com/google/common/base/SplitterTest.java
index 46928aa36..728e57aff 100644
--- a/android/guava-tests/test/com/google/common/base/SplitterTest.java
+++ b/android/guava-tests/test/com/google/common/base/SplitterTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Splitter.MapSplitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.NullPointerTester;
@@ -29,7 +30,10 @@ import java.util.Map;
import java.util.regex.Pattern;
import junit.framework.TestCase;
-/** @author Julien Silland */
+/**
+ * @author Julien Silland
+ */
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class SplitterTest extends TestCase {
@@ -287,6 +291,7 @@ public class SplitterTest extends TestCase {
.inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSimpleSplit() {
String simple = "a,b,c";
@@ -294,6 +299,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSimpleSplitWithNoDelimiter() {
String simple = "a,b,c";
@@ -301,6 +307,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a,b,c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithDoubleDelimiter() {
String doubled = "a,,b,c";
@@ -308,6 +315,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithDoubleDelimiterAndSpace() {
String doubled = "a,, b,c";
@@ -315,6 +323,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "", " b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithTrailingDelimiter() {
String trailing = "a,b,c,";
@@ -322,6 +331,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c", "").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithLeadingDelimiter() {
String leading = ",a,b,c";
@@ -331,6 +341,7 @@ public class SplitterTest extends TestCase {
// TODO(kevinb): the name of this method suggests it might not actually be testing what it
// intends to be testing?
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithMultipleLetters() {
Iterable<String> testPatterningMotto =
@@ -340,11 +351,13 @@ public class SplitterTest extends TestCase {
.inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
private static Pattern literalDotPattern() {
return Pattern.compile("\\.");
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithDoubleDelimiterOmitEmptyStrings() {
String doubled = "a..b.c";
@@ -352,6 +365,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
@AndroidIncompatible // Bug in older versions of Android we test against, since fixed.
public void testPatternSplitLookBehind() {
@@ -365,6 +379,7 @@ public class SplitterTest extends TestCase {
// splits into chunks ending in :
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
@AndroidIncompatible // Bug in older versions of Android we test against, since fixed.
public void testPatternSplitWordBoundary() {
@@ -373,6 +388,7 @@ public class SplitterTest extends TestCase {
assertThat(words).containsExactly("foo", "<", "bar", ">", "bletch").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWordBoundary_singleCharInput() {
String string = "f";
@@ -381,6 +397,7 @@ public class SplitterTest extends TestCase {
}
@AndroidIncompatible // Apparently Gingerbread's regex API is buggy.
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWordBoundary_singleWordInput() {
String string = "foo";
@@ -388,6 +405,7 @@ public class SplitterTest extends TestCase {
assertThat(words).containsExactly("foo").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitEmptyToken() {
String emptyToken = "a. .c";
@@ -395,6 +413,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitEmptyTokenOmitEmptyStrings() {
String emptyToken = "a. .c";
@@ -403,6 +422,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitOnOnlyDelimiter() {
Iterable<String> blankblank = Splitter.on(literalDotPattern()).split(".");
@@ -410,12 +430,14 @@ public class SplitterTest extends TestCase {
assertThat(blankblank).containsExactly("", "").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitOnOnlyDelimitersOmitEmptyStrings() {
Iterable<String> empty = Splitter.on(literalDotPattern()).omitEmptyStrings().split("...");
assertThat(empty).isEmpty();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitMatchingIsGreedy() {
String longDelimiter = "a, b, c";
@@ -423,6 +445,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithLongLeadingDelimiter() {
String longDelimiter = ", a, b, c";
@@ -430,6 +453,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("", "a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithLongTrailingDelimiter() {
String longDelimiter = "a, b, c/ ";
@@ -437,6 +461,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c", "").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitInvalidPattern() {
try {
@@ -446,6 +471,7 @@ public class SplitterTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithTrim() {
String jacksons =
@@ -467,6 +493,7 @@ public class SplitterTest extends TestCase {
assertIteratorIsUnmodifiable(Splitter.on(",").split("a,b").iterator());
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testSplitterIterableIsUnmodifiable_pattern() {
assertIteratorIsUnmodifiable(Splitter.on(Pattern.compile(",")).split("a,b").iterator());
@@ -489,6 +516,7 @@ public class SplitterTest extends TestCase {
assertSplitterIterableIsLazy(Splitter.on(","));
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
@AndroidIncompatible // not clear that j.u.r.Matcher promises to handle mutations during use
public void testSplitterIterableIsLazy_pattern() {
@@ -663,6 +691,7 @@ public class SplitterTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/base/StopwatchTest.java b/android/guava-tests/test/com/google/common/base/StopwatchTest.java
index b85ebb7b0..21d36d65c 100644
--- a/android/guava-tests/test/com/google/common/base/StopwatchTest.java
+++ b/android/guava-tests/test/com/google/common/base/StopwatchTest.java
@@ -21,6 +21,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.FakeTicker;
import junit.framework.TestCase;
@@ -166,6 +167,7 @@ public class StopwatchTest extends TestCase {
assertEquals(1, stopwatch.elapsed(MILLISECONDS));
}
+ @J2ktIncompatible // TODO(b/259213718): Enable
public void testToString() {
stopwatch.start();
assertEquals("0.000 ns", stopwatch.toString());
diff --git a/android/guava-tests/test/com/google/common/base/StringsTest.java b/android/guava-tests/test/com/google/common/base/StringsTest.java
index ac3ad20a5..c495ff5bf 100644
--- a/android/guava-tests/test/com/google/common/base/StringsTest.java
+++ b/android/guava-tests/test/com/google/common/base/StringsTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import junit.framework.TestCase;
@@ -28,6 +29,7 @@ import junit.framework.TestCase;
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class StringsTest extends TestCase {
public void testNullToEmpty() {
@@ -213,6 +215,7 @@ public class StringsTest extends TestCase {
assertFalse(Strings.validSurrogatePairAt("\uD8ABx", 0));
}
+ @SuppressWarnings("LenientFormatStringValidation") // Intentional for testing.
public void testLenientFormat() {
assertEquals("%s", Strings.lenientFormat("%s"));
assertEquals("5", Strings.lenientFormat("%s", 5));
@@ -232,6 +235,7 @@ public class StringsTest extends TestCase {
assertEquals("(Object[])null", Strings.lenientFormat("%s", (Object[]) null));
}
+ @J2ktIncompatible
@GwtIncompatible // GWT reflection includes less data
public void testLenientFormat_badArgumentToString() {
assertThat(Strings.lenientFormat("boiler %s plate", new ThrowsOnToString()))
@@ -252,6 +256,7 @@ public class StringsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/base/SuppliersTest.java b/android/guava-tests/test/com/google/common/base/SuppliersTest.java
index a97fe656c..9befacc6f 100644
--- a/android/guava-tests/test/com/google/common/base/SuppliersTest.java
+++ b/android/guava-tests/test/com/google/common/base/SuppliersTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Lists;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.EqualsTester;
@@ -39,6 +40,7 @@ import junit.framework.TestCase;
* @author Laurence Gonsalves
* @author Harry Heymann
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class SuppliersTest extends TestCase {
@@ -126,6 +128,7 @@ public class SuppliersTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testMemoizeNonSerializable() throws Exception {
CountingSupplier countingSupplier = new CountingSupplier();
@@ -133,7 +136,7 @@ public class SuppliersTest extends TestCase {
assertThat(memoizedSupplier.toString()).isEqualTo("Suppliers.memoize(CountingSupplier)");
checkMemoize(countingSupplier, memoizedSupplier);
// Calls to the original memoized supplier shouldn't affect its copy.
- memoizedSupplier.get();
+ Object unused = memoizedSupplier.get();
assertThat(memoizedSupplier.toString())
.isEqualTo("Suppliers.memoize(<supplier that returned 10>)");
@@ -146,6 +149,7 @@ public class SuppliersTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testMemoizeSerializable() throws Exception {
SerializableCountingSupplier countingSupplier = new SerializableCountingSupplier();
@@ -153,12 +157,12 @@ public class SuppliersTest extends TestCase {
assertThat(memoizedSupplier.toString()).isEqualTo("Suppliers.memoize(CountingSupplier)");
checkMemoize(countingSupplier, memoizedSupplier);
// Calls to the original memoized supplier shouldn't affect its copy.
- memoizedSupplier.get();
+ Object unused = memoizedSupplier.get();
assertThat(memoizedSupplier.toString())
.isEqualTo("Suppliers.memoize(<supplier that returned 10>)");
Supplier<Integer> copy = reserialize(memoizedSupplier);
- memoizedSupplier.get();
+ Object unused2 = memoizedSupplier.get();
CountingSupplier countingCopy =
(CountingSupplier) ((Suppliers.MemoizingSupplier<Integer>) copy).delegate;
@@ -213,6 +217,7 @@ public class SuppliersTest extends TestCase {
assertEquals(Integer.valueOf(1), result.get(1));
}
+ @J2ktIncompatible
@GwtIncompatible // Thread.sleep
public void testMemoizeWithExpiration() throws InterruptedException {
CountingSupplier countingSupplier = new CountingSupplier();
@@ -223,6 +228,7 @@ public class SuppliersTest extends TestCase {
checkExpiration(countingSupplier, memoizedSupplier);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread.sleep, SerializationTester
public void testMemoizeWithExpirationSerialized() throws InterruptedException {
SerializableCountingSupplier countingSupplier = new SerializableCountingSupplier();
@@ -230,16 +236,17 @@ public class SuppliersTest extends TestCase {
Supplier<Integer> memoizedSupplier =
Suppliers.memoizeWithExpiration(countingSupplier, 75, TimeUnit.MILLISECONDS);
// Calls to the original memoized supplier shouldn't affect its copy.
- memoizedSupplier.get();
+ Object unused = memoizedSupplier.get();
Supplier<Integer> copy = reserialize(memoizedSupplier);
- memoizedSupplier.get();
+ Object unused2 = memoizedSupplier.get();
CountingSupplier countingCopy =
(CountingSupplier) ((Suppliers.ExpiringMemoizingSupplier<Integer>) copy).delegate;
checkExpiration(countingCopy, copy);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread.sleep
private void checkExpiration(
CountingSupplier countingSupplier, Supplier<Integer> memoizedSupplier)
@@ -278,8 +285,8 @@ public class SuppliersTest extends TestCase {
assertNull(nullSupplier.get());
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
-
public void testExpiringMemoizedSupplierThreadSafe() throws Throwable {
Function<Supplier<Boolean>, Supplier<Boolean>> memoizer =
new Function<Supplier<Boolean>, Supplier<Boolean>>() {
@@ -291,8 +298,8 @@ public class SuppliersTest extends TestCase {
testSupplierThreadSafe(memoizer);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
-
public void testMemoizedSupplierThreadSafe() throws Throwable {
Function<Supplier<Boolean>, Supplier<Boolean>> memoizer =
new Function<Supplier<Boolean>, Supplier<Boolean>>() {
@@ -304,8 +311,9 @@ public class SuppliersTest extends TestCase {
testSupplierThreadSafe(memoizer);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
- public void testSupplierThreadSafe(Function<Supplier<Boolean>, Supplier<Boolean>> memoizer)
+ private void testSupplierThreadSafe(Function<Supplier<Boolean>, Supplier<Boolean>> memoizer)
throws Throwable {
final AtomicInteger count = new AtomicInteger(0);
final AtomicReference<Throwable> thrown = new AtomicReference<>(null);
@@ -380,8 +388,8 @@ public class SuppliersTest extends TestCase {
assertEquals(1, count.get());
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
-
public void testSynchronizedSupplierThreadSafe() throws InterruptedException {
final Supplier<Integer> nonThreadSafe =
new Supplier<Integer>() {
@@ -405,7 +413,7 @@ public class SuppliersTest extends TestCase {
@Override
public void run() {
for (int j = 0; j < iterations; j++) {
- Suppliers.synchronizedSupplier(nonThreadSafe).get();
+ Object unused = Suppliers.synchronizedSupplier(nonThreadSafe).get();
}
}
};
@@ -427,6 +435,7 @@ public class SuppliersTest extends TestCase {
assertEquals(14, (int) supplierFunction.apply(supplier));
}
+ @J2ktIncompatible
@GwtIncompatible // SerializationTester
public void testSerialization() {
assertEquals(Integer.valueOf(5), reserialize(Suppliers.ofInstance(5)).get());
@@ -443,11 +452,13 @@ public class SuppliersTest extends TestCase {
reserialize(Suppliers.synchronizedSupplier(Suppliers.ofInstance(5))).get());
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testSuppliersNullChecks() throws Exception {
new ClassSanityTester().forAllPublicStaticMethods(Suppliers.class).testNulls();
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException: com.google.common.base.Function
public void testSuppliersSerializable() throws Exception {
diff --git a/android/guava-tests/test/com/google/common/base/ThrowablesTest.java b/android/guava-tests/test/com/google/common/base/ThrowablesTest.java
index e4c64aa8d..975765340 100644
--- a/android/guava-tests/test/com/google/common/base/ThrowablesTest.java
+++ b/android/guava-tests/test/com/google/common/base/ThrowablesTest.java
@@ -28,6 +28,7 @@ import static java.util.regex.Pattern.quote;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import com.google.common.testing.NullPointerTester;
@@ -62,6 +63,7 @@ public class ThrowablesTest extends TestCase {
throwIfUnchecked(new SomeCheckedException());
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_NoneThrown() {
Sample sample =
@@ -81,6 +83,7 @@ public class ThrowablesTest extends TestCase {
sample.noneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_UncheckedThrown() {
Sample sample =
@@ -104,6 +107,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_UndeclaredThrown() {
Sample sample =
@@ -127,6 +131,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_NoneThrown() throws SomeCheckedException {
Sample sample =
@@ -148,6 +153,7 @@ public class ThrowablesTest extends TestCase {
sample.oneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_UncheckedThrown() throws SomeCheckedException {
Sample sample =
@@ -171,6 +177,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_CheckedThrown() {
Sample sample =
@@ -194,6 +201,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_UndeclaredThrown() throws SomeCheckedException {
Sample sample =
@@ -217,6 +225,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_NoneThrown()
throws SomeCheckedException, SomeOtherCheckedException {
@@ -238,6 +247,7 @@ public class ThrowablesTest extends TestCase {
sample.twoDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_UncheckedThrown()
throws SomeCheckedException, SomeOtherCheckedException {
@@ -263,6 +273,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_CheckedThrown() throws SomeOtherCheckedException {
Sample sample =
@@ -287,6 +298,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_OtherCheckedThrown() throws SomeCheckedException {
Sample sample =
@@ -319,21 +331,25 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropageIfPossible_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null);
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropageIfPossible_OneDeclared_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null, SomeCheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropageIfPossible_TwoDeclared_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null, SomeCheckedException.class, SomeUncheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_NoneThrown() {
Sample sample =
@@ -352,6 +368,7 @@ public class ThrowablesTest extends TestCase {
sample.noneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_UncheckedThrown() {
Sample sample =
@@ -374,6 +391,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_ErrorThrown() {
Sample sample =
@@ -396,6 +414,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_CheckedThrown() {
Sample sample =
@@ -419,16 +438,19 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_Unchecked() throws SomeCheckedException {
throwIfInstanceOf(new SomeUncheckedException(), SomeCheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedDifferent() throws SomeCheckedException {
throwIfInstanceOf(new SomeOtherCheckedException(), SomeCheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedSame() {
try {
@@ -438,6 +460,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedSubclass() {
try {
@@ -447,6 +470,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_NoneThrown() throws SomeCheckedException {
Sample sample =
@@ -466,6 +490,7 @@ public class ThrowablesTest extends TestCase {
sample.oneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_DeclaredThrown() {
Sample sample =
@@ -489,6 +514,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_UncheckedThrown() throws SomeCheckedException {
Sample sample =
@@ -512,6 +538,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_UndeclaredThrown() throws SomeCheckedException {
Sample sample =
@@ -536,6 +563,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_null() throws SomeCheckedException {
try {
@@ -545,6 +573,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropageIfInstanceOf_null() throws SomeCheckedException {
Throwables.propagateIfInstanceOf(null, SomeCheckedException.class);
@@ -625,6 +654,7 @@ public class ThrowablesTest extends TestCase {
throw new SomeUndeclaredCheckedException();
}
+ @J2ktIncompatible
@GwtIncompatible // getStackTraceAsString(Throwable)
public void testGetStackTraceAsString() {
class StackTraceException extends Exception {
@@ -637,8 +667,9 @@ public class ThrowablesTest extends TestCase {
String firstLine = quote(e.getClass().getName() + ": " + e.getMessage());
String secondLine = "\\s*at " + ThrowablesTest.class.getName() + "\\..*";
- String moreLines = "(?:.*\n?)*";
- String expected = firstLine + "\n" + secondLine + "\n" + moreLines;
+ String moreLines = "(?:.*" + System.lineSeparator() + "?)*";
+ String expected =
+ firstLine + System.lineSeparator() + secondLine + System.lineSeparator() + moreLines;
assertThat(getStackTraceAsString(e)).matches(expected);
}
@@ -679,6 +710,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Throwables.getCauseAs(Throwable, Class)
public void testGetCauseAs() {
SomeCheckedException cause = new SomeCheckedException();
@@ -697,6 +729,7 @@ public class ThrowablesTest extends TestCase {
}
@AndroidIncompatible // No getJavaLangAccess in Android (at least not in the version we use).
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTraceIsLazy()
public void testLazyStackTraceWorksInProd() {
// TODO(b/64442212): Remove this guard once lazyStackTrace() works in Java 9+.
@@ -708,6 +741,7 @@ public class ThrowablesTest extends TestCase {
assertTrue(lazyStackTraceIsLazy());
}
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTrace(Throwable)
public void testLazyStackTrace() {
Exception e = new Exception();
@@ -731,6 +765,7 @@ public class ThrowablesTest extends TestCase {
assertThat(lazyStackTrace(e)).containsExactly((Object[]) originalStackTrace).inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTrace
private void doTestLazyStackTraceFallback() {
assertFalse(lazyStackTraceIsLazy());
@@ -749,6 +784,7 @@ public class ThrowablesTest extends TestCase {
assertThat(lazyStackTrace(e)).isEmpty();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
new NullPointerTester().testAllPublicStaticMethods(Throwables.class);
diff --git a/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java b/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java
index db15f2ef8..62ee89191 100644
--- a/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java
+++ b/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.Map;
@@ -31,6 +32,7 @@ import junit.framework.TestCase;
@GwtCompatible
public class ToStringHelperTest extends TestCase {
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_instance() {
String toTest = MoreObjects.toStringHelper(this).toString();
@@ -42,6 +44,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_innerClass() {
String toTest = MoreObjects.toStringHelper(new TestClass()).toString();
@@ -53,6 +56,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_anonymousClass() {
String toTest = MoreObjects.toStringHelper(new Object() {}).toString();
@@ -64,6 +68,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_classObject() {
String toTest = MoreObjects.toStringHelper(TestClass.class).toString();
@@ -80,6 +85,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("FooBar{}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringHelper_localInnerClass() {
// Local inner classes have names ending like "Outer.$1Inner"
@@ -94,6 +100,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringHelper_localInnerNestedClass() {
class LocalInnerClass {
@@ -113,6 +120,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringHelper_moreThanNineAnonymousClasses() {
// The nth anonymous class has a name ending like "Outer.$n"
@@ -147,12 +155,14 @@ public class ToStringHelperTest extends TestCase {
}
// all remaining test are on an inner class with various fields
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_oneField() {
String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString();
assertEquals("TestClass{field1=Hello}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_oneIntegerField() {
String toTest =
@@ -160,6 +170,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field1=42}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_nullInteger() {
String toTest =
@@ -184,6 +195,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{field1\\=null\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_complexFields() {
@@ -230,6 +242,7 @@ public class ToStringHelperTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_addWithNullValue() {
final String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString();
@@ -242,6 +255,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(result, result.matches(".*\\{Hello\\=null\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_ToStringTwice() {
MoreObjects.ToStringHelper helper =
@@ -261,6 +275,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals(expected2, helper.toString());
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_addValue() {
String toTest =
@@ -288,6 +303,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(expected));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_addValueWithNullValue() {
final String result =
@@ -313,6 +329,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(result, result.matches(expected));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_oneField() {
String toTest =
@@ -320,6 +337,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyFieldsFirstNull() {
String toTest =
@@ -332,6 +350,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field2=Googley, field3=World}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyFieldsOmitAfterNull() {
String toTest =
@@ -344,6 +363,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field2=Googley, field3=World}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyFieldsLastNull() {
String toTest =
@@ -356,6 +376,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field1=Hello, field2=Googley}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitEmptyValues_oneValue() {
String toTest =
@@ -363,6 +384,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyValuesFirstNull() {
String toTest =
@@ -375,6 +397,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{Googley, World}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyValuesLastNull() {
String toTest =
@@ -387,6 +410,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{Hello, Googley}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_differentOrder() {
String expected = "TestClass{field1=Hello, field2=Googley, field3=World}";
@@ -408,6 +432,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals(expected, toTest2);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_canBeCalledManyTimes() {
String toTest =
diff --git a/android/guava-tests/test/com/google/common/base/Utf8Test.java b/android/guava-tests/test/com/google/common/base/Utf8Test.java
index 049e8d2ab..57464a9ee 100644
--- a/android/guava-tests/test/com/google/common/base/Utf8Test.java
+++ b/android/guava-tests/test/com/google/common/base/Utf8Test.java
@@ -26,6 +26,7 @@ import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.HashMap;
@@ -187,18 +188,21 @@ public class Utf8Test extends TestCase {
FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
/** Tests that round tripping of all two byte permutations work. */
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
public void testIsWellFormed_1Byte() {
testBytes(1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
}
/** Tests that round tripping of all two byte permutations work. */
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
public void testIsWellFormed_2Bytes() {
testBytes(2, EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
}
/** Tests that round tripping of all three byte permutations work. */
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
public void testIsWellFormed_3Bytes() {
@@ -302,6 +306,7 @@ public class Utf8Test extends TestCase {
* @param numBytes the number of bytes in the byte array
* @param expectedCount the expected number of roundtrippable permutations
*/
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
private static void testBytes(int numBytes, long expectedCount) {
testBytes(numBytes, expectedCount, 0, -1);
@@ -317,6 +322,7 @@ public class Utf8Test extends TestCase {
* @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max
* limit for numBytes
*/
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
private static void testBytes(int numBytes, long expectedCount, long start, long lim) {
byte[] bytes = new byte[numBytes];
diff --git a/android/guava-tests/test/com/google/common/base/VerifyTest.java b/android/guava-tests/test/com/google/common/base/VerifyTest.java
index 37c6efc1a..36465ea30 100644
--- a/android/guava-tests/test/com/google/common/base/VerifyTest.java
+++ b/android/guava-tests/test/com/google/common/base/VerifyTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
@@ -93,6 +94,7 @@ public class VerifyTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
// Don't bother testing: Verify is like Preconditions. See the discussion on that class.
diff --git a/android/guava-tests/test/com/google/common/cache/AbstractCacheTest.java b/android/guava-tests/test/com/google/common/cache/AbstractCacheTest.java
index 13ef33db2..8602e5873 100644
--- a/android/guava-tests/test/com/google/common/cache/AbstractCacheTest.java
+++ b/android/guava-tests/test/com/google/common/cache/AbstractCacheTest.java
@@ -24,6 +24,7 @@ import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractCache}.
@@ -37,7 +38,7 @@ public class AbstractCacheTest extends TestCase {
Cache<Object, Object> cache =
new AbstractCache<Object, Object>() {
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -53,7 +54,7 @@ public class AbstractCacheTest extends TestCase {
Cache<Object, Object> cache =
new AbstractCache<Object, Object>() {
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return null;
}
};
@@ -67,7 +68,7 @@ public class AbstractCacheTest extends TestCase {
Cache<Object, Object> cache =
new AbstractCache<Object, Object>() {
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return cachedKey.equals(key) ? cachedValue : null;
}
};
diff --git a/android/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java b/android/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java
index c2ddef7b1..84e004a8b 100644
--- a/android/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java
+++ b/android/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java
@@ -23,6 +23,7 @@ import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractLoadingCache}.
@@ -46,7 +47,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -78,7 +79,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -110,7 +111,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -142,7 +143,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
diff --git a/android/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java b/android/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java
index 948b4b560..77a4734fb 100644
--- a/android/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java
+++ b/android/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java
@@ -26,7 +26,7 @@ import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Helper class for creating {@link CacheBuilder} instances with all combinations of several sets of
@@ -120,15 +120,15 @@ class CacheBuilderFactory {
private static final Function<Object, Optional<?>> NULLABLE_TO_OPTIONAL =
new Function<Object, Optional<?>>() {
@Override
- public Optional<?> apply(@CheckForNull Object obj) {
+ public Optional<?> apply(@Nullable Object obj) {
return Optional.fromNullable(obj);
}
};
- private static final Function<Optional<?>, Object> OPTIONAL_TO_NULLABLE =
- new Function<Optional<?>, Object>() {
+ private static final Function<Optional<?>, @Nullable Object> OPTIONAL_TO_NULLABLE =
+ new Function<Optional<?>, @Nullable Object>() {
@Override
- public Object apply(Optional<?> optional) {
+ public @Nullable Object apply(Optional<?> optional) {
return optional.orNull();
}
};
@@ -158,14 +158,14 @@ class CacheBuilderFactory {
}
private CacheBuilder<Object, Object> createCacheBuilder(
- Integer concurrencyLevel,
- Integer initialCapacity,
- Integer maximumSize,
- DurationSpec expireAfterWrite,
- DurationSpec expireAfterAccess,
- DurationSpec refresh,
- Strength keyStrength,
- Strength valueStrength) {
+ @Nullable Integer concurrencyLevel,
+ @Nullable Integer initialCapacity,
+ @Nullable Integer maximumSize,
+ @Nullable DurationSpec expireAfterWrite,
+ @Nullable DurationSpec expireAfterAccess,
+ @Nullable DurationSpec refresh,
+ @Nullable Strength keyStrength,
+ @Nullable Strength valueStrength) {
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (concurrencyLevel != null) {
@@ -214,7 +214,7 @@ class CacheBuilderFactory {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof DurationSpec) {
DurationSpec that = (DurationSpec) o;
return unit.toNanos(duration) == that.unit.toNanos(that.duration);
diff --git a/android/guava-tests/test/com/google/common/cache/CacheBuilderTest.java b/android/guava-tests/test/com/google/common/cache/CacheBuilderTest.java
index 1a9faeeae..3a3a571f7 100644
--- a/android/guava-tests/test/com/google/common/cache/CacheBuilderTest.java
+++ b/android/guava-tests/test/com/google/common/cache/CacheBuilderTest.java
@@ -399,7 +399,6 @@ public class CacheBuilderTest extends TestCase {
}
@GwtIncompatible // QueuingRemovalListener
-
public void testRemovalNotification_clear() throws InterruptedException {
// If a clear() happens while a computation is pending, we should not get a removal
// notification.
diff --git a/android/guava-tests/test/com/google/common/cache/CacheExpirationTest.java b/android/guava-tests/test/com/google/common/cache/CacheExpirationTest.java
index c1416bd7d..ef9b690b1 100644
--- a/android/guava-tests/test/com/google/common/cache/CacheExpirationTest.java
+++ b/android/guava-tests/test/com/google/common/cache/CacheExpirationTest.java
@@ -339,7 +339,7 @@ public class CacheExpirationTest extends TestCase {
assertThat(keySet).containsExactly(2, 3, 4, 5, 6, 7, 8, 9, 0);
// get(K, Callable) doesn't stop 2 from expiring
- cache.get(2, Callables.returning(-2));
+ Integer unused = cache.get(2, Callables.returning(-2));
CacheTesting.drainRecencyQueues(cache);
ticker.advance(1, MILLISECONDS);
assertThat(keySet).containsExactly(3, 4, 5, 6, 7, 8, 9, 0);
@@ -403,7 +403,7 @@ public class CacheExpirationTest extends TestCase {
// get(K, Callable) fails to save 8, replace saves 6
cache.asMap().replace(6, -6);
- cache.get(8, Callables.returning(-8));
+ Integer unused = cache.get(8, Callables.returning(-8));
CacheTesting.drainRecencyQueues(cache);
ticker.advance(1, MILLISECONDS);
assertThat(keySet).containsExactly(3, 6);
diff --git a/android/guava-tests/test/com/google/common/cache/CacheLoaderTest.java b/android/guava-tests/test/com/google/common/cache/CacheLoaderTest.java
index e078dddd7..6312e0c79 100644
--- a/android/guava-tests/test/com/google/common/cache/CacheLoaderTest.java
+++ b/android/guava-tests/test/com/google/common/cache/CacheLoaderTest.java
@@ -78,10 +78,10 @@ public class CacheLoaderTest extends TestCase {
assertEquals(0, reloadCount.get());
assertEquals(0, loadAllCount.get());
- baseLoader.load(new Object());
+ Object unused1 = baseLoader.load(new Object());
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError = baseLoader.reload(new Object(), new Object());
- baseLoader.loadAll(ImmutableList.of(new Object()));
+ Map<Object, Object> unused2 = baseLoader.loadAll(ImmutableList.of(new Object()));
assertEquals(1, loadCount.get());
assertEquals(1, reloadCount.get());
assertEquals(1, loadAllCount.get());
@@ -89,10 +89,10 @@ public class CacheLoaderTest extends TestCase {
QueuingExecutor executor = new QueuingExecutor();
CacheLoader<Object, Object> asyncReloader = CacheLoader.asyncReloading(baseLoader, executor);
- asyncReloader.load(new Object());
+ Object unused3 = asyncReloader.load(new Object());
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError1 = asyncReloader.reload(new Object(), new Object());
- asyncReloader.loadAll(ImmutableList.of(new Object()));
+ Map<Object, Object> unused4 = asyncReloader.loadAll(ImmutableList.of(new Object()));
assertEquals(2, loadCount.get());
assertEquals(1, reloadCount.get());
assertEquals(2, loadAllCount.get());
diff --git a/android/guava-tests/test/com/google/common/cache/CacheLoadingTest.java b/android/guava-tests/test/com/google/common/cache/CacheLoadingTest.java
index f5ea54603..9b193ed7f 100644
--- a/android/guava-tests/test/com/google/common/cache/CacheLoadingTest.java
+++ b/android/guava-tests/test/com/google/common/cache/CacheLoadingTest.java
@@ -1767,6 +1767,7 @@ public class CacheLoadingTest extends TestCase {
}
+ @AndroidIncompatible // Depends on GC behavior
public void testReloadAfterValueReclamation() throws InterruptedException, ExecutionException {
CountingLoader countingLoader = new CountingLoader();
LoadingCache<Object, Object> cache =
@@ -1941,7 +1942,7 @@ public class CacheLoadingTest extends TestCase {
}
}
-
+ @AndroidIncompatible // Bug? expected:<1> but was:<2>
public void testConcurrentLoading() throws InterruptedException {
testConcurrentLoading(CacheBuilder.newBuilder());
}
@@ -1954,7 +1955,7 @@ public class CacheLoadingTest extends TestCase {
testConcurrentLoadingCheckedException(builder);
}
-
+ @AndroidIncompatible // Bug? expected:<1> but was:<2>
public void testConcurrentExpirationLoading() throws InterruptedException {
testConcurrentLoading(CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS));
}
@@ -2184,7 +2185,6 @@ public class CacheLoadingTest extends TestCase {
return resultList;
}
-
public void testAsMapDuringLoading() throws InterruptedException, ExecutionException {
final CountDownLatch getStartedSignal = new CountDownLatch(2);
final CountDownLatch letGetFinishSignal = new CountDownLatch(1);
@@ -2243,7 +2243,6 @@ public class CacheLoadingTest extends TestCase {
assertEquals(refreshKey + suffix, map.get(refreshKey));
}
-
public void testInvalidateDuringLoading() throws InterruptedException, ExecutionException {
// computation starts; invalidate() is called on the key being computed, computation finishes
final CountDownLatch computationStarted = new CountDownLatch(2);
@@ -2300,7 +2299,6 @@ public class CacheLoadingTest extends TestCase {
assertEquals(2, cache.size());
}
-
public void testInvalidateAndReloadDuringLoading()
throws InterruptedException, ExecutionException {
// computation starts; clear() is called, computation finishes
@@ -2373,7 +2371,6 @@ public class CacheLoadingTest extends TestCase {
assertEquals(refreshKey + suffix, map.get(refreshKey));
}
-
public void testExpandDuringLoading() throws InterruptedException {
final int count = 3;
final AtomicInteger callCount = new AtomicInteger();
@@ -2463,7 +2460,6 @@ public class CacheLoadingTest extends TestCase {
}
// Test ignored because it is extremely flaky in CI builds
-
public void
ignoreTestExpandDuringRefresh()
throws InterruptedException, ExecutionException {
diff --git a/android/guava-tests/test/com/google/common/cache/CacheTesting.java b/android/guava-tests/test/com/google/common/cache/CacheTesting.java
index 4c58ed502..47a75c0ab 100644
--- a/android/guava-tests/test/com/google/common/cache/CacheTesting.java
+++ b/android/guava-tests/test/com/google/common/cache/CacheTesting.java
@@ -44,7 +44,7 @@ import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceArray;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A collection of utilities for {@link Cache} testing.
@@ -98,7 +98,7 @@ class CacheTesting {
}
/**
- * Forces the segment containing the given {@code key} to expand (see {@link Segment#expand()}.
+ * Forces the segment containing the given {@code key} to expand (see {@link Segment#expand()}).
*/
static <K, V> void forceExpandSegment(Cache<K, V> cache, K key) {
checkNotNull(cache);
@@ -367,7 +367,7 @@ class CacheTesting {
}
interface Receiver<T> {
- void accept(@CheckForNull T object);
+ void accept(@Nullable T object);
}
/**
diff --git a/android/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java b/android/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java
index 412ff7802..639a208bd 100644
--- a/android/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java
+++ b/android/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java
@@ -104,7 +104,7 @@ public class ForwardingCacheTest extends TestCase {
private static class OnlyGet<K, V> extends ForwardingCache<K, V> {
@Override
protected Cache<K, V> delegate() {
- return null;
+ throw new AssertionError();
}
}
}
diff --git a/android/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java b/android/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java
index d78db2d37..fe4161213 100644
--- a/android/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java
+++ b/android/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java
@@ -112,7 +112,7 @@ public class ForwardingLoadingCacheTest extends TestCase {
private static class OnlyGet<K, V> extends ForwardingLoadingCache<K, V> {
@Override
protected LoadingCache<K, V> delegate() {
- return null;
+ throw new AssertionError();
}
}
}
diff --git a/android/guava-tests/test/com/google/common/cache/LocalCacheTest.java b/android/guava-tests/test/com/google/common/cache/LocalCacheTest.java
index b8ec7dfe6..431c962f4 100644
--- a/android/guava-tests/test/com/google/common/cache/LocalCacheTest.java
+++ b/android/guava-tests/test/com/google/common/cache/LocalCacheTest.java
@@ -76,6 +76,7 @@ import java.util.logging.LogRecord;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** @author Charles Fry */
@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress.
@@ -97,7 +98,6 @@ public class LocalCacheTest extends TestCase {
}
}
-
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(LocalCacheTest.class);
@@ -330,7 +330,7 @@ public class LocalCacheTest extends TestCase {
}
public void testSetConcurrencyLevel() {
- // round up to nearest power of two
+ // round up to the nearest power of two
checkConcurrencyLevel(1, 1);
checkConcurrencyLevel(2, 2);
@@ -349,7 +349,7 @@ public class LocalCacheTest extends TestCase {
}
public void testSetInitialCapacity() {
- // share capacity over each segment, then round up to nearest power of two
+ // share capacity over each segment, then round up to the nearest power of two
checkInitialCapacity(1, 0, 1);
checkInitialCapacity(1, 1, 1);
@@ -701,7 +701,6 @@ public class LocalCacheTest extends TestCase {
assertEquals(1, map.size());
}
-
public void testCopyEntry_computing() {
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch computingSignal = new CountDownLatch(1);
@@ -803,7 +802,6 @@ public class LocalCacheTest extends TestCase {
checkLogged(e);
}
-
public void testRemovalListener_replaced_computing() {
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch computingSignal = new CountDownLatch(1);
@@ -2698,7 +2696,7 @@ public class LocalCacheTest extends TestCase {
// entries and values
private static <K, V> DummyEntry<K, V> createDummyEntry(
- K key, int hash, V value, ReferenceEntry<K, V> next) {
+ K key, int hash, V value, @Nullable ReferenceEntry<K, V> next) {
DummyEntry<K, V> entry = DummyEntry.create(key, hash, next);
DummyValueReference<K, V> valueRef = DummyValueReference.create(value);
entry.setValueReference(valueRef);
@@ -2706,7 +2704,7 @@ public class LocalCacheTest extends TestCase {
}
static class DummyEntry<K, V> implements ReferenceEntry<K, V> {
- private K key;
+ private @Nullable K key;
private final int hash;
private final ReferenceEntry<K, V> next;
@@ -2716,7 +2714,8 @@ public class LocalCacheTest extends TestCase {
this.next = next;
}
- public static <K, V> DummyEntry<K, V> create(K key, int hash, ReferenceEntry<K, V> next) {
+ public static <K, V> DummyEntry<K, V> create(
+ K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new DummyEntry<>(key, hash, next);
}
@@ -2825,7 +2824,7 @@ public class LocalCacheTest extends TestCase {
}
static class DummyValueReference<K, V> implements ValueReference<K, V> {
- private V value;
+ private @Nullable V value;
boolean loading = false;
public DummyValueReference() {
@@ -2855,7 +2854,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public ReferenceEntry<K, V> getEntry() {
+ public @Nullable ReferenceEntry<K, V> getEntry() {
return null;
}
@@ -2905,7 +2904,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableCacheLoader);
}
}
@@ -2921,7 +2920,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableRemovalListener);
}
}
@@ -2938,7 +2937,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableTicker);
}
}
@@ -2955,7 +2954,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableWeigher);
}
}
diff --git a/android/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java b/android/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java
index 8ba9dbc97..3a7f416ea 100644
--- a/android/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java
+++ b/android/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java
@@ -157,7 +157,7 @@ public class LocalLoadingCacheTest extends TestCase {
assertThat(map).containsEntry(three, one);
assertThat(map).containsEntry(one, two);
- // TODO(user): Confirm with fry@ that this is a reasonable substitute.
+ // TODO(cgruber): Confirm with fry@ that this is a reasonable substitute.
// Set<Entry<Object, Object>> entries = map.entrySet();
// assertThat(entries).containsExactly(
// Maps.immutableEntry(three, one), Maps.immutableEntry(one, two));
@@ -293,7 +293,6 @@ public class LocalLoadingCacheTest extends TestCase {
assertFalse(segment.recencyQueue.isEmpty());
}
-
public void testRecursiveComputation() throws InterruptedException {
final AtomicReference<LoadingCache<Integer, String>> cacheRef = new AtomicReference<>();
CacheLoader<Integer, String> recursiveLoader =
@@ -324,7 +323,7 @@ public class LocalLoadingCacheTest extends TestCase {
recursiveCache = CacheBuilder.newBuilder().weakKeys().weakValues().build(recursiveLoader);
cacheRef.set(recursiveCache);
- // tells the test when the compution has completed
+ // tells the test when the computation has completed
final CountDownLatch doneSignal = new CountDownLatch(1);
Thread thread =
diff --git a/android/guava-tests/test/com/google/common/cache/TestingCacheLoaders.java b/android/guava-tests/test/com/google/common/cache/TestingCacheLoaders.java
index 6cc026021..e4a06c9cb 100644
--- a/android/guava-tests/test/com/google/common/cache/TestingCacheLoaders.java
+++ b/android/guava-tests/test/com/google/common/cache/TestingCacheLoaders.java
@@ -23,7 +23,7 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Utility {@link CacheLoader} implementations intended for use in testing.
@@ -57,7 +57,7 @@ class TestingCacheLoaders {
}
/** Returns a {@link CacheLoader} that returns the given {@code constant} for every request. */
- static <K, V> ConstantLoader<K, V> constantLoader(@CheckForNull V constant) {
+ static <K, V> ConstantLoader<K, V> constantLoader(@Nullable V constant) {
return new ConstantLoader<>(constant);
}
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java
new file mode 100644
index 000000000..e5cea6b55
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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 com.google.common.base.Joiner;
+import com.google.common.collect.testing.MapInterfaceTest;
+import java.util.Map;
+import java.util.Map.Entry;
+
+@GwtCompatible
+abstract class AbstractImmutableBiMapMapInterfaceTest<K, V> extends MapInterfaceTest<K, V> {
+ AbstractImmutableBiMapMapInterfaceTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ protected Map<K, V> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ private static final Joiner JOINER = Joiner.on(", ");
+
+ @Override
+ protected final void assertMoreInvariants(Map<K, V> map) {
+ BiMap<K, V> bimap = (BiMap<K, V>) map;
+
+ for (Entry<K, V> entry : map.entrySet()) {
+ assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
+ assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue()));
+ }
+
+ assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
+ assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
+ assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
+ assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
+
+ assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
+ assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..62359f0a4
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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 com.google.common.base.Joiner;
+import com.google.common.collect.testing.MapInterfaceTest;
+import com.google.common.collect.testing.MinimalSet;
+import java.util.Map;
+import java.util.Map.Entry;
+
+@GwtCompatible
+abstract class AbstractImmutableMapMapInterfaceTest<K, V> extends MapInterfaceTest<K, V> {
+ AbstractImmutableMapMapInterfaceTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ protected Map<K, V> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ private static final Joiner JOINER = Joiner.on(", ");
+
+ @Override
+ protected final void assertMoreInvariants(Map<K, V> map) {
+ // TODO: can these be moved to MapInterfaceTest?
+ for (Entry<K, V> entry : map.entrySet()) {
+ assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
+ }
+
+ assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
+ assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
+ assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
+ assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
+
+ assertEquals(MinimalSet.from(map.entrySet()), map.entrySet());
+ assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java b/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java
index d7a8d16ca..705b15a48 100644
--- a/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java
@@ -33,6 +33,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base class for {@link ImmutableSet} and {@link ImmutableSortedSet} tests.
@@ -59,7 +60,7 @@ public abstract class AbstractImmutableSetTest extends TestCase {
protected abstract <E extends Comparable<? super E>> Set<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... rest);
- protected abstract <E extends Comparable<? super E>> Set<E> copyOf(E[] elements);
+ protected abstract <E extends Comparable<? super E>> Set<E> copyOf(E @Nullable [] elements);
protected abstract <E extends Comparable<? super E>> Set<E> copyOf(
Collection<? extends E> elements);
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..bee92bd30
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2009 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 com.google.common.base.Joiner;
+import com.google.common.collect.testing.SortedMapInterfaceTest;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.SortedMap;
+
+@GwtCompatible
+public abstract class AbstractImmutableSortedMapMapInterfaceTest<K, V>
+ extends SortedMapInterfaceTest<K, V> {
+ public AbstractImmutableSortedMapMapInterfaceTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ protected SortedMap<K, V> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ private static final Joiner joiner = Joiner.on(", ");
+
+ @Override
+ protected void assertMoreInvariants(Map<K, V> map) {
+ // TODO: can these be moved to MapInterfaceTest?
+ for (Entry<K, V> entry : map.entrySet()) {
+ assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
+ }
+
+ assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
+ assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
+ assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
+ assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());
+
+ assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
+ assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java b/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java
index a76907cda..9ca7420f6 100644
--- a/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java
+++ b/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java
@@ -51,8 +51,7 @@ public class AbstractIteratorTest extends TestCase {
case 2:
return endOfData();
default:
- fail("Should not have been invoked again");
- return null;
+ throw new AssertionError("Should not have been invoked again");
}
}
};
@@ -97,8 +96,7 @@ public class AbstractIteratorTest extends TestCase {
case 2:
return endOfData();
default:
- fail("Should not have been invoked again");
- return null;
+ throw new AssertionError("Should not have been invoked again");
}
}
};
@@ -139,6 +137,7 @@ public class AbstractIteratorTest extends TestCase {
@GwtIncompatible // weak references
+ @AndroidIncompatible // depends on details of GC
public void testFreesNextReference() {
Iterator<Object> itr =
new AbstractIterator<Object>() {
@@ -188,12 +187,12 @@ public class AbstractIteratorTest extends TestCase {
@Override
public Integer computeNext() {
if (haveBeenCalled) {
- fail("Should not have been called again");
+ throw new AssertionError("Should not have been called again");
} else {
haveBeenCalled = true;
sneakyThrow(new SomeCheckedException());
+ throw new AssertionError(); // unreachable
}
- return null; // never reached
}
};
@@ -281,7 +280,7 @@ public class AbstractIteratorTest extends TestCase {
@Override
protected Integer computeNext() {
boolean unused = hasNext();
- return null;
+ throw new AssertionError();
}
};
try {
@@ -295,7 +294,7 @@ public class AbstractIteratorTest extends TestCase {
// hasNext/next/peek), but we'll cop out for now, knowing that peek() and
// next() both start by invoking hasNext() anyway.
- /** Throws a undeclared checked exception. */
+ /** Throws an undeclared checked exception. */
private static void sneakyThrow(Throwable t) {
class SneakyThrower<T extends Throwable> {
@SuppressWarnings("unchecked") // not really safe, but that's the point
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java b/android/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java
index 63c17deda..6e6b25497 100644
--- a/android/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java
+++ b/android/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import java.util.Collections;
import java.util.Map.Entry;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code AbstractMapEntry}.
@@ -28,8 +29,8 @@ import junit.framework.TestCase;
*/
@GwtCompatible
public class AbstractMapEntryTest extends TestCase {
- private static final String NK = null;
- private static final Integer NV = null;
+ private static final @Nullable String NK = null;
+ private static final @Nullable Integer NV = null;
private static <K, V> Entry<K, V> entry(final K key, final V value) {
return new AbstractMapEntry<K, V>() {
diff --git a/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java b/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
index c0b7d91c4..16a9ba781 100644
--- a/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
+++ b/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
@@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Tests for {@link AbstractSequentialIterator}. */
@GwtCompatible(emulated = true)
@@ -59,7 +60,8 @@ public class AbstractSequentialIteratorTest extends TestCase {
public Iterator<Integer> iterator() {
Iterator<Integer> powersOfTwo =
new AbstractSequentialIterator<Integer>(1) {
- protected Integer computeNext(Integer previous) {
+ @Override
+ protected @Nullable Integer computeNext(Integer previous) {
return (previous == 1 << 30) ? null : previous * 2;
}
};
@@ -136,7 +138,7 @@ public class AbstractSequentialIteratorTest extends TestCase {
private static Iterator<Integer> newDoubler(int first, final int last) {
return new AbstractSequentialIterator<Integer>(first) {
@Override
- protected Integer computeNext(Integer previous) {
+ protected @Nullable Integer computeNext(Integer previous) {
return (previous == last) ? null : previous * 2;
}
};
diff --git a/android/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java b/android/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java
new file mode 100644
index 000000000..15e7a4bf6
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableColumnMapTest extends ColumnMapTests {
+ public ArrayTableColumnMapTest() {
+ super(true, false, false, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ return ArrayTable.create(Arrays.asList(1, 2, 3), Arrays.asList("foo", "bar", "dog"));
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java b/android/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java
new file mode 100644
index 000000000..81acac43f
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableColumnTest extends ColumnTests {
+ public ArrayTableColumnTest() {
+ super(true, true, false, false, false);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ return ArrayTable.create(
+ Arrays.asList("one", "two", "three", "four"), Arrays.asList('a', 'b', 'c'));
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java b/android/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java
new file mode 100644
index 000000000..b1f76cf28
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableRowMapTest extends RowMapTests {
+ public ArrayTableRowMapTest() {
+ super(true, false, false, false);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ return ArrayTable.create(Arrays.asList("foo", "bar", "dog"), Arrays.asList(1, 2, 3));
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java b/android/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java
new file mode 100644
index 000000000..cad5783a9
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableRowTest extends RowTests {
+ public ArrayTableRowTest() {
+ super(true, true, false, false, false);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Table<Character, String, Integer> makeTable() {
+ return ArrayTable.create(
+ Arrays.asList('a', 'b', 'c'), Arrays.asList("one", "two", "three", "four"));
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java b/android/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
index 65d2ef6f4..0a524fca4 100644
--- a/android/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
+++ b/android/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
@@ -386,7 +386,7 @@ final class BenchmarkHelpers {
public <E> Interner<E> create(Collection<E> contents) {
Interner<E> interner = Interners.newWeakInterner();
for (E e : contents) {
- interner.intern(e);
+ E unused = interner.intern(e);
}
return interner;
}
@@ -396,7 +396,7 @@ final class BenchmarkHelpers {
public <E> Interner<E> create(Collection<E> contents) {
Interner<E> interner = Interners.newStrongInterner();
for (E e : contents) {
- interner.intern(e);
+ E unused = interner.intern(e);
}
return interner;
}
diff --git a/android/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java b/android/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
index cdc7a91cc..0504e6a74 100644
--- a/android/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
+++ b/android/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
@@ -22,6 +22,7 @@ import com.google.common.primitives.Ints;
import java.util.Collections;
import java.util.List;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Package up sample data for common collections benchmarking.
@@ -111,7 +112,7 @@ class CollectionBenchmarkSampleData {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return this == obj || (obj instanceof Element && ((Element) obj).hash == hash);
}
@@ -137,7 +138,7 @@ class CollectionBenchmarkSampleData {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return slowItDown() != 1 && super.equals(obj);
}
diff --git a/android/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java b/android/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java
new file mode 100644
index 000000000..8a783ec6e
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredCollectionTest;
+import java.util.Collection;
+
+public final class Collections2FilterArrayListTest
+ extends AbstractFilteredCollectionTest<Collection<Integer>> {
+ @Override
+ Collection<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Lists.newArrayList(contents);
+ }
+
+ @Override
+ Collection<Integer> filter(Collection<Integer> elements, Predicate<? super Integer> predicate) {
+ return Collections2.filter(elements, predicate);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/Collections2Test.java b/android/guava-tests/test/com/google/common/collect/Collections2Test.java
index 4b8761893..2cf05f632 100644
--- a/android/guava-tests/test/com/google/common/collect/Collections2Test.java
+++ b/android/guava-tests/test/com/google/common/collect/Collections2Test.java
@@ -16,16 +16,15 @@
package com.google.common.collect;
+import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newLinkedList;
import static com.google.common.truth.Truth.assertThat;
-import static java.util.Arrays.asList;
import static java.util.Collections.nCopies;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.TestStringCollectionGenerator;
@@ -40,6 +39,7 @@ import java.util.NoSuchElementException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Collections2}.
@@ -62,29 +62,10 @@ public class Collections2Test extends TestCase {
return suite;
}
- static final Predicate<String> NOT_YYY_ZZZ =
- new Predicate<String>() {
- @Override
- public boolean apply(String input) {
- return !"yyy".equals(input) && !"zzz".equals(input);
- }
- };
-
- static final Predicate<String> LENGTH_1 =
- new Predicate<String>() {
- @Override
- public boolean apply(String input) {
- return input.length() == 1;
- }
- };
-
- static final Predicate<String> STARTS_WITH_VOWEL =
- new Predicate<String>() {
- @Override
- public boolean apply(String input) {
- return asList('a', 'e', 'i', 'o', 'u').contains(input.charAt(0));
- }
- };
+ static final Predicate<@Nullable String> NOT_YYY_ZZZ =
+ input -> !"yyy".equals(input) && !"zzz".equals(input);
+
+ static final Predicate<String> LENGTH_1 = input -> input.length() == 1;
@GwtIncompatible // suite
private static Test testsForFilter() {
@@ -200,25 +181,18 @@ public class Collections2Test extends TestCase {
.createTestSuite();
}
- private static final Function<String, String> REMOVE_FIRST_CHAR =
- new Function<String, String>() {
- @Override
- public String apply(String from) {
- return ((from == null) || "".equals(from)) ? null : from.substring(1);
- }
- };
-
@GwtIncompatible // suite
private static Test testsForTransform() {
return CollectionTestSuiteBuilder.using(
new TestStringCollectionGenerator() {
@Override
- public Collection<String> create(String[] elements) {
- List<String> list = newArrayList();
+ public Collection<@Nullable String> create(@Nullable String[] elements) {
+ List<@Nullable String> list = newArrayList();
for (String element : elements) {
list.add((element == null) ? null : "q" + element);
}
- return Collections2.transform(list, REMOVE_FIRST_CHAR);
+ return Collections2.transform(
+ list, from -> isNullOrEmpty(from) ? null : from.substring(1));
}
})
.named("Collections2.transform")
diff --git a/android/guava-tests/test/com/google/common/collect/ComparatorsTest.java b/android/guava-tests/test/com/google/common/collect/ComparatorsTest.java
index b30cb7646..03686119d 100644
--- a/android/guava-tests/test/com/google/common/collect/ComparatorsTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ComparatorsTest.java
@@ -25,6 +25,7 @@ import com.google.common.testing.EqualsTester;
import java.util.Collections;
import java.util.Comparator;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Comparators}.
@@ -118,7 +119,7 @@ public class ComparatorsTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof Foo) && ((Foo) o).value.equals(value);
}
diff --git a/android/guava-tests/test/com/google/common/collect/ComparisonChainTest.java b/android/guava-tests/test/com/google/common/collect/ComparisonChainTest.java
index 9a9f98a8c..b2bb7efca 100644
--- a/android/guava-tests/test/com/google/common/collect/ComparisonChainTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ComparisonChainTest.java
@@ -16,6 +16,8 @@
package com.google.common.collect;
+import static com.google.common.truth.Truth.assertThat;
+
import com.google.common.annotations.GwtCompatible;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
@@ -36,77 +38,84 @@ public class ComparisonChainTest extends TestCase {
}
}
+ @SuppressWarnings("deprecation")
public void testCompareBooleans() {
- assertEquals(
- 0,
- ComparisonChain.start()
- .compare(true, true)
- .compare(true, Boolean.TRUE)
- .compare(Boolean.TRUE, true)
- .compare(Boolean.TRUE, Boolean.TRUE)
- .result());
+ assertThat(
+ ComparisonChain.start()
+ .compare(true, true)
+ .compare(true, Boolean.TRUE)
+ .compare(Boolean.TRUE, true)
+ .compare(Boolean.TRUE, Boolean.TRUE)
+ .result())
+ .isEqualTo(0);
}
public void testDegenerate() {
// kinda bogus, but who cares?
- assertEquals(0, ComparisonChain.start().result());
+ assertThat(ComparisonChain.start().result()).isEqualTo(0);
}
public void testOneEqual() {
- assertEquals(0, ComparisonChain.start().compare("a", "a").result());
+ assertThat(ComparisonChain.start().compare("a", "a").result()).isEqualTo(0);
}
public void testOneEqualUsingComparator() {
- assertEquals(
- 0, ComparisonChain.start().compare("a", "A", String.CASE_INSENSITIVE_ORDER).result());
+ assertThat(ComparisonChain.start().compare("a", "A", String.CASE_INSENSITIVE_ORDER).result())
+ .isEqualTo(0);
}
public void testManyEqual() {
- assertEquals(
- 0,
- ComparisonChain.start()
- .compare(1, 1)
- .compare(1L, 1L)
- .compareFalseFirst(true, true)
- .compare(1.0, 1.0)
- .compare(1.0f, 1.0f)
- .compare("a", "a", Ordering.usingToString())
- .result());
+ assertThat(
+ ComparisonChain.start()
+ .compare(1, 1)
+ .compare(1L, 1L)
+ .compareFalseFirst(true, true)
+ .compare(1.0, 1.0)
+ .compare(1.0f, 1.0f)
+ .compare("a", "a", Ordering.usingToString())
+ .result())
+ .isEqualTo(0);
}
public void testShortCircuitLess() {
- assertTrue(
- ComparisonChain.start().compare("a", "b").compare(DONT_COMPARE_ME, DONT_COMPARE_ME).result()
- < 0);
+ assertThat(
+ ComparisonChain.start()
+ .compare("a", "b")
+ .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
+ .result())
+ .isLessThan(0);
}
public void testShortCircuitGreater() {
- assertTrue(
- ComparisonChain.start().compare("b", "a").compare(DONT_COMPARE_ME, DONT_COMPARE_ME).result()
- > 0);
+ assertThat(
+ ComparisonChain.start()
+ .compare("b", "a")
+ .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
+ .result())
+ .isGreaterThan(0);
}
public void testShortCircuitSecondStep() {
- assertTrue(
- ComparisonChain.start()
+ assertThat(
+ ComparisonChain.start()
.compare("a", "a")
.compare("a", "b")
.compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
- .result()
- < 0);
+ .result())
+ .isLessThan(0);
}
public void testCompareFalseFirst() {
- assertTrue(ComparisonChain.start().compareFalseFirst(true, true).result() == 0);
- assertTrue(ComparisonChain.start().compareFalseFirst(true, false).result() > 0);
- assertTrue(ComparisonChain.start().compareFalseFirst(false, true).result() < 0);
- assertTrue(ComparisonChain.start().compareFalseFirst(false, false).result() == 0);
+ assertThat(ComparisonChain.start().compareFalseFirst(true, true).result()).isEqualTo(0);
+ assertThat(ComparisonChain.start().compareFalseFirst(true, false).result()).isGreaterThan(0);
+ assertThat(ComparisonChain.start().compareFalseFirst(false, true).result()).isLessThan(0);
+ assertThat(ComparisonChain.start().compareFalseFirst(false, false).result()).isEqualTo(0);
}
public void testCompareTrueFirst() {
- assertTrue(ComparisonChain.start().compareTrueFirst(true, true).result() == 0);
- assertTrue(ComparisonChain.start().compareTrueFirst(true, false).result() < 0);
- assertTrue(ComparisonChain.start().compareTrueFirst(false, true).result() > 0);
- assertTrue(ComparisonChain.start().compareTrueFirst(false, false).result() == 0);
+ assertThat(ComparisonChain.start().compareTrueFirst(true, true).result()).isEqualTo(0);
+ assertThat(ComparisonChain.start().compareTrueFirst(true, false).result()).isLessThan(0);
+ assertThat(ComparisonChain.start().compareTrueFirst(false, true).result()).isGreaterThan(0);
+ assertThat(ComparisonChain.start().compareTrueFirst(false, false).result()).isEqualTo(0);
}
}
diff --git a/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java b/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java
index 25b057a72..fa927e2d8 100644
--- a/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java
@@ -183,11 +183,13 @@ public class EnumBiMapTest extends TestCase {
assertEquals(bimap3, emptyBimap);
}
+ @GwtIncompatible // keyType
public void testKeyType() {
EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class);
assertEquals(Currency.class, bimap.keyType());
}
+ @GwtIncompatible // valueType
public void testValueType() {
EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class);
assertEquals(Country.class, bimap.valueType());
diff --git a/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java b/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java
index 2a78f5547..24f395328 100644
--- a/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java
@@ -197,6 +197,7 @@ public class EnumHashBiMapTest extends TestCase {
assertEquals(bimap3, emptyBimap);
}
+ @GwtIncompatible // keyType
public void testKeyType() {
EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(Currency.class);
assertEquals(Currency.class, bimap.keyType());
diff --git a/android/guava-tests/test/com/google/common/collect/FauxveridesTest.java b/android/guava-tests/test/com/google/common/collect/FauxveridesTest.java
index ff0b86bf9..f7eda67d5 100644
--- a/android/guava-tests/test/com/google/common/collect/FauxveridesTest.java
+++ b/android/guava-tests/test/com/google/common/collect/FauxveridesTest.java
@@ -34,6 +34,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests that all {@code public static} methods "inherited" from superclasses are "overridden" in
@@ -176,7 +177,7 @@ public class FauxveridesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof MethodSignature) {
MethodSignature other = (MethodSignature) obj;
return name.equals(other.name)
@@ -219,7 +220,7 @@ public class FauxveridesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof TypeSignature) {
TypeSignature other = (TypeSignature) obj;
return parameterSignatures.equals(other.parameterSignatures);
@@ -251,7 +252,7 @@ public class FauxveridesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof TypeParameterSignature) {
TypeParameterSignature other = (TypeParameterSignature) obj;
/*
diff --git a/android/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java b/android/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java
new file mode 100644
index 000000000..f575a73c4
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2007 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;
+
+@GwtCompatible
+public class FilteredBiMapTest extends FilteredMapTest {
+ @Override
+ BiMap<String, Integer> createUnfiltered() {
+ return HashBiMap.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java b/android/guava-tests/test/com/google/common/collect/FilteredCollectionsTestUtil.java
index 3b05972ee..77e01dc58 100644
--- a/android/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java
+++ b/android/guava-tests/test/com/google/common/collect/FilteredCollectionsTestUtil.java
@@ -28,15 +28,19 @@ import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
-import java.util.TreeSet;
import junit.framework.TestCase;
/**
- * Tests for filtered collection views.
+ * Class that contains nested abstract tests for filtered collection views, along with their
+ * implementation helpers.
*
* @author Louis Wasserman
*/
-public class FilteredCollectionsTest extends TestCase {
+/*
+ * TODO(cpovirk): Should all the tests for filtered collections run under GWT, too? Currently, they
+ * don't.
+ */
+public final class FilteredCollectionsTestUtil {
private static final Predicate<Integer> EVEN =
new Predicate<Integer>() {
@Override
@@ -374,79 +378,5 @@ public class FilteredCollectionsTest extends TestCase {
}
}
- // implementation tests
-
- public static final class IterablesFilterArrayListTest
- extends AbstractFilteredIterableTest<Iterable<Integer>> {
- @Override
- Iterable<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Lists.newArrayList(contents);
- }
-
- @Override
- Iterable<Integer> filter(Iterable<Integer> elements, Predicate<? super Integer> predicate) {
- return Iterables.filter(elements, predicate);
- }
- }
-
- public static final class Collections2FilterArrayListTest
- extends AbstractFilteredCollectionTest<Collection<Integer>> {
- @Override
- Collection<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Lists.newArrayList(contents);
- }
-
- @Override
- Collection<Integer> filter(Collection<Integer> elements, Predicate<? super Integer> predicate) {
- return Collections2.filter(elements, predicate);
- }
- }
-
- public static final class SetsFilterHashSetTest extends AbstractFilteredSetTest<Set<Integer>> {
- @Override
- Set<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Sets.newHashSet(contents);
- }
-
- @Override
- Set<Integer> filter(Set<Integer> elements, Predicate<? super Integer> predicate) {
- return Sets.filter(elements, predicate);
- }
- }
-
- public static final class SetsFilterSortedSetTest
- extends AbstractFilteredSortedSetTest<SortedSet<Integer>> {
- @Override
- SortedSet<Integer> createUnfiltered(Iterable<Integer> contents) {
- final TreeSet<Integer> result = Sets.newTreeSet(contents);
- // we have to make the result not Navigable
- return new ForwardingSortedSet<Integer>() {
- @Override
- protected SortedSet<Integer> delegate() {
- return result;
- }
- };
- }
-
- @Override
- SortedSet<Integer> filter(SortedSet<Integer> elements, Predicate<? super Integer> predicate) {
- return Sets.filter(elements, predicate);
- }
- }
-
- public static final class SetsFilterNavigableSetTest extends AbstractFilteredNavigableSetTest {
- @Override
- NavigableSet<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Sets.newTreeSet(contents);
- }
-
- @Override
- NavigableSet<Integer> filter(
- NavigableSet<Integer> elements, Predicate<? super Integer> predicate) {
- return Sets.filter(elements, predicate);
- }
- }
-
- /** No-op test so that the class has at least one method, making Maven's test runner happy. */
- public void testNoop() {}
+ private FilteredCollectionsTestUtil() {}
}
diff --git a/android/guava-tests/test/com/google/common/collect/FilteredMapTest.java b/android/guava-tests/test/com/google/common/collect/FilteredMapTest.java
new file mode 100644
index 000000000..159fec9a9
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/FilteredMapTest.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.collect.MapsTest.CORRECT_LENGTH;
+import static com.google.common.collect.MapsTest.EVEN;
+import static com.google.common.collect.MapsTest.NOT_LENGTH_3;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import java.util.Map;
+import java.util.Map.Entry;
+import junit.framework.TestCase;
+
+@GwtCompatible
+public class FilteredMapTest extends TestCase {
+ Map<String, Integer> createUnfiltered() {
+ return Maps.newHashMap();
+ }
+
+ public void testFilteredKeysIllegalPut() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
+ filtered.put("a", 1);
+ filtered.put("b", 2);
+ assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
+
+ try {
+ filtered.put("yyy", 3);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testFilteredKeysIllegalPutAll() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
+ filtered.put("a", 1);
+ filtered.put("b", 2);
+ assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
+
+ try {
+ filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
+ }
+
+ public void testFilteredKeysFilteredReflectsBackingChanges() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
+ unfiltered.put("two", 2);
+ unfiltered.put("three", 3);
+ unfiltered.put("four", 4);
+ assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered);
+ assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered);
+
+ unfiltered.remove("three");
+ assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered);
+ assertEquals(ImmutableMap.of("four", 4), filtered);
+
+ unfiltered.clear();
+ assertEquals(ImmutableMap.of(), unfiltered);
+ assertEquals(ImmutableMap.of(), filtered);
+ }
+
+ public void testFilteredValuesIllegalPut() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ filtered.put("a", 2);
+ unfiltered.put("b", 4);
+ unfiltered.put("c", 5);
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+
+ try {
+ filtered.put("yyy", 3);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+ }
+
+ public void testFilteredValuesIllegalPutAll() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ filtered.put("a", 2);
+ unfiltered.put("b", 4);
+ unfiltered.put("c", 5);
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+
+ try {
+ filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+ }
+
+ public void testFilteredValuesIllegalSetValue() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ filtered.put("a", 2);
+ filtered.put("b", 4);
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+
+ Entry<String, Integer> entry = filtered.entrySet().iterator().next();
+ try {
+ entry.setValue(5);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+ }
+
+ public void testFilteredValuesClear() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("one", 1);
+ unfiltered.put("two", 2);
+ unfiltered.put("three", 3);
+ unfiltered.put("four", 4);
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ assertEquals(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), unfiltered);
+ assertEquals(ImmutableMap.of("two", 2, "four", 4), filtered);
+
+ filtered.clear();
+ assertEquals(ImmutableMap.of("one", 1, "three", 3), unfiltered);
+ assertTrue(filtered.isEmpty());
+ }
+
+ public void testFilteredEntriesIllegalPut() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
+
+ filtered.put("chicken", 7);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+
+ try {
+ filtered.put("cow", 7);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+ }
+
+ public void testFilteredEntriesIllegalPutAll() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
+
+ filtered.put("chicken", 7);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+
+ try {
+ filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+ }
+
+ public void testFilteredEntriesObjectPredicate() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Predicate<Object> predicate = Predicates.alwaysFalse();
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
+ assertTrue(filtered.isEmpty());
+ }
+
+ public void testFilteredEntriesWildCardEntryPredicate() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Predicate<Entry<?, ?>> predicate =
+ new Predicate<Entry<?, ?>>() {
+ @Override
+ public boolean apply(Entry<?, ?> input) {
+ return "cat".equals(input.getKey()) || Integer.valueOf(2) == input.getValue();
+ }
+ };
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
+ assertEquals(ImmutableMap.of("cat", 3, "dog", 2), filtered);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java b/android/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java
new file mode 100644
index 000000000..23b3f2a99
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.collect.MapsTest.CORRECT_LENGTH;
+
+import com.google.common.annotations.GwtCompatible;
+import java.util.SortedMap;
+
+@GwtCompatible
+public class FilteredSortedMapTest extends FilteredMapTest {
+ @Override
+ SortedMap<String, Integer> createUnfiltered() {
+ return Maps.newTreeMap();
+ }
+
+ public void testFirstAndLastKeyFilteredMap() {
+ SortedMap<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("apple", 2);
+ unfiltered.put("banana", 6);
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 5);
+
+ SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+ assertEquals("banana", filtered.firstKey());
+ assertEquals("cat", filtered.lastKey());
+ }
+
+ public void testHeadSubTailMap_FilteredMap() {
+ SortedMap<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("apple", 2);
+ unfiltered.put("banana", 6);
+ unfiltered.put("cat", 4);
+ unfiltered.put("dog", 3);
+ SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+
+ assertEquals(ImmutableMap.of("banana", 6), filtered.headMap("dog"));
+ assertEquals(ImmutableMap.of(), filtered.headMap("banana"));
+ assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.headMap("emu"));
+
+ assertEquals(ImmutableMap.of("banana", 6), filtered.subMap("banana", "dog"));
+ assertEquals(ImmutableMap.of("dog", 3), filtered.subMap("cat", "emu"));
+
+ assertEquals(ImmutableMap.of("dog", 3), filtered.tailMap("cat"));
+ assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.tailMap("banana"));
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java b/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java
index b8427b1c8..a6aeee6e5 100644
--- a/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java
+++ b/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java
@@ -38,9 +38,9 @@ import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link FluentIterable}.
@@ -57,7 +57,7 @@ public class FluentIterableTest extends TestCase {
}
public void testFromArrayAndAppend() {
- FluentIterable<TimeUnit> units =
+ FluentIterable<TimeUnit> unused =
FluentIterable.from(TimeUnit.values()).append(TimeUnit.SECONDS);
}
@@ -101,7 +101,6 @@ public class FluentIterableTest extends TestCase {
List<Integer> list1 = newArrayList(1);
List<Integer> list2 = newArrayList(4);
- @SuppressWarnings("unchecked")
List<List<Integer>> input = newArrayList(list1, list2);
FluentIterable<Integer> result = FluentIterable.concat(input);
@@ -123,7 +122,6 @@ public class FluentIterableTest extends TestCase {
List<Integer> list3 = newArrayList(7, 8);
List<Integer> list4 = newArrayList(9);
List<Integer> list5 = newArrayList(10);
- @SuppressWarnings("unchecked")
FluentIterable<Integer> result = FluentIterable.concat(list1, list2, list3, list4, list5);
assertEquals(asList(1, 4, 7, 8, 9, 10), newArrayList(result));
assertEquals("[1, 4, 7, 8, 9, 10]", result.toString());
@@ -850,7 +848,7 @@ public class FluentIterableTest extends TestCase {
.uniqueIndex(
new Function<Integer, Object>() {
@Override
- public Object apply(@CheckForNull Integer input) {
+ public Object apply(@Nullable Integer input) {
return String.valueOf(input);
}
});
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingListTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingListTest.java
index 7d3466eed..881228260 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingListTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingListTest.java
@@ -31,6 +31,7 @@ import java.util.ListIterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingList}.
@@ -112,7 +113,7 @@ public class ForwardingListTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingMapTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingMapTest.java
index cf2ed0d3b..6654f5496 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingMapTest.java
@@ -47,6 +47,7 @@ import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ForwardingMap}.
@@ -83,12 +84,12 @@ public class ForwardingMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
return standardRemove(object);
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -335,7 +336,7 @@ public class ForwardingMapTest extends TestCase {
"java.util.function.Consumer", "accept",
"java.util.function.IntFunction", "apply");
- private static Object getDefaultValue(final TypeToken<?> type) {
+ private static @Nullable Object getDefaultValue(final TypeToken<?> type) {
Class<?> rawType = type.getRawType();
Object defaultValue = ArbitraryInstances.get(rawType);
if (defaultValue != null) {
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java
index 327885d53..c2d783005 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java
@@ -33,6 +33,7 @@ import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ForwardingMultiset}.
@@ -115,7 +116,7 @@ public class ForwardingMultisetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -277,7 +278,7 @@ public class ForwardingMultisetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
throw new UnsupportedOperationException();
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java
index b70cd0718..41e29ec88 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java
@@ -39,6 +39,7 @@ import java.util.SortedMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingNavigableMap}.
@@ -75,12 +76,12 @@ public class ForwardingNavigableMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
return standardRemove(object);
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -134,47 +135,47 @@ public class ForwardingNavigableMapTest extends TestCase {
}
@Override
- public Entry<K, V> lowerEntry(K key) {
+ public @Nullable Entry<K, V> lowerEntry(K key) {
return standardLowerEntry(key);
}
@Override
- public K lowerKey(K key) {
+ public @Nullable K lowerKey(K key) {
return standardLowerKey(key);
}
@Override
- public Entry<K, V> floorEntry(K key) {
+ public @Nullable Entry<K, V> floorEntry(K key) {
return standardFloorEntry(key);
}
@Override
- public K floorKey(K key) {
+ public @Nullable K floorKey(K key) {
return standardFloorKey(key);
}
@Override
- public Entry<K, V> ceilingEntry(K key) {
+ public @Nullable Entry<K, V> ceilingEntry(K key) {
return standardCeilingEntry(key);
}
@Override
- public K ceilingKey(K key) {
+ public @Nullable K ceilingKey(K key) {
return standardCeilingKey(key);
}
@Override
- public Entry<K, V> higherEntry(K key) {
+ public @Nullable Entry<K, V> higherEntry(K key) {
return standardHigherEntry(key);
}
@Override
- public K higherKey(K key) {
+ public @Nullable K higherKey(K key) {
return standardHigherKey(key);
}
@Override
- public Entry<K, V> firstEntry() {
+ public @Nullable Entry<K, V> firstEntry() {
return standardFirstEntry();
}
@@ -184,12 +185,12 @@ public class ForwardingNavigableMapTest extends TestCase {
*/
@Override
- public Entry<K, V> pollFirstEntry() {
+ public @Nullable Entry<K, V> pollFirstEntry() {
return standardPollFirstEntry();
}
@Override
- public Entry<K, V> pollLastEntry() {
+ public @Nullable Entry<K, V> pollLastEntry() {
return standardPollLastEntry();
}
@@ -242,7 +243,7 @@ public class ForwardingNavigableMapTest extends TestCase {
}
@Override
- public Entry<K, V> lastEntry() {
+ public @Nullable Entry<K, V> lastEntry() {
return standardLastEntry();
}
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java
index fd47bf8fd..2fbc42ae7 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java
@@ -34,6 +34,7 @@ import java.util.SortedSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingNavigableSet}.
@@ -54,7 +55,7 @@ public class ForwardingNavigableSetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -119,32 +120,32 @@ public class ForwardingNavigableSetTest extends TestCase {
}
@Override
- public T lower(T e) {
+ public @Nullable T lower(T e) {
return standardLower(e);
}
@Override
- public T floor(T e) {
+ public @Nullable T floor(T e) {
return standardFloor(e);
}
@Override
- public T ceiling(T e) {
+ public @Nullable T ceiling(T e) {
return standardCeiling(e);
}
@Override
- public T higher(T e) {
+ public @Nullable T higher(T e) {
return standardHigher(e);
}
@Override
- public T pollFirst() {
+ public @Nullable T pollFirst() {
return standardPollFirst();
}
@Override
- public T pollLast() {
+ public @Nullable T pollLast() {
return standardPollLast();
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java
index 248f13277..033a96d9e 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java
@@ -29,6 +29,7 @@ import java.util.Queue;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingQueue}.
@@ -106,12 +107,12 @@ public class ForwardingQueueTest extends TestCase {
}
@Override
- public T peek() {
+ public @Nullable T peek() {
return standardPeek();
}
@Override
- public T poll() {
+ public @Nullable T poll() {
return standardPoll();
}
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingSetTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingSetTest.java
index 89bf7b31d..53d12c36a 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingSetTest.java
@@ -31,6 +31,7 @@ import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingSet}.
@@ -52,7 +53,7 @@ public class ForwardingSetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java
index 59e7ece53..a4d829085 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java
@@ -36,6 +36,7 @@ import java.util.SortedMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingSortedMap}.
@@ -71,12 +72,12 @@ public class ForwardingSortedMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
return standardRemove(object);
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java
index 2b77cd5e4..4f69dea94 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java
@@ -27,10 +27,10 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableSet;
-import javax.annotation.CheckForNull;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ForwardingSortedMultiset}.
@@ -93,12 +93,12 @@ public class ForwardingSortedMultisetTest extends TestCase {
}
@Override
- public int count(@CheckForNull Object element) {
+ public int count(@Nullable Object element) {
return standardCount(element);
}
@Override
- public boolean equals(@CheckForNull Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -123,7 +123,7 @@ public class ForwardingSortedMultisetTest extends TestCase {
}
@Override
- public boolean contains(@CheckForNull Object object) {
+ public boolean contains(@Nullable Object object) {
return standardContains(object);
}
@@ -143,7 +143,7 @@ public class ForwardingSortedMultisetTest extends TestCase {
}
@Override
- public boolean remove(@CheckForNull Object object) {
+ public boolean remove(@Nullable Object object) {
return standardRemove(object);
}
diff --git a/android/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java b/android/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java
index b83ee6b97..417370488 100644
--- a/android/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java
@@ -31,6 +31,7 @@ import java.util.SortedSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingSortedSet}.
@@ -51,7 +52,7 @@ public class ForwardingSortedSetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/android/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java b/android/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java
new file mode 100644
index 000000000..5b12653b5
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+
+@GwtCompatible
+public class HashBasedTableColumnMapTest extends ColumnMapTests {
+ public HashBasedTableColumnMapTest() {
+ super(false, true, true, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java b/android/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java
new file mode 100644
index 000000000..3a68bc642
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+
+@GwtCompatible
+public class HashBasedTableColumnTest extends ColumnTests {
+ public HashBasedTableColumnTest() {
+ super(false, true, true, true, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java b/android/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java
new file mode 100644
index 000000000..e5203b134
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+
+@GwtCompatible
+public class HashBasedTableRowMapTest extends RowMapTests {
+ public HashBasedTableRowMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java b/android/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java
new file mode 100644
index 000000000..eb4afeb78
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+
+@GwtCompatible
+public class HashBasedTableRowTest extends RowTests {
+ public HashBasedTableRowTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java
new file mode 100644
index 000000000..1484171ed
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class ImmutableBiMapInverseMapInterfaceTest
+ extends AbstractImmutableBiMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ return ImmutableBiMap.of();
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse();
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java
new file mode 100644
index 000000000..6a7846e3d
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class ImmutableBiMapMapInterfaceTest
+ extends AbstractImmutableBiMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ return ImmutableBiMap.of();
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableBiMap.of("one", 1, "two", 2, "three", 3);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
index e01b094fe..50bd68482 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
@@ -20,9 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableBiMap.Builder;
-import com.google.common.collect.testing.MapInterfaceTest;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -56,11 +54,6 @@ public class ImmutableBiMapTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite();
- suite.addTestSuite(MapTests.class);
- suite.addTestSuite(InverseMapTests.class);
- suite.addTestSuite(CreationTests.class);
- suite.addTestSuite(BiMapSpecificTests.class);
-
suite.addTest(
BiMapTestSuiteBuilder.using(new ImmutableBiMapGenerator())
.named("ImmutableBiMap")
@@ -93,662 +86,585 @@ public class ImmutableBiMapTest extends TestCase {
MapFeature.ALLOWS_ANY_NULL_QUERIES)
.suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods())
.createTestSuite());
+ suite.addTestSuite(ImmutableBiMapTest.class);
return suite;
}
- public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> {
- public AbstractMapTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- protected Map<K, V> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- private static final Joiner joiner = Joiner.on(", ");
-
- @Override
- protected void assertMoreInvariants(Map<K, V> map) {
+ // Creation tests
- BiMap<K, V> bimap = (BiMap<K, V>) map;
-
- for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
- assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue()));
- }
-
- assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
- assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
- assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
- assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());
-
- assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
- assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
- }
+ public void testEmptyBuilder() {
+ ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
+ assertEquals(Collections.<Integer, String>emptyMap(), map.inverse());
+ assertSame(ImmutableBiMap.of(), map);
}
- public static class MapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- return ImmutableBiMap.of();
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableBiMap.of("one", 1, "two", 2, "three", 3);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testSingletonBuilder() {
+ ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).build();
+ assertMapEquals(map, "one", 1);
+ assertMapEquals(map.inverse(), 1, "one");
}
- public static class InverseMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- return ImmutableBiMap.of();
- }
+ public void testBuilder_withImmutableEntry() {
+ ImmutableBiMap<String, Integer> map =
+ new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).build();
+ assertMapEquals(map, "one", 1);
+ }
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse();
- }
+ public void testBuilder() {
+ ImmutableBiMap<String, Integer> map =
+ ImmutableBiMap.<String, Integer>builder()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
+ @GwtIncompatible
+ public void testBuilderExactlySizedReusesArray() {
+ ImmutableBiMap.Builder<Integer, Integer> builder = ImmutableBiMap.builderWithExpectedSize(10);
+ Object[] builderArray = builder.alternatingKeysAndValues;
+ for (int i = 0; i < 10; i++) {
+ builder.put(i, i);
+ }
+ Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues;
+ RegularImmutableBiMap<Integer, Integer> map =
+ (RegularImmutableBiMap<Integer, Integer>) builder.build();
+ Object[] mapInternalArray = map.alternatingKeysAndValues;
+ assertSame(builderArray, builderArrayAfterPuts);
+ assertSame(builderArray, mapInternalArray);
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testBuilder_orderEntriesByValue() {
+ ImmutableBiMap<String, Integer> map =
+ ImmutableBiMap.<String, Integer>builder()
+ .orderEntriesByValue(Ordering.natural())
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 4)
+ .put("two", 2)
+ .build();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
}
- public static class CreationTests extends TestCase {
- public void testEmptyBuilder() {
- ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
- assertEquals(Collections.<Integer, String>emptyMap(), map.inverse());
- assertSame(ImmutableBiMap.of(), map);
- }
+ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
+ ImmutableBiMap.Builder<String, Integer> builder =
+ new ImmutableBiMap.Builder<String, Integer>(2).put("four", 4).put("one", 1);
+ ImmutableMap<String, Integer> keyOrdered = builder.build();
+ ImmutableMap<String, Integer> valueOrdered =
+ builder.orderEntriesByValue(Ordering.natural()).build();
+ assertMapEquals(keyOrdered, "four", 4, "one", 1);
+ assertMapEquals(valueOrdered, "one", 1, "four", 4);
+ }
- public void testSingletonBuilder() {
- ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).build();
- assertMapEquals(map, "one", 1);
- assertMapEquals(map.inverse(), 1, "one");
+ public void testBuilder_orderEntriesByValue_usedTwiceFails() {
+ ImmutableBiMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
+ try {
+ builder.orderEntriesByValue(Ordering.natural());
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException expected) {
}
+ }
- public void testBuilder_withImmutableEntry() {
- ImmutableBiMap<String, Integer> map =
- new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).build();
- assertMapEquals(map, "one", 1);
- }
+ public void testBuilderPutAllWithEmptyMap() {
+ ImmutableBiMap<String, Integer> map =
+ new Builder<String, Integer>().putAll(Collections.<String, Integer>emptyMap()).build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
+ }
- public void testBuilder() {
- ImmutableBiMap<String, Integer> map =
- ImmutableBiMap.<String, Integer>builder()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
- }
+ public void testBuilderPutAll() {
+ Map<String, Integer> toPut = new LinkedHashMap<>();
+ toPut.put("one", 1);
+ toPut.put("two", 2);
+ toPut.put("three", 3);
+ Map<String, Integer> moreToPut = new LinkedHashMap<>();
+ moreToPut.put("four", 4);
+ moreToPut.put("five", 5);
+
+ ImmutableBiMap<String, Integer> map =
+ new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).build();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- @GwtIncompatible
- public void testBuilderExactlySizedReusesArray() {
- ImmutableBiMap.Builder<Integer, Integer> builder = ImmutableBiMap.builderWithExpectedSize(10);
- Object[] builderArray = builder.alternatingKeysAndValues;
- for (int i = 0; i < 10; i++) {
- builder.put(i, i);
- }
- Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues;
- RegularImmutableBiMap<Integer, Integer> map =
- (RegularImmutableBiMap<Integer, Integer>) builder.build();
- Object[] mapInternalArray = map.alternatingKeysAndValues;
- assertSame(builderArray, builderArrayAfterPuts);
- assertSame(builderArray, mapInternalArray);
- }
+ public void testBuilderReuse() {
+ Builder<String, Integer> builder = new Builder<>();
+ ImmutableBiMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
+ ImmutableBiMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
- public void testBuilder_orderEntriesByValue() {
- ImmutableBiMap<String, Integer> map =
- ImmutableBiMap.<String, Integer>builder()
- .orderEntriesByValue(Ordering.natural())
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 4)
- .put("two", 2)
- .build();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
- }
+ assertMapEquals(mapOne, "one", 1, "two", 2);
+ assertMapEquals(mapOne.inverse(), 1, "one", 2, "two");
+ assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
+ assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four");
+ }
- public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
- ImmutableBiMap.Builder<String, Integer> builder =
- new ImmutableBiMap.Builder<String, Integer>(2).put("four", 4).put("one", 1);
- ImmutableMap<String, Integer> keyOrdered = builder.build();
- ImmutableMap<String, Integer> valueOrdered =
- builder.orderEntriesByValue(Ordering.natural()).build();
- assertMapEquals(keyOrdered, "four", 4, "one", 1);
- assertMapEquals(valueOrdered, "one", 1, "four", 4);
+ public void testBuilderPutNullKey() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilder_orderEntriesByValue_usedTwiceFails() {
- ImmutableBiMap.Builder<String, Integer> builder =
- new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
- try {
- builder.orderEntriesByValue(Ordering.natural());
- fail("Expected IllegalStateException");
- } catch (IllegalStateException expected) {
- }
+ public void testBuilderPutNullValue() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAllWithEmptyMap() {
- ImmutableBiMap<String, Integer> map =
- new Builder<String, Integer>().putAll(Collections.<String, Integer>emptyMap()).build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
+ public void testBuilderPutNullKeyViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAll() {
- Map<String, Integer> toPut = new LinkedHashMap<>();
- toPut.put("one", 1);
- toPut.put("two", 2);
- toPut.put("three", 3);
- Map<String, Integer> moreToPut = new LinkedHashMap<>();
- moreToPut.put("four", 4);
- moreToPut.put("five", 5);
-
- ImmutableBiMap<String, Integer> map =
- new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).build();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ public void testBuilderPutNullValueViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap("one", null));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderReuse() {
- Builder<String, Integer> builder = new Builder<>();
- ImmutableBiMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
- ImmutableBiMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
+ @SuppressWarnings("AlwaysThrows")
+ public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
+ Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .put("one", 1)
+ .put("one", 1); // throwing on this line would be even better
- assertMapEquals(mapOne, "one", 1, "two", 2);
- assertMapEquals(mapOne.inverse(), 1, "one", 2, "two");
- assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
- assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four");
- }
-
- public void testBuilderPutNullKey() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- }
-
- public void testBuilderPutNullValue() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ builder.build();
+ fail();
+ } catch (IllegalArgumentException expected) {
+ assertThat(expected.getMessage()).contains("one");
}
+ }
- public void testBuilderPutNullKeyViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testOf() {
+ assertMapEquals(ImmutableBiMap.of("one", 1), "one", 1);
+ assertMapEquals(ImmutableBiMap.of("one", 1).inverse(), 1, "one");
+ assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2);
+ assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two");
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(),
+ 1,
+ "one",
+ 2,
+ "two",
+ 3,
+ "three");
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4);
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4).inverse(),
+ 1,
+ "one",
+ 2,
+ "two",
+ 3,
+ "three",
+ 4,
+ "four");
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5);
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(),
+ 1,
+ "one",
+ 2,
+ "two",
+ 3,
+ "three",
+ 4,
+ "four",
+ 5,
+ "five");
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9,
+ "ten", 10),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9,
+ "ten",
+ 10);
+ }
- public void testBuilderPutNullValueViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap("one", null));
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullKey() {
+ try {
+ ImmutableBiMap.of(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
- @SuppressWarnings("AlwaysThrows")
- public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
- Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .put("one", 1)
- .put("one", 1); // throwing on this line would be even better
-
- try {
- builder.build();
- fail();
- } catch (IllegalArgumentException expected) {
- assertThat(expected.getMessage()).contains("one");
- }
+ try {
+ ImmutableBiMap.of("one", 1, null, 2);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOf() {
- assertMapEquals(ImmutableBiMap.of("one", 1), "one", 1);
- assertMapEquals(ImmutableBiMap.of("one", 1).inverse(), 1, "one");
- assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2);
- assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two");
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(),
- 1,
- "one",
- 2,
- "two",
- 3,
- "three");
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4);
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4).inverse(),
- 1,
- "one",
- 2,
- "two",
- 3,
- "three",
- 4,
- "four");
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5);
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(),
- 1,
- "one",
- 2,
- "two",
- 3,
- "three",
- 4,
- "four",
- 5,
- "five");
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9,
- "ten", 10),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9,
- "ten",
- 10);
+ public void testOfNullValue() {
+ try {
+ ImmutableBiMap.of("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testOfNullKey() {
- try {
- ImmutableBiMap.of(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableBiMap.of("one", 1, null, 2);
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ ImmutableBiMap.of("one", 1, "two", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOfNullValue() {
- try {
- ImmutableBiMap.of("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableBiMap.of("one", 1, "two", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ @SuppressWarnings("AlwaysThrows")
+ public void testOfWithDuplicateKey() {
+ try {
+ ImmutableBiMap.of("one", 1, "one", 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ assertThat(expected.getMessage()).contains("one");
}
+ }
- @SuppressWarnings("AlwaysThrows")
- public void testOfWithDuplicateKey() {
- try {
- ImmutableBiMap.of("one", 1, "one", 1);
- fail();
- } catch (IllegalArgumentException expected) {
- assertThat(expected.getMessage()).contains("one");
- }
- }
+ public void testOfEntries() {
+ assertMapEquals(ImmutableBiMap.ofEntries(entry("one", 1), entry("two", 2)), "one", 1, "two", 2);
+ }
- public void testOfEntries() {
- assertMapEquals(
- ImmutableBiMap.ofEntries(entry("one", 1), entry("two", 2)), "one", 1, "two", 2);
+ public void testOfEntriesNull() {
+ Entry<Integer, Integer> nullKey = entry(null, 23);
+ try {
+ ImmutableBiMap.ofEntries(nullKey);
+ fail();
+ } catch (NullPointerException expected) {
}
-
- public void testOfEntriesNull() {
- Entry<Integer, Integer> nullKey = entry(null, 23);
- try {
- ImmutableBiMap.ofEntries(nullKey);
- fail();
- } catch (NullPointerException expected) {
- }
- Entry<Integer, Integer> nullValue = entry(23, null);
- try {
- ImmutableBiMap.ofEntries(nullValue);
- fail();
- } catch (NullPointerException expected) {
- }
+ Entry<Integer, Integer> nullValue = entry(23, null);
+ try {
+ ImmutableBiMap.ofEntries(nullValue);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- private static <T> Entry<T, T> entry(T key, T value) {
- return new AbstractMap.SimpleImmutableEntry<>(key, value);
- }
+ private static <T> Entry<T, T> entry(T key, T value) {
+ return new AbstractMap.SimpleImmutableEntry<>(key, value);
+ }
- public void testCopyOfEmptyMap() {
- ImmutableBiMap<String, Integer> copy =
- ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
- assertEquals(Collections.<String, Integer>emptyMap(), copy);
- assertSame(copy, ImmutableBiMap.copyOf(copy));
- assertSame(ImmutableBiMap.of(), copy);
- }
+ public void testCopyOfEmptyMap() {
+ ImmutableBiMap<String, Integer> copy =
+ ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
+ assertEquals(Collections.<String, Integer>emptyMap(), copy);
+ assertSame(copy, ImmutableBiMap.copyOf(copy));
+ assertSame(ImmutableBiMap.of(), copy);
+ }
- public void testCopyOfSingletonMap() {
- ImmutableBiMap<String, Integer> copy =
- ImmutableBiMap.copyOf(Collections.singletonMap("one", 1));
- assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableBiMap.copyOf(copy));
- }
+ public void testCopyOfSingletonMap() {
+ ImmutableBiMap<String, Integer> copy =
+ ImmutableBiMap.copyOf(Collections.singletonMap("one", 1));
+ assertMapEquals(copy, "one", 1);
+ assertSame(copy, ImmutableBiMap.copyOf(copy));
+ }
- public void testCopyOf() {
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
+ public void testCopyOf() {
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
- assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
- assertSame(copy, ImmutableBiMap.copyOf(copy));
- }
+ ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
+ assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
+ assertSame(copy, ImmutableBiMap.copyOf(copy));
+ }
- public void testEmpty() {
- ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
- assertEquals(Collections.<String, Integer>emptyMap(), bimap);
- assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse());
- }
+ public void testEmpty() {
+ ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
+ assertEquals(Collections.<String, Integer>emptyMap(), bimap);
+ assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse());
+ }
- public void testFromHashMap() {
- Map<String, Integer> hashMap = Maps.newLinkedHashMap();
- hashMap.put("one", 1);
- hashMap.put("two", 2);
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- assertMapEquals(bimap, "one", 1, "two", 2);
- assertMapEquals(bimap.inverse(), 1, "one", 2, "two");
- }
+ public void testFromHashMap() {
+ Map<String, Integer> hashMap = Maps.newLinkedHashMap();
+ hashMap.put("one", 1);
+ hashMap.put("two", 2);
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ assertMapEquals(bimap, "one", 1, "two", 2);
+ assertMapEquals(bimap.inverse(), 1, "one", 2, "two");
+ }
- public void testFromImmutableMap() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(
- new ImmutableMap.Builder<String, Integer>()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .buildOrThrow());
- assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
- }
+ public void testFromImmutableMap() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(
+ new ImmutableMap.Builder<String, Integer>()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .buildOrThrow());
+ assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- public void testDuplicateValues() {
- ImmutableMap<String, Integer> map =
- new ImmutableMap.Builder<String, Integer>()
- .put("one", 1)
- .put("two", 2)
- .put("uno", 1)
- .put("dos", 2)
- .buildOrThrow();
-
- try {
- ImmutableBiMap.copyOf(map);
- fail();
- } catch (IllegalArgumentException expected) {
- assertThat(expected.getMessage()).containsMatch("1|2");
- // We don't specify which of the two dups should be reported.
- }
+ public void testDuplicateValues() {
+ ImmutableMap<String, Integer> map =
+ new ImmutableMap.Builder<String, Integer>()
+ .put("one", 1)
+ .put("two", 2)
+ .put("uno", 1)
+ .put("dos", 2)
+ .buildOrThrow();
+
+ try {
+ ImmutableBiMap.copyOf(map);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ assertThat(expected.getMessage()).containsMatch("1|2");
+ // We don't specify which of the two dups should be reported.
}
+ }
- // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7.
- public void testToImmutableBiMap_java7_combine() {
- ImmutableBiMap.Builder<String, Integer> zis =
- ImmutableBiMap.<String, Integer>builder().put("one", 1);
- ImmutableBiMap.Builder<String, Integer> zat =
- ImmutableBiMap.<String, Integer>builder().put("two", 2).put("three", 3);
- ImmutableBiMap<String, Integer> biMap = zis.combine(zat).build();
- assertMapEquals(biMap, "one", 1, "two", 2, "three", 3);
- }
+ // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7.
+ public void testToImmutableBiMap_java7_combine() {
+ ImmutableBiMap.Builder<String, Integer> zis =
+ ImmutableBiMap.<String, Integer>builder().put("one", 1);
+ ImmutableBiMap.Builder<String, Integer> zat =
+ ImmutableBiMap.<String, Integer>builder().put("two", 2).put("three", 3);
+ ImmutableBiMap<String, Integer> biMap = zis.combine(zat).build();
+ assertMapEquals(biMap, "one", 1, "two", 2, "three", 3);
+ }
- // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7.
- public void testToImmutableBiMap_exceptionOnDuplicateKey_java7_combine() {
- ImmutableBiMap.Builder<String, Integer> zis =
- ImmutableBiMap.<String, Integer>builder().put("one", 1).put("two", 2);
- ImmutableBiMap.Builder<String, Integer> zat =
- ImmutableBiMap.<String, Integer>builder().put("two", 22).put("three", 3);
- try {
- zis.combine(zat).build();
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- // expected
- }
+ // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7.
+ public void testToImmutableBiMap_exceptionOnDuplicateKey_java7_combine() {
+ ImmutableBiMap.Builder<String, Integer> zis =
+ ImmutableBiMap.<String, Integer>builder().put("one", 1).put("two", 2);
+ ImmutableBiMap.Builder<String, Integer> zat =
+ ImmutableBiMap.<String, Integer>builder().put("two", 22).put("three", 3);
+ try {
+ zis.combine(zat).build();
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ // expected
}
}
- public static class BiMapSpecificTests extends TestCase {
+ // BiMap-specific tests
- @SuppressWarnings("DoNotCall")
- public void testForcePut() {
- BiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- try {
- bimap.forcePut("three", 3);
- fail();
- } catch (UnsupportedOperationException expected) {
- }
+ @SuppressWarnings("DoNotCall")
+ public void testForcePut() {
+ BiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ try {
+ bimap.forcePut("three", 3);
+ fail();
+ } catch (UnsupportedOperationException expected) {
}
+ }
- public void testKeySet() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
- Set<String> keys = bimap.keySet();
- assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys);
- assertThat(keys).containsExactly("one", "two", "three", "four").inOrder();
- }
+ public void testKeySet() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
+ Set<String> keys = bimap.keySet();
+ assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys);
+ assertThat(keys).containsExactly("one", "two", "three", "four").inOrder();
+ }
- public void testValues() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
- Set<Integer> values = bimap.values();
- assertEquals(Sets.newHashSet(1, 2, 3, 4), values);
- assertThat(values).containsExactly(1, 2, 3, 4).inOrder();
- }
+ public void testValues() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
+ Set<Integer> values = bimap.values();
+ assertEquals(Sets.newHashSet(1, 2, 3, 4), values);
+ assertThat(values).containsExactly(1, 2, 3, 4).inOrder();
+ }
- public void testDoubleInverse() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- assertSame(bimap, bimap.inverse().inverse());
- }
+ public void testDoubleInverse() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ assertSame(bimap, bimap.inverse().inverse());
+ }
- @GwtIncompatible // SerializableTester
- public void testEmptySerialization() {
- ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
- assertSame(bimap, SerializableTester.reserializeAndAssert(bimap));
- }
+ @GwtIncompatible // SerializableTester
+ public void testEmptySerialization() {
+ ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
+ assertSame(bimap, SerializableTester.reserializeAndAssert(bimap));
+ }
- @GwtIncompatible // SerializableTester
- public void testSerialization() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
- assertEquals(Integer.valueOf(1), copy.get("one"));
- assertEquals("one", copy.inverse().get(1));
- assertSame(copy, copy.inverse().inverse());
- }
+ @GwtIncompatible // SerializableTester
+ public void testSerialization() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
+ assertEquals(Integer.valueOf(1), copy.get("one"));
+ assertEquals("one", copy.inverse().get(1));
+ assertSame(copy, copy.inverse().inverse());
+ }
- @GwtIncompatible // SerializableTester
- public void testInverseSerialization() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of(1, "one", 2, "two")).inverse();
- ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
- assertEquals(Integer.valueOf(1), copy.get("one"));
- assertEquals("one", copy.inverse().get(1));
- assertSame(copy, copy.inverse().inverse());
- }
+ @GwtIncompatible // SerializableTester
+ public void testInverseSerialization() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of(1, "one", 2, "two")).inverse();
+ ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
+ assertEquals(Integer.valueOf(1), copy.get("one"));
+ assertEquals("one", copy.inverse().get(1));
+ assertSame(copy, copy.inverse().inverse());
}
private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) {
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
index bce73b8f7..b9696301f 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
@@ -33,6 +33,7 @@ import java.util.Map.Entry;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ImmutableClassToInstanceMap}.
@@ -213,7 +214,7 @@ public class ImmutableClassToInstanceMapTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof Impl && value == ((Impl) obj).value;
}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java
new file mode 100644
index 000000000..113251981
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.collect.Iterables.getOnlyElement;
+import static com.google.common.collect.Iterables.unmodifiableIterable;
+import static com.google.common.collect.Sets.newHashSet;
+import static java.lang.reflect.Proxy.newProxyInstance;
+import static java.util.Arrays.asList;
+
+import com.google.common.annotations.GwtIncompatible;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import junit.framework.TestCase;
+
+@GwtIncompatible // reflection
+public class ImmutableListCopyOfConcurrentlyModifiedInputTest extends TestCase {
+ enum WrapWithIterable {
+ WRAP,
+ NO_WRAP
+ }
+
+ private static void runConcurrentlyMutatedTest(
+ Collection<Integer> initialContents,
+ Iterable<ListFrobber> actionsToPerformConcurrently,
+ WrapWithIterable wrap) {
+ ConcurrentlyMutatedList<Integer> concurrentlyMutatedList =
+ newConcurrentlyMutatedList(initialContents, actionsToPerformConcurrently);
+
+ Iterable<Integer> iterableToCopy =
+ wrap == WrapWithIterable.WRAP
+ ? unmodifiableIterable(concurrentlyMutatedList)
+ : concurrentlyMutatedList;
+
+ ImmutableList<Integer> copyOfIterable = ImmutableList.copyOf(iterableToCopy);
+
+ assertTrue(concurrentlyMutatedList.getAllStates().contains(copyOfIterable));
+ }
+
+ private static void runConcurrentlyMutatedTest(WrapWithIterable wrap) {
+ /*
+ * TODO: Iterate over many array sizes and all possible operation lists,
+ * performing adds and removes in different ways.
+ */
+ runConcurrentlyMutatedTest(elements(), ops(add(1), add(2)), wrap);
+
+ runConcurrentlyMutatedTest(elements(), ops(add(1), nop()), wrap);
+
+ runConcurrentlyMutatedTest(elements(), ops(add(1), remove()), wrap);
+
+ runConcurrentlyMutatedTest(elements(), ops(nop(), add(1)), wrap);
+
+ runConcurrentlyMutatedTest(elements(1), ops(remove(), nop()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1), ops(remove(), add(2)), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), remove()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), nop()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), add(3)), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(nop(), remove()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2, 3), ops(remove(), remove()), wrap);
+ }
+
+ private static ImmutableList<Integer> elements(Integer... elements) {
+ return ImmutableList.copyOf(elements);
+ }
+
+ private static ImmutableList<ListFrobber> ops(ListFrobber... elements) {
+ return ImmutableList.copyOf(elements);
+ }
+
+ public void testCopyOf_concurrentlyMutatedList() {
+ runConcurrentlyMutatedTest(WrapWithIterable.NO_WRAP);
+ }
+
+ public void testCopyOf_concurrentlyMutatedIterable() {
+ runConcurrentlyMutatedTest(WrapWithIterable.WRAP);
+ }
+
+ /** An operation to perform on a list. */
+ interface ListFrobber {
+ void perform(List<Integer> list);
+ }
+
+ static ListFrobber add(final int element) {
+ return new ListFrobber() {
+ @Override
+ public void perform(List<Integer> list) {
+ list.add(0, element);
+ }
+ };
+ }
+
+ static ListFrobber remove() {
+ return new ListFrobber() {
+ @Override
+ public void perform(List<Integer> list) {
+ list.remove(0);
+ }
+ };
+ }
+
+ static ListFrobber nop() {
+ return new ListFrobber() {
+ @Override
+ public void perform(List<Integer> list) {}
+ };
+ }
+
+ /** A list that mutates itself after every call to each of its {@link List} methods. */
+ interface ConcurrentlyMutatedList<E> extends List<E> {
+ /**
+ * The elements of a {@link ConcurrentlyMutatedList} are added and removed over time. This
+ * method returns every state that the list has passed through at some point.
+ */
+ Set<List<E>> getAllStates();
+ }
+
+ /**
+ * Returns a {@link ConcurrentlyMutatedList} that performs the given operations as its concurrent
+ * modifications. The mutations occur in the same thread as the triggering method call.
+ */
+ private static ConcurrentlyMutatedList<Integer> newConcurrentlyMutatedList(
+ final Collection<Integer> initialContents,
+ final Iterable<ListFrobber> actionsToPerformConcurrently) {
+ InvocationHandler invocationHandler =
+ new InvocationHandler() {
+ final CopyOnWriteArrayList<Integer> delegate =
+ new CopyOnWriteArrayList<>(initialContents);
+
+ final Method getAllStatesMethod =
+ getOnlyElement(asList(ConcurrentlyMutatedList.class.getDeclaredMethods()));
+
+ final Iterator<ListFrobber> remainingActions = actionsToPerformConcurrently.iterator();
+
+ final Set<List<Integer>> allStates = newHashSet();
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ return method.equals(getAllStatesMethod)
+ ? getAllStates()
+ : invokeListMethod(method, args);
+ }
+
+ private Set<List<Integer>> getAllStates() {
+ return allStates;
+ }
+
+ private Object invokeListMethod(Method method, Object[] args) throws Throwable {
+ try {
+ Object returnValue = method.invoke(delegate, args);
+ mutateDelegate();
+ return returnValue;
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private void mutateDelegate() {
+ allStates.add(ImmutableList.copyOf(delegate));
+ remainingActions.next().perform(delegate);
+ allStates.add(ImmutableList.copyOf(delegate));
+ }
+ };
+
+ @SuppressWarnings("unchecked")
+ ConcurrentlyMutatedList<Integer> list =
+ (ConcurrentlyMutatedList<Integer>)
+ newProxyInstance(
+ ImmutableListCopyOfConcurrentlyModifiedInputTest.class.getClassLoader(),
+ new Class[] {ConcurrentlyMutatedList.class},
+ invocationHandler);
+ return list;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java
index 52ed7fa3f..95ae532f9 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java
@@ -16,12 +16,8 @@
package com.google.common.collect;
-import static com.google.common.collect.Iterables.getOnlyElement;
-import static com.google.common.collect.Iterables.unmodifiableIterable;
-import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
-import static java.lang.reflect.Proxy.newProxyInstance;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
@@ -41,16 +37,11 @@ import com.google.common.collect.testing.google.ListGenerators.UnhashableElement
import com.google.common.collect.testing.testers.ListHashCodeTester;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -112,727 +103,557 @@ public class ImmutableListTest extends TestCase {
return suite;
}
- public static class CreationTests extends TestCase {
- public void testCreation_noArgs() {
- List<String> list = ImmutableList.of();
- assertEquals(Collections.emptyList(), list);
- }
+ // Creation tests
- public void testCreation_oneElement() {
- List<String> list = ImmutableList.of("a");
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCreation_noArgs() {
+ List<String> list = ImmutableList.of();
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCreation_twoElements() {
- List<String> list = ImmutableList.of("a", "b");
- assertEquals(Lists.newArrayList("a", "b"), list);
- }
+ public void testCreation_oneElement() {
+ List<String> list = ImmutableList.of("a");
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCreation_threeElements() {
- List<String> list = ImmutableList.of("a", "b", "c");
- assertEquals(Lists.newArrayList("a", "b", "c"), list);
- }
+ public void testCreation_twoElements() {
+ List<String> list = ImmutableList.of("a", "b");
+ assertEquals(Lists.newArrayList("a", "b"), list);
+ }
- public void testCreation_fourElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d");
- assertEquals(Lists.newArrayList("a", "b", "c", "d"), list);
- }
+ public void testCreation_threeElements() {
+ List<String> list = ImmutableList.of("a", "b", "c");
+ assertEquals(Lists.newArrayList("a", "b", "c"), list);
+ }
- public void testCreation_fiveElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e"), list);
- }
+ public void testCreation_fourElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d"), list);
+ }
- public void testCreation_sixElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), list);
- }
+ public void testCreation_fiveElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e"), list);
+ }
- public void testCreation_sevenElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g"), list);
- }
+ public void testCreation_sixElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), list);
+ }
- public void testCreation_eightElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h"), list);
- }
+ public void testCreation_sevenElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g"), list);
+ }
- public void testCreation_nineElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i"), list);
- }
+ public void testCreation_eightElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h"), list);
+ }
- public void testCreation_tenElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), list);
- }
+ public void testCreation_nineElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i"), list);
+ }
- public void testCreation_elevenElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), list);
- }
+ public void testCreation_tenElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), list);
+ }
- // Varargs versions
+ public void testCreation_elevenElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), list);
+ }
- public void testCreation_twelveElements() {
- List<String> list =
- ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l");
- assertEquals(
- Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), list);
- }
+ // Varargs versions
- public void testCreation_thirteenElements() {
- List<String> list =
- ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");
- assertEquals(
- Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"),
- list);
- }
+ public void testCreation_twelveElements() {
+ List<String> list =
+ ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l");
+ assertEquals(
+ Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), list);
+ }
- public void testCreation_fourteenElements() {
- List<String> list =
- ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n");
- assertEquals(
- Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"),
- list);
- }
+ public void testCreation_thirteenElements() {
+ List<String> list =
+ ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");
+ assertEquals(
+ Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), list);
+ }
- public void testCreation_singletonNull() {
- try {
- ImmutableList.of((String) null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCreation_fourteenElements() {
+ List<String> list =
+ ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n");
+ assertEquals(
+ Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"),
+ list);
+ }
- public void testCreation_withNull() {
- try {
- ImmutableList.of("a", null, "b");
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCreation_singletonNull() {
+ try {
+ ImmutableList.of((String) null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCreation_generic() {
- List<String> a = ImmutableList.of("a");
- // only verify that there is no compile warning
- ImmutableList<List<String>> unused = ImmutableList.of(a, a);
+ public void testCreation_withNull() {
+ try {
+ ImmutableList.of("a", null, "b");
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCreation_arrayOfArray() {
- String[] array = new String[] {"a"};
- List<String[]> list = ImmutableList.<String[]>of(array);
- assertEquals(Collections.singletonList(array), list);
- }
+ public void testCreation_generic() {
+ List<String> a = ImmutableList.of("a");
+ // only verify that there is no compile warning
+ ImmutableList<List<String>> unused = ImmutableList.of(a, a);
+ }
- public void testCopyOf_emptyArray() {
- String[] array = new String[0];
- List<String> list = ImmutableList.copyOf(array);
- assertEquals(Collections.emptyList(), list);
- }
+ public void testCreation_arrayOfArray() {
+ String[] array = new String[] {"a"};
+ List<String[]> list = ImmutableList.<String[]>of(array);
+ assertEquals(Collections.singletonList(array), list);
+ }
- public void testCopyOf_arrayOfOneElement() {
- String[] array = new String[] {"a"};
- List<String> list = ImmutableList.copyOf(array);
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCopyOf_emptyArray() {
+ String[] array = new String[0];
+ List<String> list = ImmutableList.copyOf(array);
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCopyOf_nullArray() {
- try {
- ImmutableList.copyOf((String[]) null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOf_arrayOfOneElement() {
+ String[] array = new String[] {"a"};
+ List<String> list = ImmutableList.copyOf(array);
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCopyOf_arrayContainingOnlyNull() {
- String[] array = new String[] {null};
- try {
- ImmutableList.copyOf(array);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOf_nullArray() {
+ try {
+ ImmutableList.copyOf((String[]) null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_collection_empty() {
- // "<String>" is required to work around a javac 1.5 bug.
- Collection<String> c = MinimalCollection.<String>of();
- List<String> list = ImmutableList.copyOf(c);
- assertEquals(Collections.emptyList(), list);
+ public void testCopyOf_arrayContainingOnlyNull() {
+ String[] array = new String[] {null};
+ try {
+ ImmutableList.copyOf(array);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_collection_oneElement() {
- Collection<String> c = MinimalCollection.of("a");
- List<String> list = ImmutableList.copyOf(c);
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCopyOf_collection_empty() {
+ // "<String>" is required to work around a javac 1.5 bug.
+ Collection<String> c = MinimalCollection.<String>of();
+ List<String> list = ImmutableList.copyOf(c);
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCopyOf_collection_general() {
- Collection<String> c = MinimalCollection.of("a", "b", "a");
- List<String> list = ImmutableList.copyOf(c);
- assertEquals(asList("a", "b", "a"), list);
- List<String> mutableList = asList("a", "b");
- list = ImmutableList.copyOf(mutableList);
- mutableList.set(0, "c");
- assertEquals(asList("a", "b"), list);
- }
+ public void testCopyOf_collection_oneElement() {
+ Collection<String> c = MinimalCollection.of("a");
+ List<String> list = ImmutableList.copyOf(c);
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCopyOf_collectionContainingNull() {
- Collection<String> c = MinimalCollection.of("a", null, "b");
- try {
- ImmutableList.copyOf(c);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOf_collection_general() {
+ Collection<String> c = MinimalCollection.of("a", "b", "a");
+ List<String> list = ImmutableList.copyOf(c);
+ assertEquals(asList("a", "b", "a"), list);
+ List<String> mutableList = asList("a", "b");
+ list = ImmutableList.copyOf(mutableList);
+ mutableList.set(0, "c");
+ assertEquals(asList("a", "b"), list);
+ }
- public void testCopyOf_iterator_empty() {
- Iterator<String> iterator = Iterators.emptyIterator();
- List<String> list = ImmutableList.copyOf(iterator);
- assertEquals(Collections.emptyList(), list);
+ public void testCopyOf_collectionContainingNull() {
+ Collection<String> c = MinimalCollection.of("a", null, "b");
+ try {
+ ImmutableList.copyOf(c);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_iterator_oneElement() {
- Iterator<String> iterator = Iterators.singletonIterator("a");
- List<String> list = ImmutableList.copyOf(iterator);
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCopyOf_iterator_empty() {
+ Iterator<String> iterator = Iterators.emptyIterator();
+ List<String> list = ImmutableList.copyOf(iterator);
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCopyOf_iterator_general() {
- Iterator<String> iterator = asList("a", "b", "a").iterator();
- List<String> list = ImmutableList.copyOf(iterator);
- assertEquals(asList("a", "b", "a"), list);
- }
+ public void testCopyOf_iterator_oneElement() {
+ Iterator<String> iterator = Iterators.singletonIterator("a");
+ List<String> list = ImmutableList.copyOf(iterator);
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCopyOf_iteratorContainingNull() {
- Iterator<String> iterator = asList("a", null, "b").iterator();
- try {
- ImmutableList.copyOf(iterator);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOf_iterator_general() {
+ Iterator<String> iterator = asList("a", "b", "a").iterator();
+ List<String> list = ImmutableList.copyOf(iterator);
+ assertEquals(asList("a", "b", "a"), list);
+ }
- public void testCopyOf_iteratorNull() {
- try {
- ImmutableList.copyOf((Iterator<String>) null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOf_iteratorContainingNull() {
+ Iterator<String> iterator = asList("a", null, "b").iterator();
+ try {
+ ImmutableList.copyOf(iterator);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_concurrentlyMutating() {
- List<String> sample = Lists.newArrayList("a", "b", "c");
- for (int delta : new int[] {-1, 0, 1}) {
- for (int i = 0; i < sample.size(); i++) {
- Collection<String> misleading = Helpers.misleadingSizeCollection(delta);
- List<String> expected = sample.subList(0, i);
- misleading.addAll(expected);
- assertEquals(expected, ImmutableList.copyOf(misleading));
- assertEquals(expected, ImmutableList.copyOf((Iterable<String>) misleading));
- }
- }
+ public void testCopyOf_iteratorNull() {
+ try {
+ ImmutableList.copyOf((Iterator<String>) null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- private static class CountingIterable implements Iterable<String> {
- int count = 0;
-
- @Override
- public Iterator<String> iterator() {
- count++;
- return asList("a", "b", "a").iterator();
+ public void testCopyOf_concurrentlyMutating() {
+ List<String> sample = Lists.newArrayList("a", "b", "c");
+ for (int delta : new int[] {-1, 0, 1}) {
+ for (int i = 0; i < sample.size(); i++) {
+ Collection<String> misleading = Helpers.misleadingSizeCollection(delta);
+ List<String> expected = sample.subList(0, i);
+ misleading.addAll(expected);
+ assertEquals(expected, ImmutableList.copyOf(misleading));
+ assertEquals(expected, ImmutableList.copyOf((Iterable<String>) misleading));
}
}
+ }
- public void testCopyOf_plainIterable() {
- CountingIterable iterable = new CountingIterable();
- List<String> list = ImmutableList.copyOf(iterable);
- assertEquals(asList("a", "b", "a"), list);
- }
-
- public void testCopyOf_plainIterable_iteratesOnce() {
- CountingIterable iterable = new CountingIterable();
- ImmutableList<String> unused = ImmutableList.copyOf(iterable);
- assertEquals(1, iterable.count);
- }
-
- public void testCopyOf_shortcut_empty() {
- Collection<String> c = ImmutableList.of();
- assertSame(c, ImmutableList.copyOf(c));
- }
+ private static class CountingIterable implements Iterable<String> {
+ int count = 0;
- public void testCopyOf_shortcut_singleton() {
- Collection<String> c = ImmutableList.of("a");
- assertSame(c, ImmutableList.copyOf(c));
- }
-
- public void testCopyOf_shortcut_immutableList() {
- Collection<String> c = ImmutableList.of("a", "b", "c");
- assertSame(c, ImmutableList.copyOf(c));
+ @Override
+ public Iterator<String> iterator() {
+ count++;
+ return asList("a", "b", "a").iterator();
}
+ }
- public void testBuilderAddArrayHandlesNulls() {
- String[] elements = {"a", null, "b"};
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.add(elements);
- fail("Expected NullPointerException");
- } catch (NullPointerException expected) {
- }
- ImmutableList<String> result = builder.build();
-
- /*
- * Maybe it rejects all elements, or maybe it adds "a" before failing.
- * Either way is fine with us.
- */
- if (result.isEmpty()) {
- return;
- }
- assertTrue(ImmutableList.of("a").equals(result));
- assertEquals(1, result.size());
- }
+ public void testCopyOf_plainIterable() {
+ CountingIterable iterable = new CountingIterable();
+ List<String> list = ImmutableList.copyOf(iterable);
+ assertEquals(asList("a", "b", "a"), list);
+ }
- public void testBuilderAddCollectionHandlesNulls() {
- List<String> elements = Arrays.asList("a", null, "b");
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.addAll(elements);
- fail("Expected NullPointerException");
- } catch (NullPointerException expected) {
- }
- ImmutableList<String> result = builder.build();
- assertEquals(ImmutableList.of("a"), result);
- assertEquals(1, result.size());
- }
+ public void testCopyOf_plainIterable_iteratesOnce() {
+ CountingIterable iterable = new CountingIterable();
+ ImmutableList<String> unused = ImmutableList.copyOf(iterable);
+ assertEquals(1, iterable.count);
+ }
- public void testSortedCopyOf_natural() {
- Collection<Integer> c = MinimalCollection.of(4, 16, 10, -1, 5);
- ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
- assertEquals(asList(-1, 4, 5, 10, 16), list);
- }
+ public void testCopyOf_shortcut_empty() {
+ Collection<String> c = ImmutableList.of();
+ assertSame(c, ImmutableList.copyOf(c));
+ }
- public void testSortedCopyOf_natural_empty() {
- Collection<Integer> c = MinimalCollection.of();
- ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
- assertEquals(asList(), list);
- }
+ public void testCopyOf_shortcut_singleton() {
+ Collection<String> c = ImmutableList.of("a");
+ assertSame(c, ImmutableList.copyOf(c));
+ }
- public void testSortedCopyOf_natural_singleton() {
- Collection<Integer> c = MinimalCollection.of(100);
- ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
- assertEquals(asList(100), list);
- }
+ public void testCopyOf_shortcut_immutableList() {
+ Collection<String> c = ImmutableList.of("a", "b", "c");
+ assertSame(c, ImmutableList.copyOf(c));
+ }
- public void testSortedCopyOf_natural_containsNull() {
- Collection<Integer> c = MinimalCollection.of(1, 3, null, 2);
- try {
- ImmutableList.sortedCopyOf(c);
- fail("Expected NPE");
- } catch (NullPointerException expected) {
- }
+ public void testBuilderAddArrayHandlesNulls() {
+ String[] elements = {"a", null, "b"};
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.add(elements);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
}
+ ImmutableList<String> result = builder.build();
- public void testSortedCopyOf() {
- Collection<String> c = MinimalCollection.of("a", "b", "A", "c");
- List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- assertEquals(asList("a", "A", "b", "c"), list);
+ /*
+ * Maybe it rejects all elements, or maybe it adds "a" before failing.
+ * Either way is fine with us.
+ */
+ if (result.isEmpty()) {
+ return;
}
+ assertTrue(ImmutableList.of("a").equals(result));
+ assertEquals(1, result.size());
+ }
- public void testSortedCopyOf_empty() {
- Collection<String> c = MinimalCollection.of();
- List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- assertEquals(asList(), list);
- }
+ public void testBuilderAddCollectionHandlesNulls() {
+ List<String> elements = Arrays.asList("a", null, "b");
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.addAll(elements);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ ImmutableList<String> result = builder.build();
+ assertEquals(ImmutableList.of("a"), result);
+ assertEquals(1, result.size());
+ }
- public void testSortedCopyOf_singleton() {
- Collection<String> c = MinimalCollection.of("a");
- List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- assertEquals(asList("a"), list);
- }
+ public void testSortedCopyOf_natural() {
+ Collection<Integer> c = MinimalCollection.of(4, 16, 10, -1, 5);
+ ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
+ assertEquals(asList(-1, 4, 5, 10, 16), list);
+ }
- public void testSortedCopyOf_containsNull() {
- Collection<String> c = MinimalCollection.of("a", "b", "A", null, "c");
- try {
- ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- fail("Expected NPE");
- } catch (NullPointerException expected) {
- }
- }
+ public void testSortedCopyOf_natural_empty() {
+ Collection<Integer> c = MinimalCollection.of();
+ ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
+ assertEquals(asList(), list);
+ }
- // TODO(b/172823566): Use mainline testToImmutableList once CollectorTester is usable to java7.
- public void testToImmutableList_java7_combine() {
- ImmutableList.Builder<String> zis = ImmutableList.<String>builder().add("a", "b");
- ImmutableList.Builder<String> zat = ImmutableList.<String>builder().add("c", "d");
- ImmutableList<String> list = zis.combine(zat).build();
- assertEquals(asList("a", "b", "c", "d"), list);
- }
+ public void testSortedCopyOf_natural_singleton() {
+ Collection<Integer> c = MinimalCollection.of(100);
+ ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
+ assertEquals(asList(100), list);
}
- @GwtIncompatible // reflection
- public static class ConcurrentTests extends TestCase {
- enum WrapWithIterable {
- WRAP,
- NO_WRAP
+ public void testSortedCopyOf_natural_containsNull() {
+ Collection<Integer> c = MinimalCollection.of(1, 3, null, 2);
+ try {
+ ImmutableList.sortedCopyOf(c);
+ fail("Expected NPE");
+ } catch (NullPointerException expected) {
}
+ }
- private static void runConcurrentlyMutatedTest(
- Collection<Integer> initialContents,
- Iterable<ListFrobber> actionsToPerformConcurrently,
- WrapWithIterable wrap) {
- ConcurrentlyMutatedList<Integer> concurrentlyMutatedList =
- newConcurrentlyMutatedList(initialContents, actionsToPerformConcurrently);
+ public void testSortedCopyOf() {
+ Collection<String> c = MinimalCollection.of("a", "b", "A", "c");
+ List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ assertEquals(asList("a", "A", "b", "c"), list);
+ }
- Iterable<Integer> iterableToCopy =
- wrap == WrapWithIterable.WRAP
- ? unmodifiableIterable(concurrentlyMutatedList)
- : concurrentlyMutatedList;
+ public void testSortedCopyOf_empty() {
+ Collection<String> c = MinimalCollection.of();
+ List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ assertEquals(asList(), list);
+ }
- ImmutableList<Integer> copyOfIterable = ImmutableList.copyOf(iterableToCopy);
+ public void testSortedCopyOf_singleton() {
+ Collection<String> c = MinimalCollection.of("a");
+ List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ assertEquals(asList("a"), list);
+ }
- assertTrue(concurrentlyMutatedList.getAllStates().contains(copyOfIterable));
+ public void testSortedCopyOf_containsNull() {
+ Collection<String> c = MinimalCollection.of("a", "b", "A", null, "c");
+ try {
+ ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ fail("Expected NPE");
+ } catch (NullPointerException expected) {
}
+ }
- private static void runConcurrentlyMutatedTest(WrapWithIterable wrap) {
- /*
- * TODO: Iterate over many array sizes and all possible operation lists,
- * performing adds and removes in different ways.
- */
- runConcurrentlyMutatedTest(elements(), ops(add(1), add(2)), wrap);
-
- runConcurrentlyMutatedTest(elements(), ops(add(1), nop()), wrap);
-
- runConcurrentlyMutatedTest(elements(), ops(add(1), remove()), wrap);
-
- runConcurrentlyMutatedTest(elements(), ops(nop(), add(1)), wrap);
-
- runConcurrentlyMutatedTest(elements(1), ops(remove(), nop()), wrap);
+ // TODO(b/172823566): Use mainline testToImmutableList once CollectorTester is usable to java7.
+ public void testToImmutableList_java7_combine() {
+ ImmutableList.Builder<String> zis = ImmutableList.<String>builder().add("a", "b");
+ ImmutableList.Builder<String> zat = ImmutableList.<String>builder().add("c", "d");
+ ImmutableList<String> list = zis.combine(zat).build();
+ assertEquals(asList("a", "b", "c", "d"), list);
+ }
- runConcurrentlyMutatedTest(elements(1), ops(remove(), add(2)), wrap);
+ // Basic tests
- runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), remove()), wrap);
+ @GwtIncompatible // NullPointerTester
+ public void testNullPointers() {
+ NullPointerTester tester = new NullPointerTester();
+ tester.testAllPublicStaticMethods(ImmutableList.class);
+ tester.testAllPublicInstanceMethods(ImmutableList.of(1, 2, 3));
+ }
- runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), nop()), wrap);
+ @GwtIncompatible // SerializableTester
+ public void testSerialization_empty() {
+ Collection<String> c = ImmutableList.of();
+ assertSame(c, SerializableTester.reserialize(c));
+ }
- runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), add(3)), wrap);
+ @GwtIncompatible // SerializableTester
+ public void testSerialization_singleton() {
+ Collection<String> c = ImmutableList.of("a");
+ SerializableTester.reserializeAndAssert(c);
+ }
- runConcurrentlyMutatedTest(elements(1, 2), ops(nop(), remove()), wrap);
+ @GwtIncompatible // SerializableTester
+ public void testSerialization_multiple() {
+ Collection<String> c = ImmutableList.of("a", "b", "c");
+ SerializableTester.reserializeAndAssert(c);
+ }
- runConcurrentlyMutatedTest(elements(1, 2, 3), ops(remove(), remove()), wrap);
- }
+ public void testEquals_immutableList() {
+ Collection<String> c = ImmutableList.of("a", "b", "c");
+ assertTrue(c.equals(ImmutableList.of("a", "b", "c")));
+ assertFalse(c.equals(ImmutableList.of("a", "c", "b")));
+ assertFalse(c.equals(ImmutableList.of("a", "b")));
+ assertFalse(c.equals(ImmutableList.of("a", "b", "c", "d")));
+ }
- private static ImmutableList<Integer> elements(Integer... elements) {
- return ImmutableList.copyOf(elements);
- }
+ public void testBuilderAdd() {
+ ImmutableList<String> list =
+ new ImmutableList.Builder<String>().add("a").add("b").add("a").add("c").build();
+ assertEquals(asList("a", "b", "a", "c"), list);
+ }
- private static ImmutableList<ListFrobber> ops(ListFrobber... elements) {
- return ImmutableList.copyOf(elements);
+ @GwtIncompatible("Builder impl")
+ public void testBuilderForceCopy() {
+ ImmutableList.Builder<Integer> builder = ImmutableList.builder();
+ Object[] prevArray = null;
+ for (int i = 0; i < 10; i++) {
+ builder.add(i);
+ assertNotSame(builder.contents, prevArray);
+ prevArray = builder.contents;
+ ImmutableList<Integer> unused = builder.build();
}
+ }
- public void testCopyOf_concurrentlyMutatedList() {
- runConcurrentlyMutatedTest(WrapWithIterable.NO_WRAP);
- }
+ @GwtIncompatible
+ public void testBuilderExactlySizedReusesArray() {
+ ImmutableList.Builder<Integer> builder = ImmutableList.builderWithExpectedSize(10);
+ Object[] builderArray = builder.contents;
+ for (int i = 0; i < 10; i++) {
+ builder.add(i);
+ }
+ Object[] builderArrayAfterAdds = builder.contents;
+ RegularImmutableList<Integer> list = (RegularImmutableList<Integer>) builder.build();
+ Object[] listInternalArray = list.array;
+ assertSame(builderArray, builderArrayAfterAdds);
+ assertSame(builderArray, listInternalArray);
+ }
- public void testCopyOf_concurrentlyMutatedIterable() {
- runConcurrentlyMutatedTest(WrapWithIterable.WRAP);
- }
+ public void testBuilderAdd_varargs() {
+ ImmutableList<String> list =
+ new ImmutableList.Builder<String>().add("a", "b", "a", "c").build();
+ assertEquals(asList("a", "b", "a", "c"), list);
+ }
- /** An operation to perform on a list. */
- interface ListFrobber {
- void perform(List<Integer> list);
- }
+ public void testBuilderAddAll_iterable() {
+ List<String> a = asList("a", "b");
+ List<String> b = asList("c", "d");
+ ImmutableList<String> list = new ImmutableList.Builder<String>().addAll(a).addAll(b).build();
+ assertEquals(asList("a", "b", "c", "d"), list);
+ b.set(0, "f");
+ assertEquals(asList("a", "b", "c", "d"), list);
+ }
- static ListFrobber add(final int element) {
- return new ListFrobber() {
- @Override
- public void perform(List<Integer> list) {
- list.add(0, element);
- }
- };
- }
+ public void testBuilderAddAll_iterator() {
+ List<String> a = asList("a", "b");
+ List<String> b = asList("c", "d");
+ ImmutableList<String> list =
+ new ImmutableList.Builder<String>().addAll(a.iterator()).addAll(b.iterator()).build();
+ assertEquals(asList("a", "b", "c", "d"), list);
+ b.set(0, "f");
+ assertEquals(asList("a", "b", "c", "d"), list);
+ }
- static ListFrobber remove() {
- return new ListFrobber() {
- @Override
- public void perform(List<Integer> list) {
- list.remove(0);
+ public void testComplexBuilder() {
+ List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF);
+ ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder();
+ for (Integer red : colorElem) {
+ for (Integer green : colorElem) {
+ for (Integer blue : colorElem) {
+ webSafeColorsBuilder.add((red << 16) + (green << 8) + blue);
}
- };
- }
-
- static ListFrobber nop() {
- return new ListFrobber() {
- @Override
- public void perform(List<Integer> list) {}
- };
- }
-
- /** A list that mutates itself after every call to each of its {@link List} methods. */
- interface ConcurrentlyMutatedList<E> extends List<E> {
- /**
- * The elements of a {@link ConcurrentlyMutatedList} are added and removed over time. This
- * method returns every state that the list has passed through at some point.
- */
- Set<List<E>> getAllStates();
- }
-
- /**
- * Returns a {@link ConcurrentlyMutatedList} that performs the given operations as its
- * concurrent modifications. The mutations occur in the same thread as the triggering method
- * call.
- */
- private static ConcurrentlyMutatedList<Integer> newConcurrentlyMutatedList(
- final Collection<Integer> initialContents,
- final Iterable<ListFrobber> actionsToPerformConcurrently) {
- InvocationHandler invocationHandler =
- new InvocationHandler() {
- final CopyOnWriteArrayList<Integer> delegate =
- new CopyOnWriteArrayList<>(initialContents);
-
- final Method getAllStatesMethod =
- getOnlyElement(asList(ConcurrentlyMutatedList.class.getDeclaredMethods()));
-
- final Iterator<ListFrobber> remainingActions = actionsToPerformConcurrently.iterator();
-
- final Set<List<Integer>> allStates = newHashSet();
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- return method.equals(getAllStatesMethod)
- ? getAllStates()
- : invokeListMethod(method, args);
- }
-
- private Set<List<Integer>> getAllStates() {
- return allStates;
- }
-
- private Object invokeListMethod(Method method, Object[] args) throws Throwable {
- try {
- Object returnValue = method.invoke(delegate, args);
- mutateDelegate();
- return returnValue;
- } catch (InvocationTargetException e) {
- throw e.getCause();
- } catch (IllegalAccessException e) {
- throw new AssertionError(e);
- }
- }
-
- private void mutateDelegate() {
- allStates.add(ImmutableList.copyOf(delegate));
- remainingActions.next().perform(delegate);
- allStates.add(ImmutableList.copyOf(delegate));
- }
- };
-
- @SuppressWarnings("unchecked")
- ConcurrentlyMutatedList<Integer> list =
- (ConcurrentlyMutatedList<Integer>)
- newProxyInstance(
- ImmutableListTest.CreationTests.class.getClassLoader(),
- new Class[] {ConcurrentlyMutatedList.class},
- invocationHandler);
- return list;
+ }
}
+ ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build();
+ assertEquals(216, webSafeColors.size());
+ Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]);
+ assertEquals(0x000000, (int) webSafeColorArray[0]);
+ assertEquals(0x000033, (int) webSafeColorArray[1]);
+ assertEquals(0x000066, (int) webSafeColorArray[2]);
+ assertEquals(0x003300, (int) webSafeColorArray[6]);
+ assertEquals(0x330000, (int) webSafeColorArray[36]);
+ assertEquals(0x000066, (int) webSafeColors.get(2));
+ assertEquals(0x003300, (int) webSafeColors.get(6));
+ ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build();
+ assertEquals(
+ "Modifying the builder should not have changed any already" + " built sets",
+ 216,
+ webSafeColors.size());
+ assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size());
+ Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]);
+ assertEquals(0x00BFFF, (int) appendColorArray[216]);
}
- public static class BasicTests extends TestCase {
-
- @GwtIncompatible // NullPointerTester
- public void testNullPointers() {
- NullPointerTester tester = new NullPointerTester();
- tester.testAllPublicStaticMethods(ImmutableList.class);
- tester.testAllPublicInstanceMethods(ImmutableList.of(1, 2, 3));
- }
-
- @GwtIncompatible // SerializableTester
- public void testSerialization_empty() {
- Collection<String> c = ImmutableList.of();
- assertSame(c, SerializableTester.reserialize(c));
- }
-
- @GwtIncompatible // SerializableTester
- public void testSerialization_singleton() {
- Collection<String> c = ImmutableList.of("a");
- SerializableTester.reserializeAndAssert(c);
- }
-
- @GwtIncompatible // SerializableTester
- public void testSerialization_multiple() {
- Collection<String> c = ImmutableList.of("a", "b", "c");
- SerializableTester.reserializeAndAssert(c);
+ public void testBuilderAddHandlesNullsCorrectly() {
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.add((String) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testEquals_immutableList() {
- Collection<String> c = ImmutableList.of("a", "b", "c");
- assertTrue(c.equals(ImmutableList.of("a", "b", "c")));
- assertFalse(c.equals(ImmutableList.of("a", "c", "b")));
- assertFalse(c.equals(ImmutableList.of("a", "b")));
- assertFalse(c.equals(ImmutableList.of("a", "b", "c", "d")));
- }
-
- public void testBuilderAdd() {
- ImmutableList<String> list =
- new ImmutableList.Builder<String>().add("a").add("b").add("a").add("c").build();
- assertEquals(asList("a", "b", "a", "c"), list);
- }
-
- @GwtIncompatible("Builder impl")
- public void testBuilderForceCopy() {
- ImmutableList.Builder<Integer> builder = ImmutableList.builder();
- Object[] prevArray = null;
- for (int i = 0; i < 10; i++) {
- builder.add(i);
- assertNotSame(builder.contents, prevArray);
- prevArray = builder.contents;
- ImmutableList<Integer> unused = builder.build();
- }
- }
-
- @GwtIncompatible
- public void testBuilderExactlySizedReusesArray() {
- ImmutableList.Builder<Integer> builder = ImmutableList.builderWithExpectedSize(10);
- Object[] builderArray = builder.contents;
- for (int i = 0; i < 10; i++) {
- builder.add(i);
- }
- Object[] builderArrayAfterAdds = builder.contents;
- RegularImmutableList<Integer> list = (RegularImmutableList<Integer>) builder.build();
- Object[] listInternalArray = list.array;
- assertSame(builderArray, builderArrayAfterAdds);
- assertSame(builderArray, listInternalArray);
+ try {
+ builder.add((String[]) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAdd_varargs() {
- ImmutableList<String> list =
- new ImmutableList.Builder<String>().add("a", "b", "a", "c").build();
- assertEquals(asList("a", "b", "a", "c"), list);
+ try {
+ builder.add("a", null, "b");
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderAddAll_iterable() {
- List<String> a = asList("a", "b");
- List<String> b = asList("c", "d");
- ImmutableList<String> list = new ImmutableList.Builder<String>().addAll(a).addAll(b).build();
- assertEquals(asList("a", "b", "c", "d"), list);
- b.set(0, "f");
- assertEquals(asList("a", "b", "c", "d"), list);
+ public void testBuilderAddAllHandlesNullsCorrectly() {
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.addAll((Iterable<String>) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAddAll_iterator() {
- List<String> a = asList("a", "b");
- List<String> b = asList("c", "d");
- ImmutableList<String> list =
- new ImmutableList.Builder<String>().addAll(a.iterator()).addAll(b.iterator()).build();
- assertEquals(asList("a", "b", "c", "d"), list);
- b.set(0, "f");
- assertEquals(asList("a", "b", "c", "d"), list);
+ try {
+ builder.addAll((Iterator<String>) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testComplexBuilder() {
- List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF);
- ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder();
- for (Integer red : colorElem) {
- for (Integer green : colorElem) {
- for (Integer blue : colorElem) {
- webSafeColorsBuilder.add((red << 16) + (green << 8) + blue);
- }
- }
- }
- ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build();
- assertEquals(216, webSafeColors.size());
- Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]);
- assertEquals(0x000000, (int) webSafeColorArray[0]);
- assertEquals(0x000033, (int) webSafeColorArray[1]);
- assertEquals(0x000066, (int) webSafeColorArray[2]);
- assertEquals(0x003300, (int) webSafeColorArray[6]);
- assertEquals(0x330000, (int) webSafeColorArray[36]);
- assertEquals(0x000066, (int) webSafeColors.get(2));
- assertEquals(0x003300, (int) webSafeColors.get(6));
- ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build();
- assertEquals(
- "Modifying the builder should not have changed any already" + " built sets",
- 216,
- webSafeColors.size());
- assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size());
- Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]);
- assertEquals(0x00BFFF, (int) appendColorArray[216]);
+ builder = ImmutableList.builder();
+ List<String> listWithNulls = asList("a", null, "b");
+ try {
+ builder.addAll(listWithNulls);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAddHandlesNullsCorrectly() {
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.add((String) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- try {
- builder.add((String[]) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- try {
- builder.add("a", null, "b");
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
+ builder = ImmutableList.builder();
+ Iterator<String> iteratorWithNulls = asList("a", null, "b").iterator();
+ try {
+ builder.addAll(iteratorWithNulls);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAddAllHandlesNullsCorrectly() {
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.addAll((Iterable<String>) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- try {
- builder.addAll((Iterator<String>) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- builder = ImmutableList.builder();
- List<String> listWithNulls = asList("a", null, "b");
- try {
- builder.addAll(listWithNulls);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- builder = ImmutableList.builder();
- Iterator<String> iteratorWithNulls = asList("a", null, "b").iterator();
- try {
- builder.addAll(iteratorWithNulls);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b");
- try {
- builder.addAll(iterableWithNulls);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
+ Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b");
+ try {
+ builder.addAll(iterableWithNulls);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
+ }
- public void testAsList() {
- ImmutableList<String> list = ImmutableList.of("a", "b");
- assertSame(list, list.asList());
- }
+ public void testAsList() {
+ ImmutableList<String> list = ImmutableList.of("a", "b");
+ assertSame(list, list.asList());
+ }
- @GwtIncompatible("builder internals")
- public void testReusedBuilder() {
- ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();
- for (int i = 0; i < 10; i++) {
- builder.add("foo");
- }
- builder.add("bar");
- RegularImmutableList<String> list = (RegularImmutableList<String>) builder.build();
- builder.add("baz");
- assertTrue(list.array != builder.contents);
+ @GwtIncompatible("builder internals")
+ public void testReusedBuilder() {
+ ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();
+ for (int i = 0; i < 10; i++) {
+ builder.add("foo");
}
+ builder.add("bar");
+ RegularImmutableList<String> list = (RegularImmutableList<String>) builder.build();
+ builder.add("baz");
+ assertTrue(list.array != builder.contents);
}
}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
index 898d2a4b4..67c039af1 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
@@ -22,16 +22,10 @@ import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.ListTestSuiteBuilder;
-import com.google.common.collect.testing.MapInterfaceTest;
import com.google.common.collect.testing.MapTestSuiteBuilder;
-import com.google.common.collect.testing.MinimalSet;
-import com.google.common.collect.testing.SampleElements.Colliders;
-import com.google.common.collect.testing.SampleElements.Unhashables;
-import com.google.common.collect.testing.UnhashableObject;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -46,14 +40,15 @@ import com.google.common.collect.testing.google.MapGenerators.ImmutableMapValueL
import com.google.common.collect.testing.google.MapGenerators.ImmutableMapValuesAsSingletonSetGenerator;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
-import com.google.common.testing.SerializableTester;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractMap;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@@ -62,6 +57,7 @@ import java.util.regex.Pattern;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ImmutableMap}.
@@ -171,809 +167,704 @@ public class ImmutableMapTest extends TestCase {
return suite;
}
- public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> {
- public AbstractMapTests() {
- super(false, false, false, false, false);
- }
+ // Creation tests
- @Override
- protected Map<K, V> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
+ public void testEmptyBuilder() {
+ ImmutableMap<String, Integer> map = new Builder<String, Integer>().buildOrThrow();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
+ }
- private static final Joiner JOINER = Joiner.on(", ");
+ public void testSingletonBuilder() {
+ ImmutableMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).buildOrThrow();
+ assertMapEquals(map, "one", 1);
+ }
- @Override
- protected void assertMoreInvariants(Map<K, V> map) {
- // TODO: can these be moved to MapInterfaceTest?
- for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
- }
+ public void testBuilder() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .buildOrThrow();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ }
- assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
- assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
- assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
- assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
+ @GwtIncompatible
+ public void testBuilderExactlySizedReusesArray() {
+ ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(10);
+ Object[] builderArray = builder.alternatingKeysAndValues;
+ for (int i = 0; i < 10; i++) {
+ builder.put(i, i);
+ }
+ Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues;
+ RegularImmutableMap<Integer, Integer> map =
+ (RegularImmutableMap<Integer, Integer>) builder.buildOrThrow();
+ Object[] mapInternalArray = map.alternatingKeysAndValues;
+ assertSame(builderArray, builderArrayAfterPuts);
+ assertSame(builderArray, mapInternalArray);
+ }
- assertEquals(MinimalSet.from(map.entrySet()), map.entrySet());
- assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
- }
+ public void testBuilder_orderEntriesByValue() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>()
+ .orderEntriesByValue(Ordering.natural())
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 4)
+ .put("two", 2)
+ .buildOrThrow();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
}
- public static class MapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- return ImmutableMap.of();
- }
+ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
+ Builder<String, Integer> builder = new Builder<String, Integer>(2).put("four", 4).put("one", 1);
+ ImmutableMap<String, Integer> keyOrdered = builder.buildOrThrow();
+ ImmutableMap<String, Integer> valueOrdered =
+ builder.orderEntriesByValue(Ordering.natural()).buildOrThrow();
+ assertMapEquals(keyOrdered, "four", 4, "one", 1);
+ assertMapEquals(valueOrdered, "one", 1, "four", 4);
+ }
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableMap.of("one", 1, "two", 2, "three", 3);
+ public void testBuilder_orderEntriesByValue_usedTwiceFails() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
+ try {
+ builder.orderEntriesByValue(Ordering.natural());
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException expected) {
}
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
+ @GwtIncompatible // we haven't implemented this
+ public void testBuilder_orderEntriesByValue_keepingLast() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .orderEntriesByValue(Ordering.natural())
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 3)
+ .put("four", 5)
+ .put("four", 4) // this should win because it's last
+ .put("two", 2);
+ assertMapEquals(
+ builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ try {
+ builder.buildOrThrow();
+ fail("Expected exception from duplicate keys");
+ } catch (IllegalArgumentException expected) {
}
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
+ @GwtIncompatible // we haven't implemented this
+ public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserved() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .orderEntriesByValue(Ordering.natural())
+ .put("one", 1)
+ .put("one", 1);
+ assertMapEquals(builder.buildKeepingLast(), "one", 1);
+ try {
+ builder.buildOrThrow();
+ fail("Expected exception from duplicate keys");
+ } catch (IllegalArgumentException expected) {
}
}
- public static class SingletonMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableMap.of("one", 1);
- }
+ public void testBuilder_withImmutableEntry() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).buildOrThrow();
+ assertMapEquals(map, "one", 1);
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
+ public void testBuilder_withImmutableEntryAndNullContents() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(Maps.immutableEntry("one", (Integer) null));
+ fail();
+ } catch (NullPointerException expected) {
}
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
+ try {
+ builder.put(Maps.immutableEntry((String) null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
}
- @GwtIncompatible // SerializableTester
- public static class ReserializedMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return SerializableTester.reserialize(ImmutableMap.of("one", 1, "two", 2, "three", 3));
- }
+ private static class StringHolder {
+ String string;
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
+ public void testBuilder_withMutableEntry() {
+ ImmutableMap.Builder<String, Integer> builder = new Builder<>();
+ final StringHolder holder = new StringHolder();
+ holder.string = "one";
+ Entry<String, Integer> entry =
+ new AbstractMapEntry<String, Integer>() {
+ @Override
+ public String getKey() {
+ return holder.string;
+ }
+
+ @Override
+ public Integer getValue() {
+ return 1;
+ }
+ };
+
+ builder.put(entry);
+ holder.string = "two";
+ assertMapEquals(builder.buildOrThrow(), "one", 1);
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testBuilderPutAllWithEmptyMap() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>()
+ .putAll(Collections.<String, Integer>emptyMap())
+ .buildOrThrow();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class MapTestsWithBadHashes extends AbstractMapTests<Object, Integer> {
+ public void testBuilderPutAll() {
+ Map<String, Integer> toPut = new LinkedHashMap<>();
+ toPut.put("one", 1);
+ toPut.put("two", 2);
+ toPut.put("three", 3);
+ Map<String, Integer> moreToPut = new LinkedHashMap<>();
+ moreToPut.put("four", 4);
+ moreToPut.put("five", 5);
- @Override
- protected Map<Object, Integer> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).buildOrThrow();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ }
- @Override
- protected Map<Object, Integer> makePopulatedMap() {
- Colliders colliders = new Colliders();
- return ImmutableMap.of(
- colliders.e0(), 0,
- colliders.e1(), 1,
- colliders.e2(), 2,
- colliders.e3(), 3);
- }
+ public void testBuilderReuse() {
+ Builder<String, Integer> builder = new Builder<>();
+ ImmutableMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).buildOrThrow();
+ ImmutableMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).buildOrThrow();
- @Override
- protected Object getKeyNotInPopulatedMap() {
- return new Colliders().e4();
- }
+ assertMapEquals(mapOne, "one", 1, "two", 2);
+ assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
+ public void testBuilderPutNullKeyFailsAtomically() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ builder.put("foo", 2);
+ assertMapEquals(builder.buildOrThrow(), "foo", 2);
}
- @GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
- public static class MapTestsWithUnhashableValues
- extends AbstractMapTests<Integer, UnhashableObject> {
- @Override
- protected Map<Integer, UnhashableObject> makeEmptyMap() {
- return ImmutableMap.of();
+ public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(Maps.immutableEntry((String) null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ builder.put("foo", 2);
+ assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ }
- @Override
- protected Map<Integer, UnhashableObject> makePopulatedMap() {
- Unhashables unhashables = new Unhashables();
- return ImmutableMap.of(0, unhashables.e0(), 1, unhashables.e1(), 2, unhashables.e2());
- }
+ // for GWT compatibility
+ static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> {
+ public K key;
+ public V value;
- @Override
- protected Integer getKeyNotInPopulatedMap() {
- return 3;
+ SimpleEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
}
@Override
- protected UnhashableObject getValueNotInPopulatedMap() {
- return new Unhashables().e3();
+ public K getKey() {
+ return key;
}
- }
- @GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
- public static class MapTestsWithSingletonUnhashableValue extends MapTestsWithUnhashableValues {
@Override
- protected Map<Integer, UnhashableObject> makePopulatedMap() {
- Unhashables unhashables = new Unhashables();
- return ImmutableMap.of(0, unhashables.e0());
+ public V getValue() {
+ return value;
}
}
- public static class CreationTests extends TestCase {
- public void testEmptyBuilder() {
- ImmutableMap<String, Integer> map = new Builder<String, Integer>().buildOrThrow();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
- }
-
- public void testSingletonBuilder() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>().put("one", 1).buildOrThrow();
- assertMapEquals(map, "one", 1);
- }
-
- public void testBuilder() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .buildOrThrow();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- }
-
- @GwtIncompatible
- public void testBuilderExactlySizedReusesArray() {
- ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(10);
- Object[] builderArray = builder.alternatingKeysAndValues;
- for (int i = 0; i < 10; i++) {
- builder.put(i, i);
- }
- Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues;
- RegularImmutableMap<Integer, Integer> map =
- (RegularImmutableMap<Integer, Integer>) builder.buildOrThrow();
- Object[] mapInternalArray = map.alternatingKeysAndValues;
- assertSame(builderArray, builderArrayAfterPuts);
- assertSame(builderArray, mapInternalArray);
- }
-
- public void testBuilder_orderEntriesByValue() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>()
- .orderEntriesByValue(Ordering.natural())
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 4)
- .put("two", 2)
- .buildOrThrow();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- }
-
- public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
- Builder<String, Integer> builder =
- new Builder<String, Integer>(2).put("four", 4).put("one", 1);
- ImmutableMap<String, Integer> keyOrdered = builder.buildOrThrow();
- ImmutableMap<String, Integer> valueOrdered =
- builder.orderEntriesByValue(Ordering.natural()).buildOrThrow();
- assertMapEquals(keyOrdered, "four", 4, "one", 1);
- assertMapEquals(valueOrdered, "one", 1, "four", 4);
- }
-
- public void testBuilder_orderEntriesByValue_usedTwiceFails() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
- try {
- builder.orderEntriesByValue(Ordering.natural());
- fail("Expected IllegalStateException");
- } catch (IllegalStateException expected) {
- }
- }
-
- @GwtIncompatible // we haven't implemented this
- public void testBuilder_orderEntriesByValue_keepingLast() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .orderEntriesByValue(Ordering.natural())
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 3)
- .put("four", 5)
- .put("four", 4) // this should win because it's last
- .put("two", 2);
- assertMapEquals(
- builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- try {
- builder.buildOrThrow();
- fail("Expected exception from duplicate keys");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- @GwtIncompatible // we haven't implemented this
- public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserved() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .orderEntriesByValue(Ordering.natural())
- .put("one", 1)
- .put("one", 1);
- assertMapEquals(builder.buildKeepingLast(), "one", 1);
- try {
- builder.buildOrThrow();
- fail("Expected exception from duplicate keys");
- } catch (IllegalArgumentException expected) {
- }
- }
-
- public void testBuilder_withImmutableEntry() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).buildOrThrow();
- assertMapEquals(map, "one", 1);
- }
-
- public void testBuilder_withImmutableEntryAndNullContents() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(Maps.immutableEntry("one", (Integer) null));
- fail();
- } catch (NullPointerException expected) {
- }
- try {
- builder.put(Maps.immutableEntry((String) null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- }
-
- private static class StringHolder {
- String string;
+ public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(new SimpleEntry<String, Integer>(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ builder.put("foo", 2);
+ assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ }
- public void testBuilder_withMutableEntry() {
- ImmutableMap.Builder<String, Integer> builder = new Builder<>();
- final StringHolder holder = new StringHolder();
- holder.string = "one";
- Entry<String, Integer> entry =
- new AbstractMapEntry<String, Integer>() {
- @Override
- public String getKey() {
- return holder.string;
- }
-
- @Override
- public Integer getValue() {
- return 1;
- }
- };
-
- builder.put(entry);
- holder.string = "two";
- assertMapEquals(builder.buildOrThrow(), "one", 1);
+ public void testBuilderPutNullKey() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAllWithEmptyMap() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>()
- .putAll(Collections.<String, Integer>emptyMap())
- .buildOrThrow();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
+ public void testBuilderPutNullValue() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAll() {
- Map<String, Integer> toPut = new LinkedHashMap<>();
- toPut.put("one", 1);
- toPut.put("two", 2);
- toPut.put("three", 3);
- Map<String, Integer> moreToPut = new LinkedHashMap<>();
- moreToPut.put("four", 4);
- moreToPut.put("five", 5);
-
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).buildOrThrow();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ public void testBuilderPutNullKeyViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderReuse() {
- Builder<String, Integer> builder = new Builder<>();
- ImmutableMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).buildOrThrow();
- ImmutableMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).buildOrThrow();
-
- assertMapEquals(mapOne, "one", 1, "two", 2);
- assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
+ public void testBuilderPutNullValueViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap("one", null));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutNullKeyFailsAtomically() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- builder.put("foo", 2);
- assertMapEquals(builder.buildOrThrow(), "foo", 2);
- }
+ public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
+ Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .put("one", 1)
+ .put("one", 1); // throwing on this line might be better but it's too late to change
- public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(Maps.immutableEntry((String) null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- builder.put("foo", 2);
- assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ try {
+ builder.buildOrThrow();
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- // for GWT compatibility
- static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> {
- public K key;
- public V value;
+ public void testBuildKeepingLast_allowsOverwrite() {
+ Builder<Integer, String> builder =
+ new Builder<Integer, String>()
+ .put(1, "un")
+ .put(2, "deux")
+ .put(70, "soixante-dix")
+ .put(70, "septante")
+ .put(70, "seventy")
+ .put(1, "one")
+ .put(2, "two");
+ ImmutableMap<Integer, String> map = builder.buildKeepingLast();
+ assertMapEquals(map, 1, "one", 2, "two", 70, "seventy");
+ }
- SimpleEntry(K key, V value) {
- this.key = key;
- this.value = value;
- }
+ public void testBuildKeepingLast_smallTableSameHash() {
+ String key1 = "QED";
+ String key2 = "R&D";
+ assertThat(key1.hashCode()).isEqualTo(key2.hashCode());
+ ImmutableMap<String, Integer> map =
+ ImmutableMap.<String, Integer>builder()
+ .put(key1, 1)
+ .put(key2, 2)
+ .put(key1, 3)
+ .put(key2, 4)
+ .buildKeepingLast();
+ assertMapEquals(map, key1, 3, key2, 4);
+ }
- @Override
- public K getKey() {
- return key;
- }
+ // The java7 branch has different code depending on whether the entry indexes fit in a byte,
+ // short, or int. The small table in testBuildKeepingLast_allowsOverwrite will test the byte
+ // case. This method tests the short case.
+ public void testBuildKeepingLast_shortTable() {
+ Builder<Integer, String> builder = ImmutableMap.builder();
+ Map<Integer, String> expected = new LinkedHashMap<>();
+ for (int i = 0; i < 1000; i++) {
+ // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
+ // duplicates.
+ Integer key = i & ~1;
+ String value = String.valueOf(i);
+ builder.put(key, value);
+ expected.put(key, value);
+ }
+ ImmutableMap<Integer, String> map = builder.buildKeepingLast();
+ assertThat(map).hasSize(500);
+ assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ }
- @Override
- public V getValue() {
- return value;
- }
- }
+ // This method tests the int case.
+ public void testBuildKeepingLast_bigTable() {
+ Builder<Integer, String> builder = ImmutableMap.builder();
+ Map<Integer, String> expected = new LinkedHashMap<>();
+ for (int i = 0; i < 200_000; i++) {
+ // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
+ // duplicates.
+ Integer key = i & ~1;
+ String value = String.valueOf(i);
+ builder.put(key, value);
+ expected.put(key, value);
+ }
+ ImmutableMap<Integer, String> map = builder.buildKeepingLast();
+ assertThat(map).hasSize(100_000);
+ assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ }
- public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(new SimpleEntry<String, Integer>(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- builder.put("foo", 2);
- assertMapEquals(builder.buildOrThrow(), "foo", 2);
- }
+ private static class ClassWithTerribleHashCode implements Comparable<ClassWithTerribleHashCode> {
+ private final int value;
- public void testBuilderPutNullKey() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
+ ClassWithTerribleHashCode(int value) {
+ this.value = value;
}
- public void testBuilderPutNullValue() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ @Override
+ public int compareTo(ClassWithTerribleHashCode that) {
+ return Integer.compare(this.value, that.value);
}
- public void testBuilderPutNullKeyViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
+ @Override
+ public boolean equals(@Nullable Object x) {
+ return x instanceof ClassWithTerribleHashCode
+ && ((ClassWithTerribleHashCode) x).value == value;
}
- public void testBuilderPutNullValueViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap("one", null));
- fail();
- } catch (NullPointerException expected) {
- }
+ @Override
+ public int hashCode() {
+ return 23;
}
- public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
- Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .put("one", 1)
- .put("one", 1); // throwing on this line might be better but it's too late to change
-
- try {
- builder.buildOrThrow();
- fail();
- } catch (IllegalArgumentException expected) {
- }
+ @Override
+ public String toString() {
+ return "ClassWithTerribleHashCode(" + value + ")";
}
+ }
- public void testBuildKeepingLast_allowsOverwrite() {
- Builder<Integer, String> builder =
- new Builder<Integer, String>()
- .put(1, "un")
- .put(2, "deux")
- .put(70, "soixante-dix")
- .put(70, "septante")
- .put(70, "seventy")
- .put(1, "one")
- .put(2, "two");
- ImmutableMap<Integer, String> map = builder.buildKeepingLast();
- assertMapEquals(map, 1, "one", 2, "two", 70, "seventy");
- }
+ @GwtIncompatible
+ public void testBuildKeepingLast_collisions() {
+ Map<ClassWithTerribleHashCode, Integer> expected = new LinkedHashMap<>();
+ Builder<ClassWithTerribleHashCode, Integer> builder = new Builder<>();
+ int size = 18;
+ for (int i = 0; i < size; i++) {
+ ClassWithTerribleHashCode key = new ClassWithTerribleHashCode(i);
+ builder.put(key, i);
+ builder.put(key, -i);
+ expected.put(key, -i);
+ }
+ ImmutableMap<ClassWithTerribleHashCode, Integer> map = builder.buildKeepingLast();
+ assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ }
- public void testBuildKeepingLast_smallTableSameHash() {
- String key1 = "QED";
- String key2 = "R&D";
- assertThat(key1.hashCode()).isEqualTo(key2.hashCode());
- ImmutableMap<String, Integer> map =
- ImmutableMap.<String, Integer>builder()
- .put(key1, 1)
- .put(key2, 2)
- .put(key1, 3)
- .put(key2, 4)
- .buildKeepingLast();
- assertMapEquals(map, key1, 3, key2, 4);
+ @GwtIncompatible // Pattern, Matcher
+ public void testBuilder_keepingLast_thenOrThrow() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 3)
+ .put("four", 5)
+ .put("four", 4) // this should win because it's last
+ .put("two", 2);
+ assertMapEquals(
+ builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2);
+ try {
+ builder.buildOrThrow();
+ fail("Expected exception from duplicate keys");
+ } catch (IllegalArgumentException expected) {
+ // We don't really care which values the exception message contains, but they should be
+ // different from each other. If buildKeepingLast() collapsed duplicates, that might end up
+ // not being true.
+ Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)");
+ assertThat(expected).hasMessageThat().matches(pattern);
+ Matcher matcher = pattern.matcher(expected.getMessage());
+ assertThat(matcher.matches()).isTrue();
+ assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2));
}
+ }
- // The java7 branch has different code depending on whether the entry indexes fit in a byte,
- // short, or int. The small table in testBuildKeepingLast_allowsOverwrite will test the byte
- // case. This method tests the short case.
- public void testBuildKeepingLast_shortTable() {
- Builder<Integer, String> builder = ImmutableMap.builder();
- Map<Integer, String> expected = new LinkedHashMap<>();
- for (int i = 0; i < 1000; i++) {
- // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
- // duplicates.
- Integer key = i & ~1;
- String value = String.valueOf(i);
- builder.put(key, value);
- expected.put(key, value);
- }
- ImmutableMap<Integer, String> map = builder.buildKeepingLast();
- assertThat(map).hasSize(500);
- assertThat(map).containsExactlyEntriesIn(expected).inOrder();
- }
+ public void testOf() {
+ assertMapEquals(ImmutableMap.of("one", 1), "one", 1);
+ assertMapEquals(ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2);
+ assertMapEquals(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
+ assertMapEquals(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4);
+ assertMapEquals(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9,
+ "ten", 10),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9,
+ "ten",
+ 10);
+ }
- // This method tests the int case.
- public void testBuildKeepingLast_bigTable() {
- Builder<Integer, String> builder = ImmutableMap.builder();
- Map<Integer, String> expected = new LinkedHashMap<>();
- for (int i = 0; i < 200_000; i++) {
- // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
- // duplicates.
- Integer key = i & ~1;
- String value = String.valueOf(i);
- builder.put(key, value);
- expected.put(key, value);
- }
- ImmutableMap<Integer, String> map = builder.buildKeepingLast();
- assertThat(map).hasSize(100_000);
- assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ public void testOfNullKey() {
+ try {
+ ImmutableMap.of(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
- @GwtIncompatible // Pattern, Matcher
- public void testBuilder_keepingLast_thenOrThrow() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 3)
- .put("four", 5)
- .put("four", 4) // this should win because it's last
- .put("two", 2);
- assertMapEquals(
- builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2);
- try {
- builder.buildOrThrow();
- fail("Expected exception from duplicate keys");
- } catch (IllegalArgumentException expected) {
- // We don't really care which values the exception message contains, but they should be
- // different from each other. If buildKeepingLast() collapsed duplicates, that might end up
- // not being true.
- Pattern pattern =
- Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)");
- assertThat(expected).hasMessageThat().matches(pattern);
- Matcher matcher = pattern.matcher(expected.getMessage());
- assertThat(matcher.matches()).isTrue();
- assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2));
- }
+ try {
+ ImmutableMap.of("one", 1, null, 2);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOf() {
- assertMapEquals(ImmutableMap.of("one", 1), "one", 1);
- assertMapEquals(ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2);
- assertMapEquals(
- ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
- assertMapEquals(
- ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4);
- assertMapEquals(
- ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9,
- "ten", 10),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9,
- "ten",
- 10);
+ public void testOfNullValue() {
+ try {
+ ImmutableMap.of("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testOfNullKey() {
- try {
- ImmutableMap.of(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableMap.of("one", 1, null, 2);
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ ImmutableMap.of("one", 1, "two", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOfNullValue() {
- try {
- ImmutableMap.of("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableMap.of("one", 1, "two", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfWithDuplicateKey() {
+ try {
+ ImmutableMap.of("one", 1, "one", 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testOfWithDuplicateKey() {
- try {
- ImmutableMap.of("one", 1, "one", 1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
+ public void testCopyOfEmptyMap() {
+ ImmutableMap<String, Integer> copy =
+ ImmutableMap.copyOf(Collections.<String, Integer>emptyMap());
+ assertEquals(Collections.<String, Integer>emptyMap(), copy);
+ assertSame(copy, ImmutableMap.copyOf(copy));
+ }
- public void testCopyOfEmptyMap() {
- ImmutableMap<String, Integer> copy =
- ImmutableMap.copyOf(Collections.<String, Integer>emptyMap());
- assertEquals(Collections.<String, Integer>emptyMap(), copy);
- assertSame(copy, ImmutableMap.copyOf(copy));
- }
+ public void testCopyOfSingletonMap() {
+ ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1));
+ assertMapEquals(copy, "one", 1);
+ assertSame(copy, ImmutableMap.copyOf(copy));
+ }
- public void testCopyOfSingletonMap() {
- ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1));
- assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableMap.copyOf(copy));
- }
+ public void testCopyOf() {
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- public void testCopyOf() {
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
+ ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original);
+ assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
+ assertSame(copy, ImmutableMap.copyOf(copy));
+ }
- ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original);
- assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
- assertSame(copy, ImmutableMap.copyOf(copy));
- }
+ // TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7.
+ public void testToImmutableMap_java7_combine() {
+ ImmutableMap.Builder<String, Integer> zis =
+ ImmutableMap.<String, Integer>builder().put("one", 1);
+ ImmutableMap.Builder<String, Integer> zat =
+ ImmutableMap.<String, Integer>builder().put("two", 2).put("three", 3);
+ assertMapEquals(zis.combine(zat).build(), "one", 1, "two", 2, "three", 3);
+ }
- // TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7.
- public void testToImmutableMap_java7_combine() {
- ImmutableMap.Builder<String, Integer> zis =
- ImmutableMap.<String, Integer>builder().put("one", 1);
- ImmutableMap.Builder<String, Integer> zat =
- ImmutableMap.<String, Integer>builder().put("two", 2).put("three", 3);
- assertMapEquals(zis.combine(zat).build(), "one", 1, "two", 2, "three", 3);
+ // TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7.
+ public void testToImmutableMap_exceptionOnDuplicateKey_java7_combine() {
+ ImmutableMap.Builder<String, Integer> zis =
+ ImmutableMap.<String, Integer>builder().put("one", 1).put("two", 2);
+ ImmutableMap.Builder<String, Integer> zat =
+ ImmutableMap.<String, Integer>builder().put("two", 22).put("three", 3);
+ try {
+ zis.combine(zat).build();
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ // expected
}
+ }
- // TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7.
- public void testToImmutableMap_exceptionOnDuplicateKey_java7_combine() {
- ImmutableMap.Builder<String, Integer> zis =
- ImmutableMap.<String, Integer>builder().put("one", 1).put("two", 2);
- ImmutableMap.Builder<String, Integer> zat =
- ImmutableMap.<String, Integer>builder().put("two", 22).put("three", 3);
- try {
- zis.combine(zat).build();
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- // expected
+ public static void hashtableTestHelper(ImmutableList<Integer> sizes) {
+ for (int size : sizes) {
+ Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(size);
+ for (int i = 0; i < size; i++) {
+ Integer integer = i;
+ builder.put(integer, integer);
}
- }
-
- public static void hashtableTestHelper(ImmutableList<Integer> sizes) {
- for (int size : sizes) {
- Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(size);
- for (int i = 0; i < size; i++) {
- Integer integer = i;
- builder.put(integer, integer);
- }
- ImmutableMap<Integer, Integer> map = builder.build();
- assertEquals(size, map.size());
- int entries = 0;
- for (Integer key : map.keySet()) {
- assertEquals(entries, key.intValue());
- assertSame(key, map.get(key));
- entries++;
- }
- assertEquals(size, entries);
+ ImmutableMap<Integer, Integer> map = builder.build();
+ assertEquals(size, map.size());
+ int entries = 0;
+ for (Integer key : map.keySet()) {
+ assertEquals(entries, key.intValue());
+ assertSame(key, map.get(key));
+ entries++;
}
+ assertEquals(size, entries);
}
+ }
- public void testByteArrayHashtable() {
- hashtableTestHelper(ImmutableList.of(2, 89));
- }
+ public void testByteArrayHashtable() {
+ hashtableTestHelper(ImmutableList.of(2, 89));
+ }
- public void testShortArrayHashtable() {
- hashtableTestHelper(ImmutableList.of(90, 22937));
- }
+ public void testShortArrayHashtable() {
+ hashtableTestHelper(ImmutableList.of(90, 22937));
+ }
- public void testIntArrayHashtable() {
- hashtableTestHelper(ImmutableList.of(22938));
- }
+ public void testIntArrayHashtable() {
+ hashtableTestHelper(ImmutableList.of(22938));
}
+ // Non-creation tests
+
public void testNullGet() {
ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1);
assertNull(map.get(null));
@@ -1027,7 +918,7 @@ public class ImmutableMapTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof IntHolder) && ((IntHolder) o).value == value;
}
@@ -1087,7 +978,7 @@ public class ImmutableMapTest extends TestCase {
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked")
public void ignore_testSerializationNoDuplication_regularImmutableMap() throws Exception {
- // Tests that searializing a map, its keySet, and values only writes the underlying data once.
+ // Tests that serializing a map, its keySet, and values only writes the underlying data once.
Object[] entries = new Object[2000];
for (int i = 0; i < entries.length; i++) {
@@ -1198,4 +1089,25 @@ public class ImmutableMapTest extends TestCase {
private static <T> Entry<T, T> entry(T key, T value) {
return new AbstractMap.SimpleImmutableEntry<>(key, value);
}
+
+ public void testCopyOfMutableEntryList() {
+ List<Entry<String, String>> entryList =
+ Arrays.asList(
+ new AbstractMap.SimpleEntry<>("a", "1"), new AbstractMap.SimpleEntry<>("b", "2"));
+ ImmutableMap<String, String> map = ImmutableMap.copyOf(entryList);
+ assertThat(map).containsExactly("a", "1", "b", "2").inOrder();
+ entryList.get(0).setValue("3");
+ assertThat(map).containsExactly("a", "1", "b", "2").inOrder();
+ }
+
+ public void testBuilderPutAllEntryList() {
+ List<Entry<String, String>> entryList =
+ Arrays.asList(
+ new AbstractMap.SimpleEntry<>("a", "1"), new AbstractMap.SimpleEntry<>("b", "2"));
+ ImmutableMap<String, String> map =
+ ImmutableMap.<String, String>builder().putAll(entryList).buildOrThrow();
+ assertThat(map).containsExactly("a", "1", "b", "2").inOrder();
+ entryList.get(0).setValue("3");
+ assertThat(map).containsExactly("a", "1", "b", "2").inOrder();
+ }
}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java
new file mode 100644
index 000000000..76a1fac59
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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 com.google.common.collect.testing.SampleElements.Colliders;
+import java.util.Map;
+
+@GwtCompatible
+public class ImmutableMapWithBadHashesMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<Object, Integer> {
+ @Override
+ protected Map<Object, Integer> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Map<Object, Integer> makePopulatedMap() {
+ Colliders colliders = new Colliders();
+ return ImmutableMap.of(
+ colliders.e0(), 0,
+ colliders.e1(), 1,
+ colliders.e2(), 2,
+ colliders.e3(), 3);
+ }
+
+ @Override
+ protected Object getKeyNotInPopulatedMap() {
+ return new Colliders().e4();
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java
new file mode 100644
index 000000000..5823d542d
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapHeadMapInclusiveMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("c", true);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "d";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java
new file mode 100644
index 000000000..ed96bd1f5
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapHeadMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("d");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "d";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java
new file mode 100644
index 000000000..7d4566390
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapSubMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).subMap("b", "d");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java
new file mode 100644
index 000000000..15ba852fa
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapTailMapExclusiveMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("a", false);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java
new file mode 100644
index 000000000..54c3aa575
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapTailMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("b");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java
index 4a9178b4a..f3e7c1bd6 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java
@@ -20,12 +20,10 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSortedMap.Builder;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.NavigableMapTestSuiteBuilder;
-import com.google.common.collect.testing.SortedMapInterfaceTest;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -47,6 +45,7 @@ import java.util.TreeMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ImmutableSortedMap}.
@@ -119,713 +118,541 @@ public class ImmutableSortedMapTest extends TestCase {
return suite;
}
- public abstract static class AbstractMapTests<K, V> extends SortedMapInterfaceTest<K, V> {
- public AbstractMapTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- protected SortedMap<K, V> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- private static final Joiner joiner = Joiner.on(", ");
+ // Creation tests
- @Override
- protected void assertMoreInvariants(Map<K, V> map) {
- // TODO: can these be moved to MapInterfaceTest?
- for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
- }
-
- assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
- assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
- assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
- assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());
-
- assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
- assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
- }
+ public void testEmptyBuilder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder().build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class MapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makeEmptyMap() {
- return ImmutableSortedMap.of();
- }
-
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testSingletonBuilder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).build();
+ assertMapEquals(map, "one", 1);
}
- public static class SingletonMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("one", 1);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testBuilder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
}
- @GwtIncompatible // SerializableTester
- public static class ReserializedMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return SerializableTester.reserialize(ImmutableSortedMap.of("one", 1, "two", 2, "three", 3));
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
+ @SuppressWarnings("DoNotCall")
+ public void testBuilder_orderEntriesByValueFails() {
+ ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.orderEntriesByValue(Ordering.natural());
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException expected) {
}
}
- public static class HeadMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("d");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "d";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
- }
+ public void testBuilder_withImmutableEntry() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .put(Maps.immutableEntry("one", 1))
+ .build();
+ assertMapEquals(map, "one", 1);
}
- public static class HeadMapInclusiveTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("c", true);
+ public void testBuilder_withImmutableEntryAndNullContents() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.put(Maps.immutableEntry("one", (Integer) null));
+ fail();
+ } catch (NullPointerException expected) {
}
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "d";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
+ try {
+ builder.put(Maps.immutableEntry((String) null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
}
- public static class TailMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("b");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 1;
- }
+ private static class StringHolder {
+ String string;
}
- public static class TailExclusiveMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("a", false);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 1;
- }
+ public void testBuilder_withMutableEntry() {
+ ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ final StringHolder holder = new StringHolder();
+ holder.string = "one";
+ Entry<String, Integer> entry =
+ new AbstractMapEntry<String, Integer>() {
+ @Override
+ public String getKey() {
+ return holder.string;
+ }
+
+ @Override
+ public Integer getValue() {
+ return 1;
+ }
+ };
+
+ builder.put(entry);
+ holder.string = "two";
+ assertMapEquals(builder.build(), "one", 1);
}
- public static class SubMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).subMap("b", "d");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
- }
+ public void testBuilderPutAllWithEmptyMap() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .putAll(Collections.<String, Integer>emptyMap())
+ .build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class CreationTests extends TestCase {
- public void testEmptyBuilder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder().build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
- }
-
- public void testSingletonBuilder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).build();
- assertMapEquals(map, "one", 1);
- }
-
- public void testBuilder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
- }
+ public void testBuilderPutAll() {
+ Map<String, Integer> toPut = new LinkedHashMap<>();
+ toPut.put("one", 1);
+ toPut.put("two", 2);
+ toPut.put("three", 3);
+ Map<String, Integer> moreToPut = new LinkedHashMap<>();
+ moreToPut.put("four", 4);
+ moreToPut.put("five", 5);
+
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder().putAll(toPut).putAll(moreToPut).build();
+ assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
+ }
- @SuppressWarnings("DoNotCall")
- public void testBuilder_orderEntriesByValueFails() {
- ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.orderEntriesByValue(Ordering.natural());
- fail("Expected UnsupportedOperationException");
- } catch (UnsupportedOperationException expected) {
- }
- }
+ public void testBuilderReuse() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ ImmutableSortedMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
+ ImmutableSortedMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
- public void testBuilder_withImmutableEntry() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .put(Maps.immutableEntry("one", 1))
- .build();
- assertMapEquals(map, "one", 1);
- }
-
- public void testBuilder_withImmutableEntryAndNullContents() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.put(Maps.immutableEntry("one", (Integer) null));
- fail();
- } catch (NullPointerException expected) {
- }
- try {
- builder.put(Maps.immutableEntry((String) null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ assertMapEquals(mapOne, "one", 1, "two", 2);
+ assertMapEquals(mapTwo, "four", 4, "one", 1, "three", 3, "two", 2);
+ }
- private static class StringHolder {
- String string;
+ public void testBuilderPutNullKey() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilder_withMutableEntry() {
- ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- final StringHolder holder = new StringHolder();
- holder.string = "one";
- Entry<String, Integer> entry =
- new AbstractMapEntry<String, Integer>() {
- @Override
- public String getKey() {
- return holder.string;
- }
-
- @Override
- public Integer getValue() {
- return 1;
- }
- };
-
- builder.put(entry);
- holder.string = "two";
- assertMapEquals(builder.build(), "one", 1);
+ public void testBuilderPutNullValue() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.put("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAllWithEmptyMap() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .putAll(Collections.<String, Integer>emptyMap())
- .build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
+ public void testBuilderPutNullKeyViaPutAll() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAll() {
- Map<String, Integer> toPut = new LinkedHashMap<>();
- toPut.put("one", 1);
- toPut.put("two", 2);
- toPut.put("three", 3);
- Map<String, Integer> moreToPut = new LinkedHashMap<>();
- moreToPut.put("four", 4);
- moreToPut.put("five", 5);
-
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .putAll(toPut)
- .putAll(moreToPut)
- .build();
- assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
+ public void testBuilderPutNullValueViaPutAll() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap("one", null));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderReuse() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- ImmutableSortedMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
- ImmutableSortedMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
+ public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
+ Builder<String, Integer> builder =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .put("one", 1)
+ .put("one", 2); // throwing on this line would be even better
- assertMapEquals(mapOne, "one", 1, "two", 2);
- assertMapEquals(mapTwo, "four", 4, "one", 1, "three", 3, "two", 2);
+ try {
+ builder.build();
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testBuilderPutNullKey() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testOf() {
+ assertMapEquals(ImmutableSortedMap.of("one", 1), "one", 1);
+ assertMapEquals(ImmutableSortedMap.of("one", 1, "two", 2), "one", 1, "two", 2);
+ assertMapEquals(
+ ImmutableSortedMap.of("one", 1, "two", 2, "three", 3), "one", 1, "three", 3, "two", 2);
+ assertMapEquals(
+ ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4),
+ "four",
+ 4,
+ "one",
+ 1,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6),
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7),
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8),
+ "eight",
+ 8,
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9),
+ "eight",
+ 8,
+ "five",
+ 5,
+ "four",
+ 4,
+ "nine",
+ 9,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9,
+ "ten", 10),
+ "eight",
+ 8,
+ "five",
+ 5,
+ "four",
+ 4,
+ "nine",
+ 9,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "ten",
+ 10,
+ "three",
+ 3,
+ "two",
+ 2);
+ }
- public void testBuilderPutNullValue() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.put("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullKey() {
+ Integer n = null;
+ try {
+ ImmutableSortedMap.of(n, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testBuilderPutNullKeyViaPutAll() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ ImmutableSortedMap.of("one", 1, null, 2);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutNullValueViaPutAll() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap("one", null));
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullValue() {
+ try {
+ ImmutableSortedMap.of("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
- Builder<String, Integer> builder =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .put("one", 1)
- .put("one", 2); // throwing on this line would be even better
-
- try {
- builder.build();
- fail();
- } catch (IllegalArgumentException expected) {
- }
+ try {
+ ImmutableSortedMap.of("one", 1, "two", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOf() {
- assertMapEquals(ImmutableSortedMap.of("one", 1), "one", 1);
- assertMapEquals(ImmutableSortedMap.of("one", 1, "two", 2), "one", 1, "two", 2);
- assertMapEquals(
- ImmutableSortedMap.of("one", 1, "two", 2, "three", 3), "one", 1, "three", 3, "two", 2);
- assertMapEquals(
- ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4),
- "four",
- 4,
- "one",
- 1,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6),
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7),
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8),
- "eight",
- 8,
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9),
- "eight",
- 8,
- "five",
- 5,
- "four",
- 4,
- "nine",
- 9,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9,
- "ten", 10),
- "eight",
- 8,
- "five",
- 5,
- "four",
- 4,
- "nine",
- 9,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "ten",
- 10,
- "three",
- 3,
- "two",
- 2);
+ public void testOfWithDuplicateKey() {
+ try {
+ ImmutableSortedMap.of("one", 1, "one", 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testOfNullKey() {
- Integer n = null;
- try {
- ImmutableSortedMap.of(n, 1);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOfEmptyMap() {
+ ImmutableSortedMap<String, Integer> copy =
+ ImmutableSortedMap.copyOf(Collections.<String, Integer>emptyMap());
+ assertEquals(Collections.<String, Integer>emptyMap(), copy);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- try {
- ImmutableSortedMap.of("one", 1, null, 2);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOfSingletonMap() {
+ ImmutableSortedMap<String, Integer> copy =
+ ImmutableSortedMap.copyOf(Collections.singletonMap("one", 1));
+ assertMapEquals(copy, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- public void testOfNullValue() {
- try {
- ImmutableSortedMap.of("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOf() {
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- try {
- ImmutableSortedMap.of("one", 1, "two", null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original);
+ assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- public void testOfWithDuplicateKey() {
- try {
- ImmutableSortedMap.of("one", 1, "one", 1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
+ public void testCopyOfExplicitComparator() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
+
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
+ assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
+ assertSame(comparator, copy.comparator());
+ }
- public void testCopyOfEmptyMap() {
- ImmutableSortedMap<String, Integer> copy =
- ImmutableSortedMap.copyOf(Collections.<String, Integer>emptyMap());
- assertEquals(Collections.<String, Integer>emptyMap(), copy);
- assertSame(copy, ImmutableSortedMap.copyOf(copy));
- assertSame(Ordering.natural(), copy.comparator());
- }
+ public void testCopyOfImmutableSortedSetDifferentComparator() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ Map<String, Integer> original = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
+ assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
+ assertSame(comparator, copy.comparator());
+ }
- public void testCopyOfSingletonMap() {
- ImmutableSortedMap<String, Integer> copy =
- ImmutableSortedMap.copyOf(Collections.singletonMap("one", 1));
- assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOf(copy));
- assertSame(Ordering.natural(), copy.comparator());
- }
+ public void testCopyOfSortedNatural() {
+ SortedMap<String, Integer> original = Maps.newTreeMap();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- public void testCopyOf() {
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
+ assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
+ assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original);
- assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
- assertSame(copy, ImmutableSortedMap.copyOf(copy));
- assertSame(Ordering.natural(), copy.comparator());
- }
+ public void testCopyOfSortedExplicit() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ SortedMap<String, Integer> original = Maps.newTreeMap(comparator);
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
+
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
+ assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
+ assertSame(comparator, copy.comparator());
+ }
- public void testCopyOfExplicitComparator() {
- Comparator<String> comparator = Ordering.natural().reverse();
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
-
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
- assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
- assertSame(comparator, copy.comparator());
- }
+ private static class IntegerDiv10 implements Comparable<IntegerDiv10> {
+ final int value;
- public void testCopyOfImmutableSortedSetDifferentComparator() {
- Comparator<String> comparator = Ordering.natural().reverse();
- Map<String, Integer> original = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
- assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
- assertSame(comparator, copy.comparator());
+ IntegerDiv10(int value) {
+ this.value = value;
}
- public void testCopyOfSortedNatural() {
- SortedMap<String, Integer> original = Maps.newTreeMap();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
-
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
- assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
- assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
- assertSame(Ordering.natural(), copy.comparator());
+ @Override
+ public int compareTo(IntegerDiv10 o) {
+ return value / 10 - o.value / 10;
}
- public void testCopyOfSortedExplicit() {
- Comparator<String> comparator = Ordering.natural().reverse();
- SortedMap<String, Integer> original = Maps.newTreeMap(comparator);
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
-
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
- assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
- assertSame(comparator, copy.comparator());
+ @Override
+ public String toString() {
+ return Integer.toString(value);
}
+ }
- private static class IntegerDiv10 implements Comparable<IntegerDiv10> {
- final int value;
-
- IntegerDiv10(int value) {
- this.value = value;
- }
-
- @Override
- public int compareTo(IntegerDiv10 o) {
- return value / 10 - o.value / 10;
- }
+ public void testCopyOfDuplicateKey() {
+ Map<IntegerDiv10, String> original =
+ ImmutableMap.of(
+ new IntegerDiv10(3), "three",
+ new IntegerDiv10(20), "twenty",
+ new IntegerDiv10(11), "eleven",
+ new IntegerDiv10(35), "thirty five",
+ new IntegerDiv10(12), "twelve");
- @Override
- public String toString() {
- return Integer.toString(value);
- }
- }
-
- public void testCopyOfDuplicateKey() {
- Map<IntegerDiv10, String> original =
- ImmutableMap.of(
- new IntegerDiv10(3), "three",
- new IntegerDiv10(20), "twenty",
- new IntegerDiv10(11), "eleven",
- new IntegerDiv10(35), "thirty five",
- new IntegerDiv10(12), "twelve");
-
- try {
- ImmutableSortedMap.copyOf(original);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
+ try {
+ ImmutableSortedMap.copyOf(original);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testImmutableMapCopyOfImmutableSortedMap() {
- IntegerDiv10 three = new IntegerDiv10(3);
- IntegerDiv10 eleven = new IntegerDiv10(11);
- IntegerDiv10 twelve = new IntegerDiv10(12);
- IntegerDiv10 twenty = new IntegerDiv10(20);
- Map<IntegerDiv10, String> original =
- ImmutableSortedMap.of(three, "three", eleven, "eleven", twenty, "twenty");
- Map<IntegerDiv10, String> copy = ImmutableMap.copyOf(original);
- assertTrue(original.containsKey(twelve));
- assertFalse(copy.containsKey(twelve));
- }
+ public void testImmutableMapCopyOfImmutableSortedMap() {
+ IntegerDiv10 three = new IntegerDiv10(3);
+ IntegerDiv10 eleven = new IntegerDiv10(11);
+ IntegerDiv10 twelve = new IntegerDiv10(12);
+ IntegerDiv10 twenty = new IntegerDiv10(20);
+ Map<IntegerDiv10, String> original =
+ ImmutableSortedMap.of(three, "three", eleven, "eleven", twenty, "twenty");
+ Map<IntegerDiv10, String> copy = ImmutableMap.copyOf(original);
+ assertTrue(original.containsKey(twelve));
+ assertFalse(copy.containsKey(twelve));
+ }
- public void testBuilderReverseOrder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>reverseOrder()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
- assertEquals(Ordering.natural().reverse(), map.comparator());
- }
+ public void testBuilderReverseOrder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>reverseOrder()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
+ assertEquals(Ordering.natural().reverse(), map.comparator());
+ }
- public void testBuilderComparator() {
- Comparator<String> comparator = Ordering.natural().reverse();
- ImmutableSortedMap<String, Integer> map =
- new ImmutableSortedMap.Builder<String, Integer>(comparator)
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
- assertSame(comparator, map.comparator());
- }
+ public void testBuilderComparator() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ ImmutableSortedMap<String, Integer> map =
+ new ImmutableSortedMap.Builder<String, Integer>(comparator)
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
+ assertSame(comparator, map.comparator());
+ }
- // TODO(b/172823566): Use mainline testToImmutableSortedMap once CollectorTester is usable.
- public void testToImmutableSortedMap_java7_combine() {
- ImmutableSortedMap.Builder<String, Integer> zis =
- ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).put("four", 4);
- ImmutableSortedMap.Builder<String, Integer> zat =
- ImmutableSortedMap.<String, Integer>naturalOrder().put("two", 2).put("three", 3);
- ImmutableSortedMap<String, Integer> sortedMap = zis.combine(zat).build();
- assertMapEquals(sortedMap, "four", 4, "one", 1, "three", 3, "two", 2);
- }
+ // TODO(b/172823566): Use mainline testToImmutableSortedMap once CollectorTester is usable.
+ public void testToImmutableSortedMap_java7_combine() {
+ ImmutableSortedMap.Builder<String, Integer> zis =
+ ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).put("four", 4);
+ ImmutableSortedMap.Builder<String, Integer> zat =
+ ImmutableSortedMap.<String, Integer>naturalOrder().put("two", 2).put("three", 3);
+ ImmutableSortedMap<String, Integer> sortedMap = zis.combine(zat).build();
+ assertMapEquals(sortedMap, "four", 4, "one", 1, "three", 3, "two", 2);
+ }
- // TODO(b/172823566): Use mainline testToImmutableSortedMap once CollectorTester is usable.
- public void testToImmutableSortedMap_exceptionOnDuplicateKey_java7_combine() {
- ImmutableSortedMap.Builder<String, Integer> zis =
- ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).put("two", 2);
- ImmutableSortedMap.Builder<String, Integer> zat =
- ImmutableSortedMap.<String, Integer>naturalOrder().put("two", 22).put("three", 3);
- try {
- ImmutableSortedMap.Builder<String, Integer> combined = zis.combine(zat);
- combined.build();
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- // expected
- }
+ // TODO(b/172823566): Use mainline testToImmutableSortedMap once CollectorTester is usable.
+ public void testToImmutableSortedMap_exceptionOnDuplicateKey_java7_combine() {
+ ImmutableSortedMap.Builder<String, Integer> zis =
+ ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).put("two", 2);
+ ImmutableSortedMap.Builder<String, Integer> zat =
+ ImmutableSortedMap.<String, Integer>naturalOrder().put("two", 22).put("three", 3);
+ try {
+ ImmutableSortedMap.Builder<String, Integer> combined = zis.combine(zat);
+ combined.build();
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
+ // expected
}
}
+ // Other tests
+
public void testNullGet() {
ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.of("one", 1);
assertNull(map.get(null));
@@ -891,7 +718,7 @@ public class ImmutableSortedMapTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof IntHolder) && ((IntHolder) o).value == value;
}
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java
index ea0e3a8d1..4043497b6 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java
@@ -954,7 +954,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest {
assertEquals(list, copy);
}
- public void testAsListInconsistentComprator() {
+ public void testAsListInconsistentComparator() {
ImmutableSet<String> set =
ImmutableSortedSet.orderedBy(STRING_LENGTH)
.add("in", "the", "quick", "jumped", "over", "a")
diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java
index 9bdc99cab..4083ec43e 100644
--- a/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java
@@ -479,4 +479,33 @@ public class ImmutableTableTest extends AbstractTableReadTest {
}
assertTrue(builder.build() instanceof SparseImmutableTable);
}
+
+ @GwtIncompatible // NullPointerTester
+ @Override
+ public void testNullPointerInstance() {
+ if (isAndroid()) {
+ /*
+ * NPT fails under the old versions of Android we test under because it performs reflection on
+ * ImmutableTable, which declares static methods that refer to Collector, which is unavailable
+ * under such versions.
+ *
+ * We use a runtime check here instead of @AndroidIncompatible: @AndroidIncompatible operates
+ * by stripping annotated methods entirely, and if we strip this method, then JUnit would just
+ * run the supermethod as usual.
+ *
+ * TODO: b/292578973: Use @AndroidIncompatible if we change our system to keep the methods in
+ * place but to have the test runner skip them. However, note that if we choose to *both*
+ * strip the methods *and* have the test runner not run them (for some unusual cases in which
+ * we don't run the stripping test for technical reasons), then we'd be back to the problem
+ * described above, since the supermethod is *not* annotated @AndroidIncompatible (since it
+ * works fine with the other Table implementations).
+ */
+ return;
+ }
+ super.testNullPointerInstance();
+ }
+
+ private static boolean isAndroid() {
+ return System.getProperty("java.runtime.name", "").contains("Android");
+ }
}
diff --git a/android/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java b/android/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java
new file mode 100644
index 000000000..9cd2d9091
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredIterableTest;
+
+public final class IterablesFilterArrayListTest
+ extends AbstractFilteredIterableTest<Iterable<Integer>> {
+ @Override
+ Iterable<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Lists.newArrayList(contents);
+ }
+
+ @Override
+ Iterable<Integer> filter(Iterable<Integer> elements, Predicate<? super Integer> predicate) {
+ return Iterables.filter(elements, predicate);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/LegacyComparable.java b/android/guava-tests/test/com/google/common/collect/LegacyComparable.java
index 8b0c9620c..05a6607a4 100644
--- a/android/guava-tests/test/com/google/common/collect/LegacyComparable.java
+++ b/android/guava-tests/test/com/google/common/collect/LegacyComparable.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Arrays;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A class that implements {@code Comparable} without generics, such as those found in libraries
@@ -51,7 +52,7 @@ class LegacyComparable implements Comparable, Serializable {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object instanceof LegacyComparable) {
LegacyComparable that = (LegacyComparable) object;
return this.value.equals(that.value);
diff --git a/android/guava-tests/test/com/google/common/collect/ListsImplTest.java b/android/guava-tests/test/com/google/common/collect/ListsImplTest.java
index 2d18f5a72..8ef599c99 100644
--- a/android/guava-tests/test/com/google/common/collect/ListsImplTest.java
+++ b/android/guava-tests/test/com/google/common/collect/ListsImplTest.java
@@ -64,7 +64,7 @@ public class ListsImplTest extends TestCase {
/** Creates a new list with the given contents. */
public abstract <T> List<T> createList(Class<T> listType, Collection<? extends T> contents);
- /** The modifiablity of this list example. */
+ /** The modifiability of this list example. */
public Modifiability modifiability() {
return modifiability;
}
diff --git a/android/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java b/android/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java
index 47fc74c82..453e3e74d 100644
--- a/android/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java
@@ -90,7 +90,7 @@ public class MapMakerInternalMapTest extends TestCase {
}
public void testSetConcurrencyLevel() {
- // round up to nearest power of two
+ // round up to the nearest power of two
checkConcurrencyLevel(1, 1);
checkConcurrencyLevel(2, 2);
@@ -109,7 +109,7 @@ public class MapMakerInternalMapTest extends TestCase {
}
public void testSetInitialCapacity() {
- // share capacity over each segment, then round up to nearest power of two
+ // share capacity over each segment, then round up to the nearest power of two
checkInitialCapacity(1, 0, 1);
checkInitialCapacity(1, 1, 1);
@@ -152,42 +152,6 @@ public class MapMakerInternalMapTest extends TestCase {
}
}
- public void testSetMaximumSize() {
- // vary maximumSize wrt concurrencyLevel
-
- for (int maxSize = 1; maxSize < 8; maxSize++) {
- checkMaximumSize(1, 8, maxSize);
- checkMaximumSize(2, 8, maxSize);
- checkMaximumSize(4, 8, maxSize);
- checkMaximumSize(8, 8, maxSize);
- }
-
- checkMaximumSize(1, 8, Integer.MAX_VALUE);
- checkMaximumSize(2, 8, Integer.MAX_VALUE);
- checkMaximumSize(4, 8, Integer.MAX_VALUE);
- checkMaximumSize(8, 8, Integer.MAX_VALUE);
-
- // vary initial capacity wrt maximumSize
-
- for (int capacity = 0; capacity < 8; capacity++) {
- checkMaximumSize(1, capacity, 4);
- checkMaximumSize(2, capacity, 4);
- checkMaximumSize(4, capacity, 4);
- checkMaximumSize(8, capacity, 4);
- }
- }
-
- private static void checkMaximumSize(int concurrencyLevel, int initialCapacity, int maxSize) {
- MapMakerInternalMap<Object, Object, ?, ?> map =
- makeMap(
- createMapMaker().concurrencyLevel(concurrencyLevel).initialCapacity(initialCapacity));
- int totalCapacity = 0;
- for (int i = 0; i < map.segments.length; i++) {
- totalCapacity += map.segments[i].maxSegmentSize;
- }
- assertTrue("totalCapcity=" + totalCapacity + ", maxSize=" + maxSize, totalCapacity <= maxSize);
- }
-
public void testSetWeakKeys() {
MapMakerInternalMap<Object, Object, ?, ?> map = makeMap(createMapMaker().weakKeys());
checkStrength(map, Strength.WEAK, Strength.STRONG);
diff --git a/android/guava-tests/test/com/google/common/collect/MapMakerTest.java b/android/guava-tests/test/com/google/common/collect/MapMakerTest.java
index 9669ded7c..5e93001c7 100644
--- a/android/guava-tests/test/com/google/common/collect/MapMakerTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MapMakerTest.java
@@ -30,7 +30,6 @@ import junit.framework.TestCase;
/** @author Charles Fry */
@GwtCompatible(emulated = true)
public class MapMakerTest extends TestCase {
-
@GwtIncompatible // NullPointerTester
public void testNullParameters() throws Exception {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/collect/MapsCollectionTest.java b/android/guava-tests/test/com/google/common/collect/MapsCollectionTest.java
index 9aa8e66b7..1e600647b 100644
--- a/android/guava-tests/test/com/google/common/collect/MapsCollectionTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MapsCollectionTest.java
@@ -49,10 +49,10 @@ import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
-import javax.annotation.CheckForNull;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Test suites for wrappers in {@code Maps}.
@@ -561,7 +561,7 @@ public class MapsCollectionTest extends TestCase {
static final Predicate<String> FILTER_KEYS =
new Predicate<String>() {
@Override
- public boolean apply(@CheckForNull String string) {
+ public boolean apply(@Nullable String string) {
return !"banana".equals(string) && !"eggplant".equals(string);
}
};
@@ -569,7 +569,7 @@ public class MapsCollectionTest extends TestCase {
static final Predicate<String> FILTER_VALUES =
new Predicate<String>() {
@Override
- public boolean apply(@CheckForNull String string) {
+ public boolean apply(@Nullable String string) {
return !"toast".equals(string) && !"spam".equals(string);
}
};
diff --git a/android/guava-tests/test/com/google/common/collect/MapsTest.java b/android/guava-tests/test/com/google/common/collect/MapsTest.java
index d0f983863..1672efa19 100644
--- a/android/guava-tests/test/com/google/common/collect/MapsTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MapsTest.java
@@ -31,7 +31,6 @@ import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
import com.google.common.collect.Maps.EntryTransformer;
import com.google.common.collect.Maps.ValueDifferenceImpl;
import com.google.common.collect.SetsTest.Derived;
@@ -63,6 +62,7 @@ import java.util.SortedSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@code Maps}.
@@ -126,7 +126,10 @@ public class MapsTest extends TestCase {
for (int size = 1; size < 200; size++) {
assertWontGrow(
- size, Maps.newHashMapWithExpectedSize(size), Maps.newHashMapWithExpectedSize(size));
+ size,
+ new HashMap<>(),
+ Maps.newHashMapWithExpectedSize(size),
+ Maps.newHashMapWithExpectedSize(size));
}
}
@@ -139,6 +142,7 @@ public class MapsTest extends TestCase {
for (int size = 1; size < 200; size++) {
assertWontGrow(
size,
+ new LinkedHashMap<>(),
Maps.newLinkedHashMapWithExpectedSize(size),
Maps.newLinkedHashMapWithExpectedSize(size));
}
@@ -146,7 +150,11 @@ public class MapsTest extends TestCase {
@GwtIncompatible // reflection
private static void assertWontGrow(
- int size, HashMap<Object, Object> map1, HashMap<Object, Object> map2) throws Exception {
+ int size,
+ HashMap<Object, Object> referenceMap,
+ HashMap<Object, Object> map1,
+ HashMap<Object, Object> map2)
+ throws Exception {
// Only start measuring table size after the first element inserted, to
// deal with empty-map optimization.
map1.put(0, null);
@@ -168,6 +176,16 @@ public class MapsTest extends TestCase {
assertWithMessage("table size after adding " + size + " elements")
.that(bucketsOf(map1))
.isEqualTo(initialBuckets);
+
+ // Ensure that referenceMap, which doesn't use WithExpectedSize, ends up with the same table
+ // size as the other two maps. If it ended up with a smaller size that would imply that we
+ // computed the wrong initial capacity.
+ for (int i = 0; i < size; i++) {
+ referenceMap.put(i, null);
+ }
+ assertWithMessage("table size after adding " + size + " elements")
+ .that(initialBuckets)
+ .isAtMost(bucketsOf(referenceMap));
}
@GwtIncompatible // reflection
@@ -1308,23 +1326,23 @@ public class MapsTest extends TestCase {
assertEquals(ImmutableSet.of(1, 2, 3), sync.inverse().keySet());
}
- private static final Predicate<String> NOT_LENGTH_3 =
- new Predicate<String>() {
+ static final Predicate<@Nullable String> NOT_LENGTH_3 =
+ new Predicate<@Nullable String>() {
@Override
- public boolean apply(String input) {
+ public boolean apply(@Nullable String input) {
return input == null || input.length() != 3;
}
};
- private static final Predicate<Integer> EVEN =
- new Predicate<Integer>() {
+ static final Predicate<@Nullable Integer> EVEN =
+ new Predicate<@Nullable Integer>() {
@Override
- public boolean apply(Integer input) {
+ public boolean apply(@Nullable Integer input) {
return input == null || input % 2 == 0;
}
};
- private static final Predicate<Entry<String, Integer>> CORRECT_LENGTH =
+ static final Predicate<Entry<String, Integer>> CORRECT_LENGTH =
new Predicate<Entry<String, Integer>>() {
@Override
public boolean apply(Entry<String, Integer> input) {
@@ -1332,7 +1350,7 @@ public class MapsTest extends TestCase {
}
};
- private static final Function<Integer, Double> SQRT_FUNCTION =
+ static final Function<Integer, Double> SQRT_FUNCTION =
new Function<Integer, Double>() {
@Override
public Double apply(Integer in) {
@@ -1340,233 +1358,6 @@ public class MapsTest extends TestCase {
}
};
- public static class FilteredMapTest extends TestCase {
- Map<String, Integer> createUnfiltered() {
- return Maps.newHashMap();
- }
-
- public void testFilteredKeysIllegalPut() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
- filtered.put("a", 1);
- filtered.put("b", 2);
- assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
-
- try {
- filtered.put("yyy", 3);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
-
- public void testFilteredKeysIllegalPutAll() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
- filtered.put("a", 1);
- filtered.put("b", 2);
- assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
-
- try {
- filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5));
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
- }
-
- public void testFilteredKeysFilteredReflectsBackingChanges() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
- unfiltered.put("two", 2);
- unfiltered.put("three", 3);
- unfiltered.put("four", 4);
- assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered);
- assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered);
-
- unfiltered.remove("three");
- assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered);
- assertEquals(ImmutableMap.of("four", 4), filtered);
-
- unfiltered.clear();
- assertEquals(ImmutableMap.of(), unfiltered);
- assertEquals(ImmutableMap.of(), filtered);
- }
-
- public void testFilteredValuesIllegalPut() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- filtered.put("a", 2);
- unfiltered.put("b", 4);
- unfiltered.put("c", 5);
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
-
- try {
- filtered.put("yyy", 3);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
- }
-
- public void testFilteredValuesIllegalPutAll() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- filtered.put("a", 2);
- unfiltered.put("b", 4);
- unfiltered.put("c", 5);
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
-
- try {
- filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6));
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
- }
-
- public void testFilteredValuesIllegalSetValue() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- filtered.put("a", 2);
- filtered.put("b", 4);
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
-
- Entry<String, Integer> entry = filtered.entrySet().iterator().next();
- try {
- entry.setValue(5);
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
- }
-
- public void testFilteredValuesClear() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("one", 1);
- unfiltered.put("two", 2);
- unfiltered.put("three", 3);
- unfiltered.put("four", 4);
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- assertEquals(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), unfiltered);
- assertEquals(ImmutableMap.of("two", 2, "four", 4), filtered);
-
- filtered.clear();
- assertEquals(ImmutableMap.of("one", 1, "three", 3), unfiltered);
- assertTrue(filtered.isEmpty());
- }
-
- public void testFilteredEntriesIllegalPut() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
-
- filtered.put("chicken", 7);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
-
- try {
- filtered.put("cow", 7);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
- }
-
- public void testFilteredEntriesIllegalPutAll() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
-
- filtered.put("chicken", 7);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
-
- try {
- filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7));
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
- }
-
- public void testFilteredEntriesObjectPredicate() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Predicate<Object> predicate = Predicates.alwaysFalse();
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
- assertTrue(filtered.isEmpty());
- }
-
- public void testFilteredEntriesWildCardEntryPredicate() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Predicate<Entry<?, ?>> predicate =
- new Predicate<Entry<?, ?>>() {
- @Override
- public boolean apply(Entry<?, ?> input) {
- return "cat".equals(input.getKey()) || Integer.valueOf(2) == input.getValue();
- }
- };
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
- assertEquals(ImmutableMap.of("cat", 3, "dog", 2), filtered);
- }
- }
-
- public static class FilteredSortedMapTest extends FilteredMapTest {
- @Override
- SortedMap<String, Integer> createUnfiltered() {
- return Maps.newTreeMap();
- }
-
- public void testFirstAndLastKeyFilteredMap() {
- SortedMap<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("apple", 2);
- unfiltered.put("banana", 6);
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 5);
-
- SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
- assertEquals("banana", filtered.firstKey());
- assertEquals("cat", filtered.lastKey());
- }
-
- public void testHeadSubTailMap_FilteredMap() {
- SortedMap<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("apple", 2);
- unfiltered.put("banana", 6);
- unfiltered.put("cat", 4);
- unfiltered.put("dog", 3);
- SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
-
- assertEquals(ImmutableMap.of("banana", 6), filtered.headMap("dog"));
- assertEquals(ImmutableMap.of(), filtered.headMap("banana"));
- assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.headMap("emu"));
-
- assertEquals(ImmutableMap.of("banana", 6), filtered.subMap("banana", "dog"));
- assertEquals(ImmutableMap.of("dog", 3), filtered.subMap("cat", "emu"));
-
- assertEquals(ImmutableMap.of("dog", 3), filtered.tailMap("cat"));
- assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.tailMap("banana"));
- }
- }
-
- public static class FilteredBiMapTest extends FilteredMapTest {
- @Override
- BiMap<String, Integer> createUnfiltered() {
- return HashBiMap.create();
- }
- }
-
public void testTransformValues() {
Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
Map<String, Double> transformed = transformValues(map, SQRT_FUNCTION);
diff --git a/android/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java b/android/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java
index b4382dbca..a88ff9cd1 100644
--- a/android/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java
@@ -25,7 +25,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Maps#transformValues}.
@@ -156,7 +156,7 @@ public class MapsTransformValuesTest extends MapInterfaceTest<String, String> {
underlying,
new Function<String, Boolean>() {
@Override
- public Boolean apply(@CheckForNull String from) {
+ public Boolean apply(@Nullable String from) {
return from == null;
}
});
@@ -264,22 +264,22 @@ public class MapsTransformValuesTest extends MapInterfaceTest<String, String> {
}
public void testTransformEntrySetContains() {
- Map<String, Boolean> underlying = Maps.newHashMap();
+ Map<@Nullable String, @Nullable Boolean> underlying = Maps.newHashMap();
underlying.put("a", null);
underlying.put("b", true);
underlying.put(null, true);
- Map<String, Boolean> map =
+ Map<@Nullable String, @Nullable Boolean> map =
Maps.transformValues(
underlying,
- new Function<Boolean, Boolean>() {
+ new Function<@Nullable Boolean, @Nullable Boolean>() {
@Override
- public Boolean apply(@CheckForNull Boolean from) {
+ public @Nullable Boolean apply(@Nullable Boolean from) {
return (from == null) ? true : null;
}
});
- Set<Entry<String, Boolean>> entries = map.entrySet();
+ Set<Entry<@Nullable String, @Nullable Boolean>> entries = map.entrySet();
assertTrue(entries.contains(Maps.immutableEntry("a", true)));
assertTrue(entries.contains(Maps.immutableEntry("b", (Boolean) null)));
assertTrue(entries.contains(Maps.immutableEntry((String) null, (Boolean) null)));
diff --git a/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java b/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
index 10739513f..7411beca4 100644
--- a/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
@@ -25,7 +25,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Maps#transformValues} when the backing map's views have iterators that don't
@@ -232,7 +232,7 @@ public class MapsTransformValuesUnmodifiableIteratorTest extends MapInterfaceTes
underlying,
new Function<String, Boolean>() {
@Override
- public Boolean apply(@CheckForNull String from) {
+ public Boolean apply(@Nullable String from) {
return from == null;
}
});
@@ -340,22 +340,22 @@ public class MapsTransformValuesUnmodifiableIteratorTest extends MapInterfaceTes
}
public void testTransformEntrySetContains() {
- Map<String, Boolean> underlying = Maps.newHashMap();
+ Map<@Nullable String, @Nullable Boolean> underlying = Maps.newHashMap();
underlying.put("a", null);
underlying.put("b", true);
underlying.put(null, true);
- Map<String, Boolean> map =
+ Map<@Nullable String, @Nullable Boolean> map =
Maps.transformValues(
underlying,
- new Function<Boolean, Boolean>() {
+ new Function<@Nullable Boolean, @Nullable Boolean>() {
@Override
- public Boolean apply(@CheckForNull Boolean from) {
+ public @Nullable Boolean apply(@Nullable Boolean from) {
return (from == null) ? true : null;
}
});
- Set<Entry<String, Boolean>> entries = map.entrySet();
+ Set<Entry<@Nullable String, @Nullable Boolean>> entries = map.entrySet();
assertTrue(entries.contains(Maps.immutableEntry("a", true)));
assertTrue(entries.contains(Maps.immutableEntry("b", (Boolean) null)));
assertTrue(entries.contains(Maps.immutableEntry((String) null, (Boolean) null)));
diff --git a/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java b/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
index 5471e3609..9a39e192d 100644
--- a/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
@@ -276,7 +276,7 @@ public class MinMaxPriorityQueueTest extends TestCase {
public void testRemove() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(1, 2, 3, 4, 47, 1, 5, 3, 0));
- assertTrue("Heap is not intact initally", mmHeap.isIntact());
+ assertTrue("Heap is not intact initially", mmHeap.isIntact());
assertEquals(9, mmHeap.size());
mmHeap.remove(5);
assertEquals(8, mmHeap.size());
diff --git a/android/guava-tests/test/com/google/common/collect/MultimapsTest.java b/android/guava-tests/test/com/google/common/collect/MultimapsTest.java
index 02ea574bb..1894c2613 100644
--- a/android/guava-tests/test/com/google/common/collect/MultimapsTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MultimapsTest.java
@@ -55,8 +55,8 @@ import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@code Multimaps}.
@@ -267,8 +267,8 @@ public class MultimapsTest extends TestCase {
private static void checkUnmodifiableMultimap(
Multimap<String, Integer> multimap,
boolean permitsDuplicates,
- @CheckForNull String nullKey,
- @CheckForNull Integer nullValue) {
+ @Nullable String nullKey,
+ @Nullable Integer nullValue) {
Multimap<String, Integer> unmodifiable =
prepareUnmodifiableTests(multimap, permitsDuplicates, nullKey, nullValue);
@@ -297,8 +297,8 @@ public class MultimapsTest extends TestCase {
private static Multimap<String, Integer> prepareUnmodifiableTests(
Multimap<String, Integer> multimap,
boolean permitsDuplicates,
- @CheckForNull String nullKey,
- @CheckForNull Integer nullValue) {
+ @Nullable String nullKey,
+ @Nullable Integer nullValue) {
multimap.clear();
multimap.put("foo", 1);
multimap.put("foo", 2);
diff --git a/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java b/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java
index bef27b9b2..870490e5f 100644
--- a/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java
+++ b/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset.Entry;
import java.util.Collections;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Multisets#immutableEntry}.
@@ -28,7 +29,7 @@ import junit.framework.TestCase;
*/
@GwtCompatible
public class MultisetsImmutableEntryTest extends TestCase {
- private static final String NE = null;
+ private static final @Nullable String NE = null;
private static <E> Entry<E> entry(final E element, final int count) {
return Multisets.immutableEntry(element, count);
diff --git a/android/guava-tests/test/com/google/common/collect/OrderingTest.java b/android/guava-tests/test/com/google/common/collect/OrderingTest.java
index 7c4acc943..a98379986 100644
--- a/android/guava-tests/test/com/google/common/collect/OrderingTest.java
+++ b/android/guava-tests/test/com/google/common/collect/OrderingTest.java
@@ -40,8 +40,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.RandomAccess;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@code Ordering}.
@@ -833,7 +833,7 @@ public class OrderingTest extends TestCase {
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return other instanceof NumberOrdering;
}
@@ -1030,7 +1030,7 @@ public class OrderingTest extends TestCase {
scenario.ordering.onResultOf(
new Function<Integer, T>() {
@Override
- public T apply(@CheckForNull Integer from) {
+ public T apply(@Nullable Integer from) {
return scenario.strictlyOrderedList.get(from);
}
});
diff --git a/android/guava-tests/test/com/google/common/collect/QueuesTest.java b/android/guava-tests/test/com/google/common/collect/QueuesTest.java
index 819700e4c..e2c3485f9 100644
--- a/android/guava-tests/test/com/google/common/collect/QueuesTest.java
+++ b/android/guava-tests/test/com/google/common/collect/QueuesTest.java
@@ -40,13 +40,13 @@ import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Queues}.
*
* @author Dimitris Andreou
*/
-
public class QueuesTest extends TestCase {
/*
* All the following tests relate to BlockingQueue methods in Queues.
@@ -221,8 +221,9 @@ public class QueuesTest extends TestCase {
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError =
threadPool.submit(
- new Callable<Void>() {
- public Void call() throws InterruptedException {
+ new Callable<@Nullable Void>() {
+ @Override
+ public @Nullable Void call() throws InterruptedException {
new Producer(q, 50).call();
new Interrupter(mainThread).run();
new Producer(q, 50).call();
@@ -303,7 +304,7 @@ public class QueuesTest extends TestCase {
}
}
- private static class Producer implements Callable<Void> {
+ private static class Producer implements Callable<@Nullable Void> {
final BlockingQueue<Object> q;
final int elements;
final CountDownLatch beganProducing = new CountDownLatch(1);
@@ -315,7 +316,7 @@ public class QueuesTest extends TestCase {
}
@Override
- public Void call() throws InterruptedException {
+ public @Nullable Void call() throws InterruptedException {
try {
beganProducing.countDown();
for (int i = 0; i < elements; i++) {
diff --git a/android/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..4035d6955
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class RegularImmutableMapMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ return ImmutableMap.of();
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableMap.of("one", 1, "two", 2, "three", 3);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java
new file mode 100644
index 000000000..5bbf247b8
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java
@@ -0,0 +1,47 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.testing.SampleElements.Unhashables;
+import com.google.common.collect.testing.UnhashableObject;
+import java.util.Map;
+
+@GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
+public class RegularImmutableMapWithUnhashableValuesMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<Integer, UnhashableObject> {
+ @Override
+ protected Map<Integer, UnhashableObject> makeEmptyMap() {
+ return ImmutableMap.of();
+ }
+
+ @Override
+ protected Map<Integer, UnhashableObject> makePopulatedMap() {
+ Unhashables unhashables = new Unhashables();
+ return ImmutableMap.of(0, unhashables.e0(), 1, unhashables.e1(), 2, unhashables.e2());
+ }
+
+ @Override
+ protected Integer getKeyNotInPopulatedMap() {
+ return 3;
+ }
+
+ @Override
+ protected UnhashableObject getValueNotInPopulatedMap() {
+ return new Unhashables().e3();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..d825eac5e
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class RegularImmutableSortedMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makeEmptyMap() {
+ return ImmutableSortedMap.of();
+ }
+
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..6eef9f30b
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.testing.SerializableTester;
+import java.util.Map;
+
+@GwtIncompatible // SerializableTester
+public class ReserializedImmutableMapMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return SerializableTester.reserialize(ImmutableMap.of("one", 1, "two", 2, "three", 3));
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..1011cfef3
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2009 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.GwtIncompatible;
+import com.google.common.testing.SerializableTester;
+import java.util.SortedMap;
+
+@GwtIncompatible // SerializableTester
+public class ReserializedImmutableSortedMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return SerializableTester.reserialize(ImmutableSortedMap.of("one", 1, "two", 2, "three", 3));
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java b/android/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java
new file mode 100644
index 000000000..a550f0487
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredSetTest;
+import java.util.Set;
+
+public final class SetsFilterHashSetTest extends AbstractFilteredSetTest<Set<Integer>> {
+ @Override
+ Set<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Sets.newHashSet(contents);
+ }
+
+ @Override
+ Set<Integer> filter(Set<Integer> elements, Predicate<? super Integer> predicate) {
+ return Sets.filter(elements, predicate);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java b/android/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java
new file mode 100644
index 000000000..350c09150
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredNavigableSetTest;
+import java.util.NavigableSet;
+
+public final class SetsFilterNavigableSetTest extends AbstractFilteredNavigableSetTest {
+ @Override
+ NavigableSet<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Sets.newTreeSet(contents);
+ }
+
+ @Override
+ NavigableSet<Integer> filter(
+ NavigableSet<Integer> elements, Predicate<? super Integer> predicate) {
+ return Sets.filter(elements, predicate);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java b/android/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java
new file mode 100644
index 000000000..0529bead6
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredSortedSetTest;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+public final class SetsFilterSortedSetTest
+ extends AbstractFilteredSortedSetTest<SortedSet<Integer>> {
+ @Override
+ SortedSet<Integer> createUnfiltered(Iterable<Integer> contents) {
+ final TreeSet<Integer> result = Sets.newTreeSet(contents);
+ // we have to make the result not Navigable
+ return new ForwardingSortedSet<Integer>() {
+ @Override
+ protected SortedSet<Integer> delegate() {
+ return result;
+ }
+ };
+ }
+
+ @Override
+ SortedSet<Integer> filter(SortedSet<Integer> elements, Predicate<? super Integer> predicate) {
+ return Sets.filter(elements, predicate);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SetsTest.java b/android/guava-tests/test/com/google/common/collect/SetsTest.java
index d7799cec0..82c40b09f 100644
--- a/android/guava-tests/test/com/google/common/collect/SetsTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SetsTest.java
@@ -73,10 +73,10 @@ import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArraySet;
-import javax.annotation.CheckForNull;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@code Sets}.
@@ -578,48 +578,56 @@ public class SetsTest extends TestCase {
verifySetContents(set, SOME_COLLECTION);
}
+ @GwtIncompatible // complementOf
public void testComplementOfEnumSet() {
Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEnumSetWithType() {
Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfRegularSet() {
Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfRegularSetWithType() {
Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEmptySet() {
Set<SomeEnum> noUnits = Collections.emptySet();
EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits, SomeEnum.class);
verifySetContents(EnumSet.allOf(SomeEnum.class), allUnits);
}
+ @GwtIncompatible // complementOf
public void testComplementOfFullSet() {
Set<SomeEnum> allUnits = Sets.newHashSet(SomeEnum.values());
EnumSet<SomeEnum> noUnits = Sets.complementOf(allUnits, SomeEnum.class);
verifySetContents(noUnits, EnumSet.noneOf(SomeEnum.class));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEmptyEnumSetWithoutType() {
Set<SomeEnum> noUnits = EnumSet.noneOf(SomeEnum.class);
EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits);
verifySetContents(allUnits, EnumSet.allOf(SomeEnum.class));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEmptySetWithoutTypeDoesntWork() {
Set<SomeEnum> set = Collections.emptySet();
try {
@@ -1077,7 +1085,7 @@ public class SetsTest extends TestCase {
* same as the given comparator.
*/
private static <E> void verifySortedSetContents(
- SortedSet<E> set, Iterable<E> iterable, @CheckForNull Comparator<E> comparator) {
+ SortedSet<E> set, Iterable<E> iterable, @Nullable Comparator<E> comparator) {
assertSame(comparator, set.comparator());
verifySetContents(set, iterable);
}
@@ -1113,7 +1121,7 @@ public class SetsTest extends TestCase {
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
if (other == null) {
return false;
} else if (other instanceof Base) {
diff --git a/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java b/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java
index 02ab44b9f..04f4fe67c 100644
--- a/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java
@@ -28,10 +28,10 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
-import javax.annotation.CheckForNull;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractMultiset}.
@@ -106,7 +106,7 @@ public class SimpleAbstractMultisetTest extends TestCase {
}
@Override
- public int count(@CheckForNull Object element) {
+ public int count(@Nullable Object element) {
for (Entry<E> entry : entrySet()) {
if (Objects.equal(entry.getElement(), element)) {
return entry.getCount();
@@ -116,7 +116,7 @@ public class SimpleAbstractMultisetTest extends TestCase {
}
@Override
- public int add(@CheckForNull E element, int occurrences) {
+ public int add(@Nullable E element, int occurrences) {
checkArgument(occurrences >= 0);
Integer frequency = backingMap.get(element);
if (frequency == null) {
diff --git a/android/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..2a9197d6c
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class SingletonImmutableMapMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableMap.of("one", 1);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java
new file mode 100644
index 000000000..851e5d8c5
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.testing.SampleElements.Unhashables;
+import com.google.common.collect.testing.UnhashableObject;
+import java.util.Map;
+
+@GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
+public class SingletonImmutableMapWithUnhashableValueMapInterfaceTest
+ extends RegularImmutableMapWithUnhashableValuesMapInterfaceTest {
+ @Override
+ protected Map<Integer, UnhashableObject> makePopulatedMap() {
+ Unhashables unhashables = new Unhashables();
+ return ImmutableMap.of(0, unhashables.e0());
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..4cb7ca5f4
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class SingletonImmutableSortedMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("one", 1);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java
index 1e422b2b4..c5637038d 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java
@@ -29,6 +29,7 @@ import com.google.common.collect.testing.google.TestStringBiMapGenerator;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Synchronized#biMap}.
@@ -111,7 +112,7 @@ public class SynchronizedBiMapTest extends SynchronizedMapTest {
}
@Override
- public V forcePut(K key, V value) {
+ public @Nullable V forcePut(K key, V value) {
assertTrue(Thread.holdsLock(mutex));
return delegate.forcePut(key, value);
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java
index 1df6aa1bf..09f9c429b 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java
@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Synchronized#deque} and {@link Queues#synchronizedDeque}.
@@ -47,7 +48,7 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E poll() {
+ public @Nullable E poll() {
assertTrue(Thread.holdsLock(mutex));
return delegate.poll();
}
@@ -65,7 +66,7 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E peek() {
+ public @Nullable E peek() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peek();
}
@@ -186,13 +187,13 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E pollFirst() {
+ public @Nullable E pollFirst() {
assertTrue(Thread.holdsLock(mutex));
return delegate.pollFirst();
}
@Override
- public E pollLast() {
+ public @Nullable E pollLast() {
assertTrue(Thread.holdsLock(mutex));
return delegate.pollLast();
}
@@ -210,13 +211,13 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E peekFirst() {
+ public @Nullable E peekFirst() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peekFirst();
}
@Override
- public E peekLast() {
+ public @Nullable E peekLast() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peekLast();
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java
index 2e15eda32..1aeae36cc 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java
@@ -28,6 +28,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Synchronized#map}.
@@ -71,7 +72,7 @@ public class SynchronizedMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
assertTrue(Thread.holdsLock(mutex));
return super.remove(object);
}
@@ -95,13 +96,13 @@ public class SynchronizedMapTest extends TestCase {
}
@Override
- public V get(Object key) {
+ public @Nullable V get(Object key) {
assertTrue(Thread.holdsLock(mutex));
return super.get(key);
}
@Override
- public V put(K key, V value) {
+ public @Nullable V put(K key, V value) {
assertTrue(Thread.holdsLock(mutex));
return super.put(key, value);
}
@@ -131,7 +132,7 @@ public class SynchronizedMapTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(obj);
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java
index 3c4f1375a..6475dad8f 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java
@@ -30,10 +30,10 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.RandomAccess;
import java.util.Set;
-import javax.annotation.CheckForNull;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Synchronized#multimap}.
@@ -89,7 +89,7 @@ public class SynchronizedMultimapTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object o) {
+ public boolean equals(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(o);
}
@@ -113,25 +113,25 @@ public class SynchronizedMultimapTest extends TestCase {
}
@Override
- public boolean containsKey(@CheckForNull Object key) {
+ public boolean containsKey(@Nullable Object key) {
assertTrue(Thread.holdsLock(mutex));
return super.containsKey(key);
}
@Override
- public boolean containsValue(@CheckForNull Object value) {
+ public boolean containsValue(@Nullable Object value) {
assertTrue(Thread.holdsLock(mutex));
return super.containsValue(value);
}
@Override
- public boolean containsEntry(@CheckForNull Object key, @CheckForNull Object value) {
+ public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
assertTrue(Thread.holdsLock(mutex));
return super.containsEntry(key, value);
}
@Override
- public Set<V> get(@CheckForNull K key) {
+ public Set<V> get(@Nullable K key) {
assertTrue(Thread.holdsLock(mutex));
/* TODO: verify that the Collection is also synchronized? */
return super.get(key);
@@ -144,7 +144,7 @@ public class SynchronizedMultimapTest extends TestCase {
}
@Override
- public boolean putAll(@CheckForNull K key, Iterable<? extends V> values) {
+ public boolean putAll(@Nullable K key, Iterable<? extends V> values) {
assertTrue(Thread.holdsLock(mutex));
return super.putAll(key, values);
}
@@ -156,19 +156,19 @@ public class SynchronizedMultimapTest extends TestCase {
}
@Override
- public Set<V> replaceValues(@CheckForNull K key, Iterable<? extends V> values) {
+ public Set<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
assertTrue(Thread.holdsLock(mutex));
return super.replaceValues(key, values);
}
@Override
- public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
+ public boolean remove(@Nullable Object key, @Nullable Object value) {
assertTrue(Thread.holdsLock(mutex));
return super.remove(key, value);
}
@Override
- public Set<V> removeAll(@CheckForNull Object key) {
+ public Set<V> removeAll(@Nullable Object key) {
assertTrue(Thread.holdsLock(mutex));
return super.removeAll(key);
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java
index 41b597aac..ad9fd230d 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java
@@ -33,6 +33,7 @@ import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.SortedMap;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Maps#synchronizedNavigableMap(NavigableMap)}.
@@ -65,7 +66,7 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(object);
}
@@ -110,13 +111,13 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> ceilingEntry(K key) {
+ public @Nullable Entry<K, V> ceilingEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceilingEntry(key);
}
@Override
- public K ceilingKey(K key) {
+ public @Nullable K ceilingKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceilingKey(key);
}
@@ -134,19 +135,19 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> firstEntry() {
+ public @Nullable Entry<K, V> firstEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().firstEntry();
}
@Override
- public Entry<K, V> floorEntry(K key) {
+ public @Nullable Entry<K, V> floorEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().floorEntry(key);
}
@Override
- public K floorKey(K key) {
+ public @Nullable K floorKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().floorKey(key);
}
@@ -163,31 +164,31 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> higherEntry(K key) {
+ public @Nullable Entry<K, V> higherEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().higherEntry(key);
}
@Override
- public K higherKey(K key) {
+ public @Nullable K higherKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().higherKey(key);
}
@Override
- public Entry<K, V> lastEntry() {
+ public @Nullable Entry<K, V> lastEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().lastEntry();
}
@Override
- public Entry<K, V> lowerEntry(K key) {
+ public @Nullable Entry<K, V> lowerEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().lowerEntry(key);
}
@Override
- public K lowerKey(K key) {
+ public @Nullable K lowerKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().lowerKey(key);
}
@@ -199,13 +200,13 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> pollFirstEntry() {
+ public @Nullable Entry<K, V> pollFirstEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollFirstEntry();
}
@Override
- public Entry<K, V> pollLastEntry() {
+ public @Nullable Entry<K, V> pollLastEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollLastEntry();
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java
index 8638b0d17..572bea44e 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java
@@ -32,6 +32,7 @@ import java.util.SortedSet;
import java.util.TreeSet;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Sets#synchronizedNavigableSet(NavigableSet)}.
@@ -51,7 +52,7 @@ public class SynchronizedNavigableSetTest extends TestCase {
static class TestSet<E> extends SynchronizedSetTest.TestSet<E> implements NavigableSet<E> {
- TestSet(NavigableSet<E> delegate, Object mutex) {
+ TestSet(NavigableSet<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@@ -61,7 +62,7 @@ public class SynchronizedNavigableSetTest extends TestCase {
}
@Override
- public E ceiling(E e) {
+ public @Nullable E ceiling(E e) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceiling(e);
}
@@ -78,7 +79,7 @@ public class SynchronizedNavigableSetTest extends TestCase {
}
@Override
- public E floor(E e) {
+ public @Nullable E floor(E e) {
assertTrue(Thread.holdsLock(mutex));
return delegate().floor(e);
}
@@ -95,24 +96,24 @@ public class SynchronizedNavigableSetTest extends TestCase {
}
@Override
- public E higher(E e) {
+ public @Nullable E higher(E e) {
assertTrue(Thread.holdsLock(mutex));
return delegate().higher(e);
}
@Override
- public E lower(E e) {
+ public @Nullable E lower(E e) {
return delegate().lower(e);
}
@Override
- public E pollFirst() {
+ public @Nullable E pollFirst() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollFirst();
}
@Override
- public E pollLast() {
+ public @Nullable E pollLast() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollLast();
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java
index f7b04fe2e..b677c281b 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java
@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Synchronized#queue} and {@link Queues#synchronizedQueue}.
@@ -47,7 +48,7 @@ public class SynchronizedQueueTest extends TestCase {
}
@Override
- public E poll() {
+ public @Nullable E poll() {
assertTrue(Thread.holdsLock(mutex));
return delegate.poll();
}
@@ -65,7 +66,7 @@ public class SynchronizedQueueTest extends TestCase {
}
@Override
- public E peek() {
+ public @Nullable E peek() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peek();
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java
index 5ffcf5d54..0e85a24bb 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java
@@ -27,9 +27,9 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
-import javax.annotation.CheckForNull;
import junit.framework.Test;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Synchronized#set}.
@@ -40,6 +40,9 @@ public class SynchronizedSetTest extends TestCase {
public static final Object MUTEX = new Integer(1); // something Serializable
+ // TODO(cpovirk): Resolve difference between branches in their choice of mutex:
+ // - The mainline uses `null` (even since the change in cl/99720576 was integrated).
+ // - The backport continued to use MUTEX.
public static Test suite() {
return SetTestSuiteBuilder.using(
new TestStringSetGenerator() {
@@ -82,7 +85,7 @@ public class SynchronizedSetTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object o) {
+ public boolean equals(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(o);
}
@@ -94,7 +97,7 @@ public class SynchronizedSetTest extends TestCase {
}
@Override
- public boolean add(@CheckForNull E o) {
+ public boolean add(@Nullable E o) {
assertTrue(Thread.holdsLock(mutex));
return super.add(o);
}
@@ -112,7 +115,7 @@ public class SynchronizedSetTest extends TestCase {
}
@Override
- public boolean contains(@CheckForNull Object o) {
+ public boolean contains(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.contains(o);
}
@@ -132,7 +135,7 @@ public class SynchronizedSetTest extends TestCase {
/* Don't test iterator(); it may or may not hold the mutex. */
@Override
- public boolean remove(@CheckForNull Object o) {
+ public boolean remove(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.remove(o);
}
diff --git a/android/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java b/android/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java
index e1b454436..216f32b2e 100644
--- a/android/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java
+++ b/android/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java
@@ -20,7 +20,7 @@ import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
public class SynchronizedTableTest extends AbstractTableTest {
private static final class TestTable<R, C, V> implements Table<R, C, V>, Serializable {
@@ -34,7 +34,7 @@ public class SynchronizedTableTest extends AbstractTableTest {
}
@Override
- public boolean equals(@CheckForNull Object o) {
+ public boolean equals(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return delegate.equals(o);
}
@@ -58,7 +58,7 @@ public class SynchronizedTableTest extends AbstractTableTest {
}
@Override
- public boolean containsValue(@CheckForNull Object value) {
+ public boolean containsValue(@Nullable Object value) {
assertTrue(Thread.holdsLock(mutex));
return delegate.containsValue(value);
}
@@ -119,13 +119,13 @@ public class SynchronizedTableTest extends AbstractTableTest {
}
@Override
- public V get(Object rowKey, Object columnKey) {
+ public @Nullable V get(Object rowKey, Object columnKey) {
assertTrue(Thread.holdsLock(mutex));
return delegate.get(rowKey, columnKey);
}
@Override
- public V put(R rowKey, C columnKey, V value) {
+ public @Nullable V put(R rowKey, C columnKey, V value) {
assertTrue(Thread.holdsLock(mutex));
return delegate.put(rowKey, columnKey, value);
}
@@ -137,7 +137,7 @@ public class SynchronizedTableTest extends AbstractTableTest {
}
@Override
- public V remove(Object rowKey, Object columnKey) {
+ public @Nullable V remove(Object rowKey, Object columnKey) {
assertTrue(Thread.holdsLock(mutex));
return delegate.remove(rowKey, columnKey);
}
diff --git a/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java b/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java
index 7c944441a..18ad54939 100644
--- a/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java
+++ b/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java
@@ -35,17 +35,16 @@ import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.SortedMap;
import java.util.SortedSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Collection tests for {@link Table} implementations.
@@ -78,35 +77,6 @@ public class TableCollectionTest extends TestCase {
@GwtIncompatible // suite
public static Test suite() {
TestSuite suite = new TestSuite();
- suite.addTestSuite(ArrayRowTests.class);
- suite.addTestSuite(HashRowTests.class);
- suite.addTestSuite(TreeRowTests.class);
- suite.addTestSuite(TransposeRowTests.class);
- suite.addTestSuite(TransformValueRowTests.class);
- suite.addTestSuite(UnmodifiableHashRowTests.class);
- suite.addTestSuite(UnmodifiableTreeRowTests.class);
- suite.addTestSuite(ArrayColumnTests.class);
- suite.addTestSuite(HashColumnTests.class);
- suite.addTestSuite(TreeColumnTests.class);
- suite.addTestSuite(TransposeColumnTests.class);
- suite.addTestSuite(TransformValueColumnTests.class);
- suite.addTestSuite(UnmodifiableHashColumnTests.class);
- suite.addTestSuite(UnmodifiableTreeColumnTests.class);
- suite.addTestSuite(ArrayRowMapTests.class);
- suite.addTestSuite(HashRowMapTests.class);
- suite.addTestSuite(TreeRowMapTests.class);
- suite.addTestSuite(TreeRowMapHeadMapTests.class);
- suite.addTestSuite(TreeRowMapTailMapTests.class);
- suite.addTestSuite(TreeRowMapSubMapTests.class);
- suite.addTestSuite(TransformValueRowMapTests.class);
- suite.addTestSuite(UnmodifiableHashRowMapTests.class);
- suite.addTestSuite(UnmodifiableTreeRowMapTests.class);
- suite.addTestSuite(ArrayColumnMapTests.class);
- suite.addTestSuite(HashColumnMapTests.class);
- suite.addTestSuite(TreeColumnMapTests.class);
- suite.addTestSuite(TransformValueColumnMapTests.class);
- suite.addTestSuite(UnmodifiableHashColumnMapTests.class);
- suite.addTestSuite(UnmodifiableTreeColumnMapTests.class);
// Not testing rowKeySet() or columnKeySet() of Table.transformValues()
// since the transformation doesn't affect the row and column key sets.
@@ -770,7 +740,7 @@ public class TableCollectionTest extends TestCase {
}
}
- private abstract static class RowTests extends MapTests {
+ abstract static class RowTests extends MapTests {
RowTests(
boolean allowsNullValues,
boolean supportsPut,
@@ -798,138 +768,15 @@ public class TableCollectionTest extends TestCase {
}
}
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayRowTests extends RowTests {
- public ArrayRowTests() {
- super(true, true, false, false, false);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected Table<Character, String, Integer> makeTable() {
- return ArrayTable.create(
- Arrays.asList('a', 'b', 'c'), Arrays.asList("one", "two", "three", "four"));
- }
- }
-
- public static class HashRowTests extends RowTests {
- public HashRowTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeRowTests extends RowTests {
- public TreeRowTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TransposeRowTests extends RowTests {
- public TransposeRowTests() {
- super(false, true, true, true, false);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- Table<String, Character, Integer> original = TreeBasedTable.create();
- return Tables.transpose(original);
- }
- }
-
- private static final Function<Integer, Integer> DIVIDE_BY_2 =
- new Function<Integer, Integer>() {
+ static final Function<@Nullable Integer, @Nullable Integer> DIVIDE_BY_2 =
+ new Function<@Nullable Integer, @Nullable Integer>() {
@Override
- public Integer apply(Integer input) {
+ public @Nullable Integer apply(@Nullable Integer input) {
return (input == null) ? null : input / 2;
}
};
- public static class TransformValueRowTests extends RowTests {
- public TransformValueRowTests() {
- super(false, false, true, true, true);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- return Tables.transformValues(table, DIVIDE_BY_2);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- table.put('a', "one", 2);
- table.put('a', "two", 4);
- table.put('a', "three", 6);
- table.put('b', "four", 8);
- return Tables.transformValues(table, DIVIDE_BY_2).row('a');
- }
- }
-
- public static class UnmodifiableHashRowTests extends RowTests {
- public UnmodifiableHashRowTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- return Tables.unmodifiableTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- table.put('a', "one", 1);
- table.put('a', "two", 2);
- table.put('a', "three", 3);
- table.put('b', "four", 4);
- return Tables.unmodifiableTable(table).row('a');
- }
- }
-
- public static class UnmodifiableTreeRowTests extends RowTests {
- public UnmodifiableTreeRowTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
- table.put('a', "one", 1);
- table.put('a', "two", 2);
- table.put('a', "three", 3);
- table.put('b', "four", 4);
- return Tables.unmodifiableRowSortedTable(table).row('a');
- }
- }
-
- private abstract static class ColumnTests extends MapTests {
+ abstract static class ColumnTests extends MapTests {
ColumnTests(
boolean allowsNullValues,
boolean supportsPut,
@@ -957,129 +804,6 @@ public class TableCollectionTest extends TestCase {
}
}
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayColumnTests extends ColumnTests {
- public ArrayColumnTests() {
- super(true, true, false, false, false);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- return ArrayTable.create(
- Arrays.asList("one", "two", "three", "four"), Arrays.asList('a', 'b', 'c'));
- }
- }
-
- public static class HashColumnTests extends ColumnTests {
- public HashColumnTests() {
- super(false, true, true, true, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeColumnTests extends ColumnTests {
- public TreeColumnTests() {
- super(false, true, true, true, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TransposeColumnTests extends ColumnTests {
- public TransposeColumnTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- Table<Character, String, Integer> original = TreeBasedTable.create();
- return Tables.transpose(original);
- }
- }
-
- public static class TransformValueColumnTests extends ColumnTests {
- public TransformValueColumnTests() {
- super(false, false, true, true, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- return Tables.transformValues(table, DIVIDE_BY_2);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- table.put("one", 'a', 1);
- table.put("two", 'a', 2);
- table.put("three", 'a', 3);
- table.put("four", 'b', 4);
- return Tables.transformValues(table, DIVIDE_BY_2).column('a');
- }
- }
-
- public static class UnmodifiableHashColumnTests extends ColumnTests {
- public UnmodifiableHashColumnTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- return Tables.unmodifiableTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- table.put("one", 'a', 1);
- table.put("two", 'a', 2);
- table.put("three", 'a', 3);
- table.put("four", 'b', 4);
- return Tables.unmodifiableTable(table).column('a');
- }
- }
-
- public static class UnmodifiableTreeColumnTests extends ColumnTests {
- public UnmodifiableTreeColumnTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
- table.put("one", 'a', 1);
- table.put("two", 'a', 2);
- table.put("three", 'a', 3);
- table.put("four", 'b', 4);
- return Tables.unmodifiableRowSortedTable(table).column('a');
- }
- }
-
private abstract static class MapMapTests
extends MapInterfaceTest<String, Map<Integer, Character>> {
@@ -1136,7 +860,7 @@ public class TableCollectionTest extends TestCase {
}
}
- private abstract static class RowMapTests extends MapMapTests {
+ abstract static class RowMapTests extends MapMapTests {
RowMapTests(
boolean allowsNullValues,
boolean supportsRemove,
@@ -1166,208 +890,15 @@ public class TableCollectionTest extends TestCase {
}
}
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayRowMapTests extends RowMapTests {
- public ArrayRowMapTests() {
- super(true, false, false, false);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- return ArrayTable.create(Arrays.asList("foo", "bar", "dog"), Arrays.asList(1, 2, 3));
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
- }
-
- public static class HashRowMapTests extends RowMapTests {
- public HashRowMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeRowMapTests extends RowMapTests {
- public TreeRowMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TreeRowMapHeadMapTests extends RowMapTests {
- public TreeRowMapHeadMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- TreeBasedTable<String, Integer, Character> makeTable() {
- TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("z", 1, 'a');
- return table;
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- TreeBasedTable<String, Integer, Character> table = makeTable();
- populateTable(table);
- return table.rowMap().headMap("x");
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- return makeTable().rowMap().headMap("x");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "z";
- }
- }
-
- public static class TreeRowMapTailMapTests extends RowMapTests {
- public TreeRowMapTailMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- TreeBasedTable<String, Integer, Character> makeTable() {
- TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("a", 1, 'a');
- return table;
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- TreeBasedTable<String, Integer, Character> table = makeTable();
- populateTable(table);
- return table.rowMap().tailMap("b");
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- return makeTable().rowMap().tailMap("b");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
- }
-
- public static class TreeRowMapSubMapTests extends RowMapTests {
- public TreeRowMapSubMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- TreeBasedTable<String, Integer, Character> makeTable() {
- TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("a", 1, 'a');
- table.put("z", 1, 'a');
- return table;
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- TreeBasedTable<String, Integer, Character> table = makeTable();
- populateTable(table);
- return table.rowMap().subMap("b", "x");
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- return makeTable().rowMap().subMap("b", "x");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "z";
- }
- }
-
- private static final Function<String, Character> FIRST_CHARACTER =
- new Function<String, Character>() {
+ static final Function<@Nullable String, @Nullable Character> FIRST_CHARACTER =
+ new Function<@Nullable String, @Nullable Character>() {
@Override
- public Character apply(String input) {
+ public @Nullable Character apply(@Nullable String input) {
return input == null ? null : input.charAt(0);
}
};
- public static class TransformValueRowMapTests extends RowMapTests {
- public TransformValueRowMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- Table<String, Integer, String> original = HashBasedTable.create();
- return Tables.transformValues(original, FIRST_CHARACTER);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<String, Integer, String> table = HashBasedTable.create();
- table.put("foo", 1, "apple");
- table.put("bar", 1, "banana");
- table.put("foo", 3, "cat");
- return Tables.transformValues(table, FIRST_CHARACTER).rowMap();
- }
- }
-
- public static class UnmodifiableHashRowMapTests extends RowMapTests {
- public UnmodifiableHashRowMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- Table<String, Integer, Character> original = HashBasedTable.create();
- return Tables.unmodifiableTable(original);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<String, Integer, Character> table = HashBasedTable.create();
- table.put("foo", 1, 'a');
- table.put("bar", 1, 'b');
- table.put("foo", 3, 'c');
- return Tables.unmodifiableTable(table).rowMap();
- }
- }
-
- public static class UnmodifiableTreeRowMapTests extends RowMapTests {
- public UnmodifiableTreeRowMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- RowSortedTable<String, Integer, Character> makeTable() {
- RowSortedTable<String, Integer, Character> original = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(original);
- }
-
- @Override
- protected SortedMap<String, Map<Integer, Character>> makePopulatedMap() {
- RowSortedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("foo", 1, 'a');
- table.put("bar", 1, 'b');
- table.put("foo", 3, 'c');
- return Tables.unmodifiableRowSortedTable(table).rowMap();
- }
- }
-
- private abstract static class ColumnMapTests extends MapMapTests {
+ abstract static class ColumnMapTests extends MapMapTests {
ColumnMapTests(
boolean allowsNullValues,
boolean supportsRemove,
@@ -1392,106 +923,4 @@ public class TableCollectionTest extends TestCase {
return makeTable().columnMap();
}
}
-
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayColumnMapTests extends ColumnMapTests {
- public ArrayColumnMapTests() {
- super(true, false, false, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- return ArrayTable.create(Arrays.asList(1, 2, 3), Arrays.asList("foo", "bar", "dog"));
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
- }
-
- public static class HashColumnMapTests extends ColumnMapTests {
- public HashColumnMapTests() {
- super(false, true, true, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeColumnMapTests extends ColumnMapTests {
- public TreeColumnMapTests() {
- super(false, true, true, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TransformValueColumnMapTests extends ColumnMapTests {
- public TransformValueColumnMapTests() {
- super(false, true, true, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- Table<Integer, String, String> original = HashBasedTable.create();
- return Tables.transformValues(original, FIRST_CHARACTER);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<Integer, String, String> table = HashBasedTable.create();
- table.put(1, "foo", "apple");
- table.put(1, "bar", "banana");
- table.put(3, "foo", "cat");
- return Tables.transformValues(table, FIRST_CHARACTER).columnMap();
- }
- }
-
- public static class UnmodifiableHashColumnMapTests extends ColumnMapTests {
- public UnmodifiableHashColumnMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- Table<Integer, String, Character> original = HashBasedTable.create();
- return Tables.unmodifiableTable(original);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<Integer, String, Character> table = HashBasedTable.create();
- table.put(1, "foo", 'a');
- table.put(1, "bar", 'b');
- table.put(3, "foo", 'c');
- return Tables.unmodifiableTable(table).columnMap();
- }
- }
-
- public static class UnmodifiableTreeColumnMapTests extends ColumnMapTests {
- public UnmodifiableTreeColumnMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- RowSortedTable<Integer, String, Character> original = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(original);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- RowSortedTable<Integer, String, Character> table = TreeBasedTable.create();
- table.put(1, "foo", 'a');
- table.put(1, "bar", 'b');
- table.put(3, "foo", 'c');
- return Tables.unmodifiableRowSortedTable(table).columnMap();
- }
- }
}
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java
new file mode 100644
index 000000000..0344b56c1
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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 static com.google.common.collect.TableCollectionTest.FIRST_CHARACTER;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesColumnMapTest extends ColumnMapTests {
+ public TablesTransformValuesColumnMapTest() {
+ super(false, true, true, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ Table<Integer, String, String> original = HashBasedTable.create();
+ return Tables.transformValues(original, FIRST_CHARACTER);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<Integer, String, String> table = HashBasedTable.create();
+ table.put(1, "foo", "apple");
+ table.put(1, "bar", "banana");
+ table.put(3, "foo", "cat");
+ return Tables.transformValues(table, FIRST_CHARACTER).columnMap();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java
new file mode 100644
index 000000000..b28f5c506
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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 static com.google.common.collect.TableCollectionTest.DIVIDE_BY_2;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesColumnTest extends ColumnTests {
+ public TablesTransformValuesColumnTest() {
+ super(false, false, true, true, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ return Tables.transformValues(table, DIVIDE_BY_2);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ table.put("one", 'a', 1);
+ table.put("two", 'a', 2);
+ table.put("three", 'a', 3);
+ table.put("four", 'b', 4);
+ return Tables.transformValues(table, DIVIDE_BY_2).column('a');
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java
new file mode 100644
index 000000000..661a23255
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesRowMapTest extends RowMapTests {
+ public TablesTransformValuesRowMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ Table<String, Integer, String> original = HashBasedTable.create();
+ return Tables.transformValues(original, TableCollectionTest.FIRST_CHARACTER);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<String, Integer, String> table = HashBasedTable.create();
+ table.put("foo", 1, "apple");
+ table.put("bar", 1, "banana");
+ table.put("foo", 3, "cat");
+ return Tables.transformValues(table, TableCollectionTest.FIRST_CHARACTER).rowMap();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java
new file mode 100644
index 000000000..71571b983
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesRowTest extends RowTests {
+ public TablesTransformValuesRowTest() {
+ super(false, false, true, true, true);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ return Tables.transformValues(table, TableCollectionTest.DIVIDE_BY_2);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ table.put('a', "one", 2);
+ table.put('a', "two", 4);
+ table.put('a', "three", 6);
+ table.put('b', "four", 8);
+ return Tables.transformValues(table, TableCollectionTest.DIVIDE_BY_2).row('a');
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java
index 6730b3f51..d6330a246 100644
--- a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java
@@ -21,6 +21,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Test cases for {@link Tables#transformValues}.
@@ -30,10 +31,10 @@ import com.google.common.base.Function;
@GwtCompatible(emulated = true)
public class TablesTransformValuesTest extends AbstractTableTest {
- private static final Function<String, Character> FIRST_CHARACTER =
- new Function<String, Character>() {
+ private static final Function<@Nullable String, @Nullable Character> FIRST_CHARACTER =
+ new Function<@Nullable String, @Nullable Character>() {
@Override
- public Character apply(String input) {
+ public @Nullable Character apply(@Nullable String input) {
return input == null ? null : input.charAt(0);
}
};
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java
new file mode 100644
index 000000000..142dbc7cf
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java
@@ -0,0 +1,33 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+
+@GwtCompatible
+public class TablesTransposeColumnTest extends ColumnTests {
+ public TablesTransposeColumnTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ Table<Character, String, Integer> original = TreeBasedTable.create();
+ return Tables.transpose(original);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java
new file mode 100644
index 000000000..03caae1de
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java
@@ -0,0 +1,33 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+
+@GwtCompatible
+public class TablesTransposeRowTest extends RowTests {
+ public TablesTransposeRowTest() {
+ super(false, true, true, true, false);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ Table<String, Character, Integer> original = TreeBasedTable.create();
+ return Tables.transpose(original);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java
new file mode 100644
index 000000000..b5c92c8e7
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+
+@GwtCompatible
+public class TreeBasedTableColumnMapTest extends ColumnMapTests {
+ public TreeBasedTableColumnMapTest() {
+ super(false, true, true, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java
new file mode 100644
index 000000000..b90f46b4b
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+
+@GwtCompatible
+public class TreeBasedTableColumnTest extends ColumnTests {
+ public TreeBasedTableColumnTest() {
+ super(false, true, true, true, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java
new file mode 100644
index 000000000..05bfc4133
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TreeBasedTableRowMapHeadMapTest extends RowMapTests {
+ public TreeBasedTableRowMapHeadMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ TreeBasedTable<String, Integer, Character> makeTable() {
+ TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("z", 1, 'a');
+ return table;
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ TreeBasedTable<String, Integer, Character> table = makeTable();
+ populateTable(table);
+ return table.rowMap().headMap("x");
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ return makeTable().rowMap().headMap("x");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "z";
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java
new file mode 100644
index 000000000..dd8aec3aa
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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 com.google.common.collect.testing.SortedMapInterfaceTest;
+import java.util.SortedMap;
+
+@GwtCompatible
+public class TreeBasedTableRowMapInterfaceTest extends SortedMapInterfaceTest<String, String> {
+ public TreeBasedTableRowMapInterfaceTest() {
+ super(false, false, true, true, true);
+ }
+
+ @Override
+ protected SortedMap<String, String> makeEmptyMap() {
+ TreeBasedTable<String, String, String> table = TreeBasedTable.create();
+ table.put("a", "b", "c");
+ table.put("c", "b", "a");
+ table.put("a", "a", "d");
+ return table.row("b");
+ }
+
+ @Override
+ protected SortedMap<String, String> makePopulatedMap() {
+ TreeBasedTable<String, String, String> table = TreeBasedTable.create();
+ table.put("a", "b", "c");
+ table.put("c", "b", "a");
+ table.put("b", "b", "x");
+ table.put("b", "c", "y");
+ table.put("b", "x", "n");
+ table.put("a", "a", "d");
+ return table.row("b");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "q";
+ }
+
+ @Override
+ protected String getValueNotInPopulatedMap() {
+ return "p";
+ }
+
+ public void testClearSubMapOfRowMap() {
+ TreeBasedTable<String, String, String> table = TreeBasedTable.create();
+ table.put("a", "b", "c");
+ table.put("c", "b", "a");
+ table.put("b", "b", "x");
+ table.put("b", "c", "y");
+ table.put("b", "x", "n");
+ table.put("a", "a", "d");
+ table.row("b").subMap("c", "x").clear();
+ assertEquals(table.row("b"), ImmutableMap.of("b", "x", "x", "n"));
+ table.row("b").subMap("b", "y").clear();
+ assertEquals(table.row("b"), ImmutableMap.of());
+ assertFalse(table.backingMap.containsKey("b"));
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java
new file mode 100644
index 000000000..a9c7e9ff4
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TreeBasedTableRowMapSubMapTest extends RowMapTests {
+ public TreeBasedTableRowMapSubMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ TreeBasedTable<String, Integer, Character> makeTable() {
+ TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("a", 1, 'a');
+ table.put("z", 1, 'a');
+ return table;
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ TreeBasedTable<String, Integer, Character> table = makeTable();
+ populateTable(table);
+ return table.rowMap().subMap("b", "x");
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ return makeTable().rowMap().subMap("b", "x");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "z";
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java
new file mode 100644
index 000000000..7d7b82e43
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TreeBasedTableRowMapTailMapTest extends RowMapTests {
+ public TreeBasedTableRowMapTailMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ TreeBasedTable<String, Integer, Character> makeTable() {
+ TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("a", 1, 'a');
+ return table;
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ TreeBasedTable<String, Integer, Character> table = makeTable();
+ populateTable(table);
+ return table.rowMap().tailMap("b");
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ return makeTable().rowMap().tailMap("b");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java
new file mode 100644
index 000000000..63a86bfcc
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+
+@GwtCompatible
+public class TreeBasedTableRowMapTest extends RowMapTests {
+ public TreeBasedTableRowMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java
new file mode 100644
index 000000000..9a67fe934
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+
+@GwtCompatible
+public class TreeBasedTableRowTest extends RowTests {
+ public TreeBasedTableRowTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java b/android/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java
index 084e6492f..7975111ed 100644
--- a/android/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java
+++ b/android/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java
@@ -20,7 +20,6 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.collect.testing.SortedMapInterfaceTest;
import com.google.common.collect.testing.SortedMapTestSuiteBuilder;
import com.google.common.collect.testing.TestStringSortedMapGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
@@ -48,7 +47,6 @@ public class TreeBasedTableTest extends AbstractTableTest {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(TreeBasedTableTest.class);
- suite.addTestSuite(TreeRowTest.class);
suite.addTest(
SortedMapTestSuiteBuilder.using(
new TestStringSortedMapGenerator() {
@@ -73,58 +71,6 @@ public class TreeBasedTableTest extends AbstractTableTest {
return suite;
}
- public static class TreeRowTest extends SortedMapInterfaceTest<String, String> {
- public TreeRowTest() {
- super(false, false, true, true, true);
- }
-
- @Override
- protected SortedMap<String, String> makeEmptyMap() {
- TreeBasedTable<String, String, String> table = TreeBasedTable.create();
- table.put("a", "b", "c");
- table.put("c", "b", "a");
- table.put("a", "a", "d");
- return table.row("b");
- }
-
- @Override
- protected SortedMap<String, String> makePopulatedMap() {
- TreeBasedTable<String, String, String> table = TreeBasedTable.create();
- table.put("a", "b", "c");
- table.put("c", "b", "a");
- table.put("b", "b", "x");
- table.put("b", "c", "y");
- table.put("b", "x", "n");
- table.put("a", "a", "d");
- return table.row("b");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "q";
- }
-
- @Override
- protected String getValueNotInPopulatedMap() {
- return "p";
- }
-
- public void testClearSubMapOfRowMap() {
- TreeBasedTable<String, String, String> table = TreeBasedTable.create();
- table.put("a", "b", "c");
- table.put("c", "b", "a");
- table.put("b", "b", "x");
- table.put("b", "c", "y");
- table.put("b", "x", "n");
- table.put("a", "a", "d");
- table.row("b").subMap("c", "x").clear();
- assertEquals(table.row("b"), ImmutableMap.of("b", "x", "x", "n"));
- table.row("b").subMap("b", "y").clear();
- assertEquals(table.row("b"), ImmutableMap.of());
- assertFalse(table.backingMap.containsKey("b"));
- }
- }
-
private TreeBasedTable<String, Integer, Character> sortedTable;
protected TreeBasedTable<String, Integer, Character> create(
diff --git a/android/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java b/android/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java
index 92a3d83a7..4b00570a6 100644
--- a/android/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java
+++ b/android/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java
@@ -28,6 +28,7 @@ import java.util.Iterator;
import java.util.Map.Entry;
import java.util.SortedSet;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@code TreeMultimap} with explicit comparators.
@@ -41,11 +42,11 @@ public class TreeMultimapExplicitTest extends TestCase {
* Compare strings lengths, and if the lengths are equal compare the strings. A {@code null} is
* less than any non-null value.
*/
- private enum StringLength implements Comparator<String> {
+ private enum StringLength implements Comparator<@Nullable String> {
COMPARATOR;
@Override
- public int compare(String first, String second) {
+ public int compare(@Nullable String first, @Nullable String second) {
if (first == second) {
return 0;
} else if (first == null) {
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java
new file mode 100644
index 000000000..3f49178c3
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableColumnMapTest extends ColumnMapTests {
+ public UnmodifiableRowSortedTableColumnMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ RowSortedTable<Integer, String, Character> original = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(original);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ RowSortedTable<Integer, String, Character> table = TreeBasedTable.create();
+ table.put(1, "foo", 'a');
+ table.put(1, "bar", 'b');
+ table.put(3, "foo", 'c');
+ return Tables.unmodifiableRowSortedTable(table).columnMap();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java
new file mode 100644
index 000000000..ff7008160
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableColumnTest extends ColumnTests {
+ public UnmodifiableRowSortedTableColumnTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
+ table.put("one", 'a', 1);
+ table.put("two", 'a', 2);
+ table.put("three", 'a', 3);
+ table.put("four", 'b', 4);
+ return Tables.unmodifiableRowSortedTable(table).column('a');
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java
new file mode 100644
index 000000000..76dadc334
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+import java.util.SortedMap;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableRowMapTest extends RowMapTests {
+ public UnmodifiableRowSortedTableRowMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ RowSortedTable<String, Integer, Character> makeTable() {
+ RowSortedTable<String, Integer, Character> original = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(original);
+ }
+
+ @Override
+ protected SortedMap<String, Map<Integer, Character>> makePopulatedMap() {
+ RowSortedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("foo", 1, 'a');
+ table.put("bar", 1, 'b');
+ table.put("foo", 3, 'c');
+ return Tables.unmodifiableRowSortedTable(table).rowMap();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java
new file mode 100644
index 000000000..0de5f0e34
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableRowTest extends RowTests {
+ public UnmodifiableRowSortedTableRowTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
+ table.put('a', "one", 1);
+ table.put('a', "two", 2);
+ table.put('a', "three", 3);
+ table.put('b', "four", 4);
+ return Tables.unmodifiableRowSortedTable(table).row('a');
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java
new file mode 100644
index 000000000..a5cc6fba9
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableColumnMapTest extends ColumnMapTests {
+ public UnmodifiableTableColumnMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ Table<Integer, String, Character> original = HashBasedTable.create();
+ return Tables.unmodifiableTable(original);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<Integer, String, Character> table = HashBasedTable.create();
+ table.put(1, "foo", 'a');
+ table.put(1, "bar", 'b');
+ table.put(3, "foo", 'c');
+ return Tables.unmodifiableTable(table).columnMap();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java
new file mode 100644
index 000000000..ebf378b87
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableColumnTest extends ColumnTests {
+ public UnmodifiableTableColumnTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ return Tables.unmodifiableTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ table.put("one", 'a', 1);
+ table.put("two", 'a', 2);
+ table.put("three", 'a', 3);
+ table.put("four", 'b', 4);
+ return Tables.unmodifiableTable(table).column('a');
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java
new file mode 100644
index 000000000..c53f15777
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableRowMapTest extends RowMapTests {
+ public UnmodifiableTableRowMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ Table<String, Integer, Character> original = HashBasedTable.create();
+ return Tables.unmodifiableTable(original);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<String, Integer, Character> table = HashBasedTable.create();
+ table.put("foo", 1, 'a');
+ table.put("bar", 1, 'b');
+ table.put("foo", 3, 'c');
+ return Tables.unmodifiableTable(table).rowMap();
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java
new file mode 100644
index 000000000..f0440abc5
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableRowTest extends RowTests {
+ public UnmodifiableTableRowTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ return Tables.unmodifiableTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ table.put('a', "one", 1);
+ table.put('a', "two", 2);
+ table.put('a', "three", 3);
+ table.put('b', "four", 4);
+ return Tables.unmodifiableTable(table).row('a');
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java b/android/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java
index 6d9c1d89d..47d04bfc9 100644
--- a/android/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java
+++ b/android/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java
@@ -62,7 +62,7 @@ public class ArrayBasedEscaperMapTest extends TestCase {
char[][] replacementArray = fem.getReplacementArray();
// Array length is highest character value + 1
assertEquals(65536, replacementArray.length);
- // The final element should always be non null.
+ // The final element should always be non-null.
assertNotNull(replacementArray[replacementArray.length - 1]);
// Exhaustively check all mappings (an int index avoids wrapping).
for (int n = 0; n < replacementArray.length; ++n) {
diff --git a/android/guava-tests/test/com/google/common/escape/EscapersTest.java b/android/guava-tests/test/com/google/common/escape/EscapersTest.java
index 442232030..e9549d083 100644
--- a/android/guava-tests/test/com/google/common/escape/EscapersTest.java
+++ b/android/guava-tests/test/com/google/common/escape/EscapersTest.java
@@ -60,7 +60,7 @@ public class EscapersTest extends TestCase {
}
public void testBuilderCreatesIndependentEscapers() {
- // Setup a simple builder and create the first escaper.
+ // Set up a simple builder and create the first escaper.
Escapers.Builder builder = Escapers.builder();
builder.setSafeRange('a', 'z');
builder.setUnsafeReplacement("X");
@@ -108,7 +108,7 @@ public class EscapersTest extends TestCase {
}
}
- // A trival non-optimized escaper for testing.
+ // A trivial non-optimized escaper for testing.
static CharEscaper createSimpleCharEscaper(final ImmutableMap<Character, char[]> replacementMap) {
return new CharEscaper() {
@Override
@@ -118,7 +118,7 @@ public class EscapersTest extends TestCase {
};
}
- // A trival non-optimized escaper for testing.
+ // A trivial non-optimized escaper for testing.
static UnicodeEscaper createSimpleUnicodeEscaper(
final ImmutableMap<Integer, char[]> replacementMap) {
return new UnicodeEscaper() {
diff --git a/android/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java b/android/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java
index 96cfa10b0..48f2f1715 100644
--- a/android/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java
+++ b/android/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java
@@ -18,6 +18,7 @@ package com.google.common.escape;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link UnicodeEscaper}.
@@ -39,7 +40,7 @@ public class UnicodeEscaperTest extends TestCase {
private static final UnicodeEscaper NOP_ESCAPER =
new UnicodeEscaper() {
@Override
- protected char[] escape(int c) {
+ protected char @Nullable [] escape(int c) {
return null;
}
};
@@ -48,7 +49,7 @@ public class UnicodeEscaperTest extends TestCase {
private static final UnicodeEscaper SIMPLE_ESCAPER =
new UnicodeEscaper() {
@Override
- protected char[] escape(int cp) {
+ protected char @Nullable [] escape(int cp) {
return ('a' <= cp && cp <= 'z') || ('A' <= cp && cp <= 'Z') || ('0' <= cp && cp <= '9')
? null
: ("[" + String.valueOf(cp) + "]").toCharArray();
@@ -163,7 +164,7 @@ public class UnicodeEscaperTest extends TestCase {
new UnicodeEscaper() {
// Canonical escaper method that only escapes lower case ASCII letters.
@Override
- protected char[] escape(int cp) {
+ protected char @Nullable [] escape(int cp) {
return ('a' <= cp && cp <= 'z') ? new char[] {Character.toUpperCase((char) cp)} : null;
}
// Inefficient implementation that defines all letters as escapable.
diff --git a/android/guava-tests/test/com/google/common/eventbus/DispatcherTest.java b/android/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
index b63a99543..ec78c716f 100644
--- a/android/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
+++ b/android/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
@@ -31,7 +31,6 @@ import junit.framework.TestCase;
*
* @author Colin Decker
*/
-
public class DispatcherTest extends TestCase {
private final EventBus bus = new EventBus();
diff --git a/android/guava-tests/test/com/google/common/eventbus/EventBusTest.java b/android/guava-tests/test/com/google/common/eventbus/EventBusTest.java
index 249d3b06c..d314f7ee7 100644
--- a/android/guava-tests/test/com/google/common/eventbus/EventBusTest.java
+++ b/android/guava-tests/test/com/google/common/eventbus/EventBusTest.java
@@ -168,7 +168,7 @@ public class EventBusTest extends TestCase {
GhostCatcher catcher = new GhostCatcher();
bus.register(catcher);
- // A String -- an event for which noone has registered.
+ // A String -- an event for which no one has registered.
bus.post(EVENT);
List<DeadEvent> events = catcher.getEvents();
@@ -239,7 +239,6 @@ public class EventBusTest extends TestCase {
// NOTE: This test will always pass if register() is thread-safe but may also
// pass if it isn't, though this is unlikely.
-
public void testRegisterThreadSafety() throws Exception {
List<StringCatcher> catchers = Lists.newCopyOnWriteArrayList();
List<Future<?>> futures = Lists.newArrayList();
diff --git a/android/guava-tests/test/com/google/common/eventbus/PackageSanityTests.java b/android/guava-tests/test/com/google/common/eventbus/PackageSanityTests.java
index 225e55500..539e13607 100644
--- a/android/guava-tests/test/com/google/common/eventbus/PackageSanityTests.java
+++ b/android/guava-tests/test/com/google/common/eventbus/PackageSanityTests.java
@@ -18,7 +18,7 @@ package com.google.common.eventbus;
import com.google.common.testing.AbstractPackageSanityTests;
import java.lang.reflect.Method;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Basic sanity tests for the entire package.
@@ -41,7 +41,7 @@ public class PackageSanityTests extends AbstractPackageSanityTests {
private final EventBus eventBus = new EventBus();
@Subscribe
- public void handle(@CheckForNull Object anything) {}
+ public void handle(@Nullable Object anything) {}
Subscriber toSubscriber() throws Exception {
return Subscriber.create(eventBus, this, subscriberMethod());
diff --git a/android/guava-tests/test/com/google/common/eventbus/StringCatcher.java b/android/guava-tests/test/com/google/common/eventbus/StringCatcher.java
index 198fa2eda..0fb9cecf1 100644
--- a/android/guava-tests/test/com/google/common/eventbus/StringCatcher.java
+++ b/android/guava-tests/test/com/google/common/eventbus/StringCatcher.java
@@ -18,8 +18,8 @@ package com.google.common.eventbus;
import com.google.common.collect.Lists;
import java.util.List;
-import javax.annotation.CheckForNull;
import junit.framework.Assert;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A simple EventSubscriber mock that records Strings.
@@ -33,11 +33,11 @@ public class StringCatcher {
private List<String> events = Lists.newArrayList();
@Subscribe
- public void hereHaveAString(@CheckForNull String string) {
+ public void hereHaveAString(@Nullable String string) {
events.add(string);
}
- public void methodWithoutAnnotation(@CheckForNull String string) {
+ public void methodWithoutAnnotation(@Nullable String string) {
Assert.fail("Event bus must not call methods without @Subscribe!");
}
diff --git a/android/guava-tests/test/com/google/common/eventbus/SubscriberTest.java b/android/guava-tests/test/com/google/common/eventbus/SubscriberTest.java
index e2380df21..14210ac14 100644
--- a/android/guava-tests/test/com/google/common/eventbus/SubscriberTest.java
+++ b/android/guava-tests/test/com/google/common/eventbus/SubscriberTest.java
@@ -22,6 +22,7 @@ import com.google.common.testing.EqualsTester;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Subscriber}.
@@ -35,7 +36,7 @@ public class SubscriberTest extends TestCase {
private EventBus bus;
private boolean methodCalled;
- private Object methodArgument;
+ private @Nullable Object methodArgument;
@Override
protected void setUp() throws Exception {
diff --git a/android/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java b/android/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java
index f4af7a751..54d6c93f5 100644
--- a/android/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java
+++ b/android/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java
@@ -18,6 +18,7 @@ package com.google.common.eventbus.outside;
import com.google.common.eventbus.EventBus;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Abstract base class for tests that EventBus finds the correct subscribers.
@@ -34,7 +35,7 @@ abstract class AbstractEventBusTest<H> extends TestCase {
abstract H createSubscriber();
- private H subscriber;
+ private @Nullable H subscriber;
H getSubscriber() {
return subscriber;
diff --git a/android/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java b/android/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java
index 776e4bfea..a02783f61 100644
--- a/android/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java
+++ b/android/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java
@@ -36,6 +36,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -785,7 +786,6 @@ public abstract class AbstractNetworkTest {
assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12);
}
-
@Test
public void concurrentIteration() throws Exception {
addEdge(1, 2, "foo");
@@ -799,9 +799,9 @@ public abstract class AbstractNetworkTest {
for (int i = 0; i < threadCount; i++) {
futures.add(
executor.submit(
- new Callable<Object>() {
+ new Callable<@Nullable Void>() {
@Override
- public Object call() throws Exception {
+ public @Nullable Void call() throws Exception {
barrier.await();
Integer first = network.nodes().iterator().next();
for (Integer node : network.nodes()) {
diff --git a/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java b/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java
index a483f42d1..da9226c31 100644
--- a/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java
+++ b/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java
@@ -166,8 +166,8 @@ public abstract class AbstractStandardUndirectedGraphTest extends AbstractGraphT
@Test
public void hasEdgeConnecting_mismatch() {
putEdge(N1, N2);
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N1, N2))).isTrue();
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N2, N1))).isTrue();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N1, N2))).isFalse();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N2, N1))).isFalse();
}
@Test
diff --git a/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java b/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java
index 5cda1c1bb..beadaf92d 100644
--- a/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java
+++ b/android/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java
@@ -16,6 +16,7 @@
package com.google.common.graph;
+import static com.google.common.graph.GraphConstants.ENDPOINTS_MISMATCH;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertTrue;
@@ -195,15 +196,30 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
@Test
public void edges_containsOrderMismatch() {
addEdge(N1, N2, E12);
- assertThat(network.asGraph().edges()).contains(ENDPOINTS_N2N1);
- assertThat(network.asGraph().edges()).contains(ENDPOINTS_N1N2);
+ assertThat(network.asGraph().edges()).doesNotContain(ENDPOINTS_N2N1);
+ assertThat(network.asGraph().edges()).doesNotContain(ENDPOINTS_N1N2);
+ }
+
+ @Test
+ public void edgesConnecting_orderMismatch() {
+ addEdge(N1, N2, E12);
+ try {
+ Set<String> unused = network.edgesConnecting(ENDPOINTS_N1N2);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
public void edgeConnectingOrNull_orderMismatch() {
addEdge(N1, N2, E12);
- assertThat(network.edgeConnectingOrNull(ENDPOINTS_N2N1)).isEqualTo(E12);
- assertThat(network.edgeConnectingOrNull(ENDPOINTS_N1N2)).isEqualTo(E12);
+ try {
+ String unused = network.edgeConnectingOrNull(ENDPOINTS_N1N2);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -418,7 +434,7 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N4, N5, E12);
fail(ERROR_ADDED_EXISTING_EDGE);
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
}
@@ -432,13 +448,13 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N1, N2, EDGE_NOT_IN_GRAPH);
fail(ERROR_ADDED_PARALLEL_EDGE);
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_PARALLEL_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_PARALLEL_EDGE);
}
try {
networkAsMutableNetwork.addEdge(N2, N1, EDGE_NOT_IN_GRAPH);
fail(ERROR_ADDED_PARALLEL_EDGE);
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_PARALLEL_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_PARALLEL_EDGE);
}
}
@@ -458,7 +474,12 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
assume().that(graphIsMutable()).isTrue();
EndpointPair<Integer> endpoints = EndpointPair.ordered(N1, N2);
- assertThat(networkAsMutableNetwork.addEdge(endpoints, E12)).isTrue();
+ try {
+ networkAsMutableNetwork.addEdge(endpoints, E12);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -527,20 +548,20 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N1, N2, E11);
fail("Reusing an existing self-loop edge to connect different nodes succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
try {
networkAsMutableNetwork.addEdge(N2, N2, E11);
fail("Reusing an existing self-loop edge to make a different self-loop edge succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
addEdge(N1, N2, E12);
try {
networkAsMutableNetwork.addEdge(N1, N1, E12);
fail("Reusing an existing edge to add a self-loop edge between different nodes succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
}
@@ -555,7 +576,7 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N1, N1, EDGE_NOT_IN_GRAPH);
fail("Adding a parallel self-loop edge succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_PARALLEL_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_PARALLEL_EDGE);
}
}
diff --git a/android/guava-tests/test/com/google/common/graph/ElementOrderTest.java b/android/guava-tests/test/com/google/common/graph/ElementOrderTest.java
index 0557fb7ba..5e4c8d4d8 100644
--- a/android/guava-tests/test/com/google/common/graph/ElementOrderTest.java
+++ b/android/guava-tests/test/com/google/common/graph/ElementOrderTest.java
@@ -150,7 +150,7 @@ public final class ElementOrderTest {
// Combined node and edge order tests
@Test
- public void nodeOrderUnorderedandEdgesSorted() {
+ public void nodeOrderUnorderedAndEdgesSorted() {
MutableNetwork<Integer, String> network =
NetworkBuilder.directed()
.nodeOrder(unordered())
diff --git a/android/guava-tests/test/com/google/common/graph/EndpointPairTest.java b/android/guava-tests/test/com/google/common/graph/EndpointPairTest.java
index 099be1d22..c67693a71 100644
--- a/android/guava-tests/test/com/google/common/graph/EndpointPairTest.java
+++ b/android/guava-tests/test/com/google/common/graph/EndpointPairTest.java
@@ -214,8 +214,8 @@ public final class EndpointPairTest {
assertThat(edges).contains(EndpointPair.unordered(N1, N2));
assertThat(edges).contains(EndpointPair.unordered(N2, N1)); // equal to unordered(N1, N2)
- // ordered endpoints OK for undirected graph (because ordering is irrelevant)
- assertThat(edges).contains(EndpointPair.ordered(N1, N2));
+ // ordered endpoints not compatible with undirected graph
+ assertThat(edges).doesNotContain(EndpointPair.ordered(N1, N2));
assertThat(edges).doesNotContain(EndpointPair.unordered(N2, N2)); // edge not present
assertThat(edges).doesNotContain(EndpointPair.unordered(N3, N4)); // nodes not in graph
diff --git a/android/guava-tests/test/com/google/common/graph/ValueGraphTest.java b/android/guava-tests/test/com/google/common/graph/ValueGraphTest.java
index b17c91dfa..24323ca00 100644
--- a/android/guava-tests/test/com/google/common/graph/ValueGraphTest.java
+++ b/android/guava-tests/test/com/google/common/graph/ValueGraphTest.java
@@ -28,6 +28,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -173,8 +174,8 @@ public final class ValueGraphTest {
public void hasEdgeConnecting_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(1, 2))).isTrue();
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(2, 1))).isTrue();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(1, 2))).isFalse();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(2, 1))).isFalse();
}
@Test
@@ -223,8 +224,19 @@ public final class ValueGraphTest {
public void edgeValueOrDefault_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
- assertThat(graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default")).isEqualTo("A");
- assertThat(graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default")).isEqualTo("A");
+ // Check that edgeValueOrDefault() throws on each possible ordering of an ordered EndpointPair
+ try {
+ String unused = graph.edgeValueOrDefault(EndpointPair.ordered(1, 2), "default");
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
+ try {
+ String unused = graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default");
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -251,7 +263,12 @@ public final class ValueGraphTest {
@Test
public void putEdgeValue_undirected_orderMismatch() {
graph = ValueGraphBuilder.undirected().build();
- assertThat(graph.putEdgeValue(EndpointPair.ordered(1, 2), "irrelevant")).isNull();
+ try {
+ graph.putEdgeValue(EndpointPair.ordered(1, 2), "irrelevant");
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -311,7 +328,19 @@ public final class ValueGraphTest {
public void removeEdge_undirected_orderMismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "1-2");
- assertThat(graph.removeEdge(EndpointPair.ordered(1, 2))).isEqualTo("1-2");
+ // Check that removeEdge() throws on each possible ordering of an ordered EndpointPair
+ try {
+ graph.removeEdge(EndpointPair.ordered(1, 2));
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
+ try {
+ graph.removeEdge(EndpointPair.ordered(2, 1));
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -380,7 +409,6 @@ public final class ValueGraphTest {
.inOrder();
}
-
@Test
public void concurrentIteration() throws Exception {
graph = ValueGraphBuilder.directed().build();
@@ -395,9 +423,9 @@ public final class ValueGraphTest {
for (int i = 0; i < threadCount; i++) {
futures.add(
executor.submit(
- new Callable<Object>() {
+ new Callable<@Nullable Void>() {
@Override
- public Object call() throws Exception {
+ public @Nullable Void call() throws Exception {
barrier.await();
Integer first = graph.nodes().iterator().next();
for (Integer node : graph.nodes()) {
diff --git a/android/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java b/android/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java
index e5c359aaf..7ceb25e0c 100644
--- a/android/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java
+++ b/android/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java
@@ -17,7 +17,6 @@ package com.google.common.hash;
import static com.google.common.base.Charsets.UTF_16LE;
import static org.junit.Assert.assertArrayEquals;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import junit.framework.TestCase;
@@ -110,7 +109,6 @@ public class AbstractByteHasherTest extends TestCase {
}
}
- @CanIgnoreReturnValue
private class TestHasher extends AbstractByteHasher {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
diff --git a/android/guava-tests/test/com/google/common/hash/BloomFilterTest.java b/android/guava-tests/test/com/google/common/hash/BloomFilterTest.java
index d99be0902..8ee920ca9 100644
--- a/android/guava-tests/test/com/google/common/hash/BloomFilterTest.java
+++ b/android/guava-tests/test/com/google/common/hash/BloomFilterTest.java
@@ -36,8 +36,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for SimpleGenericBloomFilter and derived BloomFilter views.
@@ -408,7 +408,7 @@ public class BloomFilterTest extends TestCase {
}
@Override
- public boolean equals(@CheckForNull Object object) {
+ public boolean equals(@Nullable Object object) {
return (object instanceof CustomFunnel);
}
diff --git a/android/guava-tests/test/com/google/common/hash/HashCodeTest.java b/android/guava-tests/test/com/google/common/hash/HashCodeTest.java
index 4cccefe7e..231fd402b 100644
--- a/android/guava-tests/test/com/google/common/hash/HashCodeTest.java
+++ b/android/guava-tests/test/com/google/common/hash/HashCodeTest.java
@@ -24,6 +24,7 @@ import com.google.common.io.BaseEncoding;
import com.google.common.testing.ClassSanityTester;
import java.util.Arrays;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link HashCode}.
@@ -391,7 +392,7 @@ public class HashCodeTest extends TestCase {
final Long asLong; // null means that asLong should throw an exception
final String toString;
- ExpectedHashCode(byte[] bytes, int asInt, Long asLong, String toString) {
+ ExpectedHashCode(byte[] bytes, int asInt, @Nullable Long asLong, String toString) {
this.bytes = bytes;
this.asInt = asInt;
this.asLong = asLong;
diff --git a/android/guava-tests/test/com/google/common/hash/HashTestUtils.java b/android/guava-tests/test/com/google/common/hash/HashTestUtils.java
index 9e9944b5a..3a9b46c8e 100644
--- a/android/guava-tests/test/com/google/common/hash/HashTestUtils.java
+++ b/android/guava-tests/test/com/google/common/hash/HashTestUtils.java
@@ -376,7 +376,7 @@ final class HashTestUtils {
for (int j = 0; j < keyBits; j++) {
if (j <= i) continue;
int count = 0;
- int maxCount = 20; // the probability of error here is miniscule
+ int maxCount = 20; // the probability of error here is minuscule
boolean diff = false;
while (!diff) {
diff --git a/android/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java b/android/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java
index 4dbb4241e..7783b5fc3 100644
--- a/android/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java
+++ b/android/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java
@@ -29,6 +29,7 @@ import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
import sun.security.jca.ProviderList;
import sun.security.jca.Providers;
@@ -155,7 +156,7 @@ public class MacHashFunctionTest extends TestCase {
}
@Override
- public byte[] getEncoded() {
+ public byte @Nullable [] getEncoded() {
return null;
}
diff --git a/android/guava-tests/test/com/google/common/io/BaseEncodingTest.java b/android/guava-tests/test/com/google/common/io/BaseEncodingTest.java
index c2fdf0257..e67f70c5a 100644
--- a/android/guava-tests/test/com/google/common/io/BaseEncodingTest.java
+++ b/android/guava-tests/test/com/google/common/io/BaseEncodingTest.java
@@ -35,8 +35,8 @@ import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code BaseEncoding}.
@@ -125,7 +125,6 @@ public class BaseEncodingTest extends TestCase {
base64().upperCase();
fail();
} catch (IllegalStateException expected) {
- // success
}
}
@@ -134,7 +133,14 @@ public class BaseEncodingTest extends TestCase {
base64().lowerCase();
fail();
} catch (IllegalStateException expected) {
- // success
+ }
+ }
+
+ public void testBase64CannotIgnoreCase() {
+ try {
+ base64().ignoreCase();
+ fail();
+ } catch (IllegalStateException expected) {
}
}
@@ -262,7 +268,19 @@ public class BaseEncodingTest extends TestCase {
}
public void testBase32UpperCaseIsNoOp() {
- assertSame(base32(), base32().upperCase());
+ assertThat(base32().upperCase()).isSameInstanceAs(base32());
+ }
+
+ public void testBase32LowerCase() {
+ testEncodingWithCasing(base32().lowerCase(), "foobar", "mzxw6ytboi======");
+ }
+
+ public void testBase32IgnoreCase() {
+ BaseEncoding ignoreCase = base32().ignoreCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base32());
+ assertThat(ignoreCase).isSameInstanceAs(base32().ignoreCase());
+ testDecodes(ignoreCase, "MZXW6YTBOI======", "foobar");
+ testDecodes(ignoreCase, "mzxw6ytboi======", "foobar");
}
public void testBase32Offset() {
@@ -318,7 +336,7 @@ public class BaseEncodingTest extends TestCase {
}
public void testBase32HexUpperCaseIsNoOp() {
- assertSame(base32Hex(), base32Hex().upperCase());
+ assertThat(base32Hex().upperCase()).isSameInstanceAs(base32Hex());
}
public void testBase16() {
@@ -332,7 +350,44 @@ public class BaseEncodingTest extends TestCase {
}
public void testBase16UpperCaseIsNoOp() {
- assertSame(base16(), base16().upperCase());
+ assertThat(base16().upperCase()).isSameInstanceAs(base16());
+ }
+
+ public void testBase16LowerCase() {
+ BaseEncoding lowerCase = base16().lowerCase();
+ assertThat(lowerCase).isNotSameInstanceAs(base16());
+ assertThat(lowerCase).isSameInstanceAs(base16().lowerCase());
+ testEncodingWithCasing(lowerCase, "foobar", "666f6f626172");
+ }
+
+ public void testBase16IgnoreCase() {
+ BaseEncoding ignoreCase = base16().ignoreCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base16());
+ assertThat(ignoreCase).isSameInstanceAs(base16().ignoreCase());
+ testEncodingWithCasing(ignoreCase, "foobar", "666F6F626172");
+ testDecodes(ignoreCase, "666F6F626172", "foobar");
+ testDecodes(ignoreCase, "666f6f626172", "foobar");
+ testDecodes(ignoreCase, "666F6f626172", "foobar");
+ }
+
+ public void testBase16LowerCaseIgnoreCase() {
+ BaseEncoding ignoreCase = base16().lowerCase().ignoreCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base16());
+ assertThat(ignoreCase).isSameInstanceAs(base16().lowerCase().ignoreCase());
+ testEncodingWithCasing(ignoreCase, "foobar", "666f6f626172");
+ testDecodes(ignoreCase, "666F6F626172", "foobar");
+ testDecodes(ignoreCase, "666f6f626172", "foobar");
+ testDecodes(ignoreCase, "666F6f626172", "foobar");
+ }
+
+ // order the methods are called should not matter
+ public void testBase16IgnoreCaseLowerCase() {
+ BaseEncoding ignoreCase = base16().ignoreCase().lowerCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base16());
+ testEncodingWithCasing(ignoreCase, "foobar", "666f6f626172");
+ testDecodes(ignoreCase, "666F6F626172", "foobar");
+ testDecodes(ignoreCase, "666f6f626172", "foobar");
+ testDecodes(ignoreCase, "666F6f626172", "foobar");
}
public void testBase16InvalidDecodings() {
@@ -344,6 +399,8 @@ public class BaseEncodingTest extends TestCase {
assertFailsToDecode(base16(), "ABC");
// These have a combination of invalid length and unrecognized characters.
assertFailsToDecode(base16(), "?", "Invalid input length 1");
+ assertFailsToDecode(base16(), "ab");
+ assertFailsToDecode(base16().lowerCase(), "AB");
}
public void testBase16Offset() {
@@ -391,12 +448,12 @@ public class BaseEncodingTest extends TestCase {
}
private static void testDecodes(BaseEncoding encoding, String encoded, String decoded) {
- assertTrue(encoding.canDecode(encoded));
+ assertThat(encoding.canDecode(encoded)).isTrue();
assertThat(encoding.decode(encoded)).isEqualTo(decoded.getBytes(UTF_8));
}
private static void testDecodesByBytes(BaseEncoding encoding, String encoded, byte[] decoded) {
- assertTrue(encoding.canDecode(encoded));
+ assertThat(encoding.canDecode(encoded)).isTrue();
assertThat(encoding.decode(encoded)).isEqualTo(decoded);
}
@@ -405,7 +462,7 @@ public class BaseEncodingTest extends TestCase {
}
private static void assertFailsToDecode(
- BaseEncoding encoding, String cannotDecode, @CheckForNull String expectedMessage) {
+ BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage) {
// We use this somewhat weird pattern with an enum for each assertion we want to make as a way
// of dealing with the fact that one of the assertions is @GwtIncompatible but we don't want to
// have to have duplicate @GwtIncompatible test methods just to make that assertion.
@@ -419,7 +476,7 @@ public class BaseEncodingTest extends TestCase {
DECODING_STREAM {
@Override
void assertFailsToDecode(
- BaseEncoding encoding, String cannotDecode, @CheckForNull String expectedMessage) {
+ BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage) {
// Regression test for case where DecodingException was swallowed by default implementation
// of
// InputStream.read(byte[], int, int)
@@ -440,14 +497,14 @@ public class BaseEncodingTest extends TestCase {
CAN_DECODE {
@Override
void assertFailsToDecode(
- BaseEncoding encoding, String cannotDecode, @CheckForNull String expectedMessage) {
- assertFalse(encoding.canDecode(cannotDecode));
+ BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage) {
+ assertThat(encoding.canDecode(cannotDecode)).isFalse();
}
},
DECODE {
@Override
void assertFailsToDecode(
- BaseEncoding encoding, String cannotDecode, @CheckForNull String expectedMessage) {
+ BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage) {
try {
encoding.decode(cannotDecode);
fail("Expected IllegalArgumentException");
@@ -461,7 +518,7 @@ public class BaseEncodingTest extends TestCase {
DECODE_CHECKED {
@Override
void assertFailsToDecode(
- BaseEncoding encoding, String cannotDecode, @CheckForNull String expectedMessage) {
+ BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage) {
try {
encoding.decodeChecked(cannotDecode);
fail("Expected DecodingException");
@@ -474,7 +531,7 @@ public class BaseEncodingTest extends TestCase {
};
abstract void assertFailsToDecode(
- BaseEncoding encoding, String cannotDecode, @CheckForNull String expectedMessage);
+ BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage);
}
@GwtIncompatible // Reader/Writer
@@ -512,9 +569,9 @@ public class BaseEncodingTest extends TestCase {
private static void testStreamingEncodes(BaseEncoding encoding, String decoded, String encoded)
throws IOException {
StringWriter writer = new StringWriter();
- OutputStream encodingStream = encoding.encodingStream(writer);
- encodingStream.write(decoded.getBytes(UTF_8));
- encodingStream.close();
+ try (OutputStream encodingStream = encoding.encodingStream(writer)) {
+ encodingStream.write(decoded.getBytes(UTF_8));
+ }
assertThat(writer.toString()).isEqualTo(encoded);
}
@@ -522,22 +579,21 @@ public class BaseEncodingTest extends TestCase {
private static void testStreamingDecodes(BaseEncoding encoding, String encoded, String decoded)
throws IOException {
byte[] bytes = decoded.getBytes(UTF_8);
- InputStream decodingStream = encoding.decodingStream(new StringReader(encoded));
- for (int i = 0; i < bytes.length; i++) {
- assertThat(decodingStream.read()).isEqualTo(bytes[i] & 0xFF);
+ try (InputStream decodingStream = encoding.decodingStream(new StringReader(encoded))) {
+ for (int i = 0; i < bytes.length; i++) {
+ assertThat(decodingStream.read()).isEqualTo(bytes[i] & 0xFF);
+ }
+ assertThat(decodingStream.read()).isEqualTo(-1);
}
- assertThat(decodingStream.read()).isEqualTo(-1);
- decodingStream.close();
}
public void testToString() {
- assertEquals("BaseEncoding.base64().withPadChar('=')", base64().toString());
- assertEquals("BaseEncoding.base32Hex().omitPadding()", base32Hex().omitPadding().toString());
- assertEquals(
- "BaseEncoding.base32().lowerCase().withPadChar('$')",
- base32().lowerCase().withPadChar('$').toString());
- assertEquals(
- "BaseEncoding.base16().withSeparator(\"\n\", 10)",
- base16().withSeparator("\n", 10).toString());
+ assertThat(base64().toString()).isEqualTo("BaseEncoding.base64().withPadChar('=')");
+ assertThat(base32Hex().omitPadding().toString())
+ .isEqualTo("BaseEncoding.base32Hex().omitPadding()");
+ assertThat(base32().lowerCase().withPadChar('$').toString())
+ .isEqualTo("BaseEncoding.base32().lowerCase().withPadChar('$')");
+ assertThat(base16().withSeparator("\n", 10).toString())
+ .isEqualTo("BaseEncoding.base16().withSeparator(\"\n\", 10)");
}
}
diff --git a/android/guava-tests/test/com/google/common/io/ByteSinkTester.java b/android/guava-tests/test/com/google/common/io/ByteSinkTester.java
index a8ed36f81..6baf3779d 100644
--- a/android/guava-tests/test/com/google/common/io/ByteSinkTester.java
+++ b/android/guava-tests/test/com/google/common/io/ByteSinkTester.java
@@ -31,12 +31,12 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code ByteSink} implementations.
- * Generates tests of a all methods on a {@code ByteSink} given various inputs written to it as well
+ * Generates tests of all methods on a {@code ByteSink} given various inputs written to it as well
* as sub-suites for testing the {@code CharSink} view in the same way.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class ByteSinkTester extends SourceSinkTester<ByteSink, byte[], ByteSinkFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(ByteSinkTester.class);
diff --git a/android/guava-tests/test/com/google/common/io/ByteSourceTest.java b/android/guava-tests/test/com/google/common/io/ByteSourceTest.java
index 3cf6cca44..58ad653c2 100644
--- a/android/guava-tests/test/com/google/common/io/ByteSourceTest.java
+++ b/android/guava-tests/test/com/google/common/io/ByteSourceTest.java
@@ -40,6 +40,7 @@ import java.io.OutputStream;
import java.util.Arrays;
import java.util.EnumSet;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for the default implementations of {@code ByteSource} methods.
@@ -151,8 +152,8 @@ public class ByteSourceTest extends IoTestCase {
}
public void testRead_withProcessor_stopsOnFalse() throws IOException {
- ByteProcessor<Void> processor =
- new ByteProcessor<Void>() {
+ ByteProcessor<@Nullable Void> processor =
+ new ByteProcessor<@Nullable Void>() {
boolean firstCall = true;
@Override
@@ -163,7 +164,7 @@ public class ByteSourceTest extends IoTestCase {
}
@Override
- public Void getResult() {
+ public @Nullable Void getResult() {
return null;
}
};
@@ -473,7 +474,9 @@ public class ByteSourceTest extends IoTestCase {
}
}
- /** @return the number of exceptions that were suppressed on the expected thrown exception */
+ /**
+ * @return the number of exceptions that were suppressed on the expected thrown exception
+ */
private static int runSuppressionFailureTest(ByteSource in, ByteSink out) {
try {
in.copyTo(out);
diff --git a/android/guava-tests/test/com/google/common/io/ByteSourceTester.java b/android/guava-tests/test/com/google/common/io/ByteSourceTester.java
index 758541256..fe10810f6 100644
--- a/android/guava-tests/test/com/google/common/io/ByteSourceTester.java
+++ b/android/guava-tests/test/com/google/common/io/ByteSourceTester.java
@@ -37,13 +37,13 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code ByteSource} implementations.
- * Generates tests of a all methods on a {@code ByteSource} given various inputs the source is
+ * Generates tests of all methods on a {@code ByteSource} given various inputs the source is
* expected to contain as well as sub-suites for testing the {@code CharSource} view and {@code
* slice()} views in the same way.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class ByteSourceTester extends SourceSinkTester<ByteSource, byte[], ByteSourceFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(ByteSourceTester.class);
diff --git a/android/guava-tests/test/com/google/common/io/ByteStreamsTest.java b/android/guava-tests/test/com/google/common/io/ByteStreamsTest.java
index dddae1ffc..2598b9fed 100644
--- a/android/guava-tests/test/com/google/common/io/ByteStreamsTest.java
+++ b/android/guava-tests/test/com/google/common/io/ByteStreamsTest.java
@@ -380,7 +380,7 @@ public class ByteStreamsTest extends IoTestCase {
assertThat(out.toByteArray()).isEqualTo(expected);
}
- @AndroidIncompatible // https://code.google.com/p/android/issues/detail?id=196848
+ @AndroidIncompatible // https://issuetracker.google.com/issues/37074504
public void testUtf16Expected() {
byte[] hardcodedExpected = utf16ExpectedWithBom;
byte[] computedExpected = "r\u00C9sum\u00C9".getBytes(Charsets.UTF_16);
diff --git a/android/guava-tests/test/com/google/common/io/CharSinkTester.java b/android/guava-tests/test/com/google/common/io/CharSinkTester.java
index 788f9c02e..58a75498c 100644
--- a/android/guava-tests/test/com/google/common/io/CharSinkTester.java
+++ b/android/guava-tests/test/com/google/common/io/CharSinkTester.java
@@ -28,11 +28,11 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code CharSink} implementations.
- * Generates tests of a all methods on a {@code CharSink} given various inputs written to it.
+ * Generates tests of all methods on a {@code CharSink} given various inputs written to it.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class CharSinkTester extends SourceSinkTester<CharSink, String, CharSinkFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(CharSinkTester.class);
diff --git a/android/guava-tests/test/com/google/common/io/CharSourceTester.java b/android/guava-tests/test/com/google/common/io/CharSourceTester.java
index e73fcdc17..1f75b121f 100644
--- a/android/guava-tests/test/com/google/common/io/CharSourceTester.java
+++ b/android/guava-tests/test/com/google/common/io/CharSourceTester.java
@@ -33,12 +33,12 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code CharSource} implementations.
- * Generates tests of a all methods on a {@code CharSource} given various inputs the source is
+ * Generates tests of all methods on a {@code CharSource} given various inputs the source is
* expected to contain.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class CharSourceTester extends SourceSinkTester<CharSource, String, CharSourceFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(CharSourceTester.class);
diff --git a/android/guava-tests/test/com/google/common/io/CloserTest.java b/android/guava-tests/test/com/google/common/io/CloserTest.java
index 38ff700c8..f30d771a8 100644
--- a/android/guava-tests/test/com/google/common/io/CloserTest.java
+++ b/android/guava-tests/test/com/google/common/io/CloserTest.java
@@ -31,8 +31,8 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.LogRecord;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Closer}.
@@ -393,7 +393,7 @@ public class CloserTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof Suppression) {
Suppression other = (Suppression) obj;
return closeable.equals(other.closeable)
@@ -435,7 +435,7 @@ public class CloserTest extends TestCase {
throw new IOException();
}
- private TestCloseable(@CheckForNull Throwable throwOnClose) {
+ private TestCloseable(@Nullable Throwable throwOnClose) {
this.throwOnClose = throwOnClose;
}
diff --git a/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java b/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java
new file mode 100644
index 000000000..4ecdcf8d5
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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.io;
+
+import static com.google.common.io.FileBackedOutputStreamTest.write;
+
+import com.google.common.testing.GcFinalization;
+import java.io.File;
+
+/**
+ * Android-incompatible tests for {@link FileBackedOutputStream}.
+ *
+ * @author Chris Nokleberg
+ */
+@AndroidIncompatible // Finalization probably just doesn't happen fast enough?
+public class FileBackedOutputStreamAndroidIncompatibleTest extends IoTestCase {
+
+ public void testFinalizeDeletesFile() throws Exception {
+ byte[] data = newPreFilledByteArray(100);
+ FileBackedOutputStream out = new FileBackedOutputStream(0, true);
+
+ write(out, data, 0, 100, true);
+ final File file = out.getFile();
+ assertEquals(100, file.length());
+ assertTrue(file.exists());
+ out.close();
+
+ // Make sure that finalize deletes the file
+ out = null;
+
+ // times out and throws RuntimeException on failure
+ GcFinalization.awaitDone(
+ new GcFinalization.FinalizationPredicate() {
+ @Override
+ public boolean isDone() {
+ return !file.exists();
+ }
+ });
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java b/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java
index 6841a41a9..3d756a88b 100644
--- a/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java
+++ b/android/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java
@@ -16,16 +16,25 @@
package com.google.common.io;
+import static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
+import static com.google.common.truth.Truth.assertThat;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
+import static org.junit.Assert.assertThrows;
-import com.google.common.testing.GcFinalization;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFileAttributes;
import java.util.Arrays;
/**
* Unit tests for {@link FileBackedOutputStream}.
*
+ * <p>For a tiny bit more testing, see {@link FileBackedOutputStreamAndroidIncompatibleTest}.
+ *
* @author Chris Nokleberg
*/
public class FileBackedOutputStreamTest extends IoTestCase {
@@ -61,10 +70,21 @@ public class FileBackedOutputStreamTest extends IoTestCase {
// Write data to go over the threshold
if (chunk2 > 0) {
+ if (JAVA_IO_TMPDIR.value().equals("/sdcard")) {
+ assertThrows(IOException.class, () -> write(out, data, chunk1, chunk2, singleByte));
+ return;
+ }
write(out, data, chunk1, chunk2, singleByte);
file = out.getFile();
assertEquals(dataSize, file.length());
assertTrue(file.exists());
+ assertThat(file.getName()).contains("FileBackedOutputStream");
+ if (!isAndroid() && !isWindows()) {
+ PosixFileAttributes attributes =
+ java.nio.file.Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class)
+ .readAttributes();
+ assertThat(attributes.permissions()).containsExactly(OWNER_READ, OWNER_WRITE);
+ }
}
out.close();
@@ -79,30 +99,6 @@ public class FileBackedOutputStreamTest extends IoTestCase {
}
- public void testFinalizeDeletesFile() throws Exception {
- byte[] data = newPreFilledByteArray(100);
- FileBackedOutputStream out = new FileBackedOutputStream(0, true);
-
- write(out, data, 0, 100, true);
- final File file = out.getFile();
- assertEquals(100, file.length());
- assertTrue(file.exists());
- out.close();
-
- // Make sure that finalize deletes the file
- out = null;
-
- // times out and throws RuntimeException on failure
- GcFinalization.awaitDone(
- new GcFinalization.FinalizationPredicate() {
- @Override
- public boolean isDone() {
- return !file.exists();
- }
- });
- }
-
-
public void testThreshold_resetOnFinalize() throws Exception {
testThreshold(0, 100, true, true);
testThreshold(10, 100, true, true);
@@ -114,7 +110,7 @@ public class FileBackedOutputStreamTest extends IoTestCase {
testThreshold(1000, 100, false, true);
}
- private static void write(OutputStream out, byte[] b, int off, int len, boolean singleByte)
+ static void write(OutputStream out, byte[] b, int off, int len, boolean singleByte)
throws IOException {
if (singleByte) {
for (int i = off; i < off + len; i++) {
@@ -133,6 +129,10 @@ public class FileBackedOutputStreamTest extends IoTestCase {
FileBackedOutputStream out = new FileBackedOutputStream(50);
ByteSource source = out.asByteSource();
+ if (JAVA_IO_TMPDIR.value().equals("/sdcard")) {
+ assertThrows(IOException.class, () -> out.write(data));
+ return;
+ }
out.write(data);
assertTrue(Arrays.equals(data, source.read()));
@@ -164,4 +164,12 @@ public class FileBackedOutputStreamTest extends IoTestCase {
out.close();
}
+
+ private static boolean isAndroid() {
+ return System.getProperty("java.runtime.name", "").contains("Android");
+ }
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/android/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java b/android/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java
new file mode 100644
index 000000000..a31c43770
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2007 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.io;
+
+import static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
+import static com.google.common.truth.Truth.assertThat;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
+import static org.junit.Assert.assertThrows;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFileAttributes;
+import junit.framework.TestCase;
+
+/**
+ * Unit test for {@link Files#createTempDir}.
+ *
+ * @author Chris Nokleberg
+ */
+
+@SuppressWarnings("deprecation") // tests of a deprecated method
+public class FilesCreateTempDirTest extends TestCase {
+ public void testCreateTempDir() throws IOException {
+ if (JAVA_IO_TMPDIR.value().equals("/sdcard")) {
+ assertThrows(IllegalStateException.class, Files::createTempDir);
+ return;
+ }
+ File temp = Files.createTempDir();
+ try {
+ assertThat(temp.exists()).isTrue();
+ assertThat(temp.isDirectory()).isTrue();
+ assertThat(temp.listFiles()).isEmpty();
+ File child = new File(temp, "child");
+ assertThat(child.createNewFile()).isTrue();
+ assertThat(child.delete()).isTrue();
+
+ if (!isAndroid() && !isWindows()) {
+ PosixFileAttributes attributes =
+ java.nio.file.Files.getFileAttributeView(temp.toPath(), PosixFileAttributeView.class)
+ .readAttributes();
+ assertThat(attributes.permissions())
+ .containsExactly(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
+ }
+ } finally {
+ assertThat(temp.delete()).isTrue();
+ }
+ }
+
+ private static boolean isAndroid() {
+ return System.getProperty("java.runtime.name", "").contains("Android");
+ }
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java b/android/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java
index c13240685..9409d216d 100644
--- a/android/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java
+++ b/android/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java
@@ -22,11 +22,6 @@ import com.google.common.collect.Iterables;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.File;
import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Path;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-import junit.framework.TestCase;
/**
* Tests for {@link Files#fileTraverser()}.
@@ -34,37 +29,13 @@ import junit.framework.TestCase;
* @author Jens Nyman
*/
-public class FilesFileTraverserTest extends TestCase {
+public class FilesFileTraverserTest extends IoTestCase {
private File rootDir;
@Override
public void setUp() throws IOException {
- rootDir = Files.createTempDir();
- }
-
- @Override
- public void tearDown() throws IOException {
- // delete rootDir and its contents
- java.nio.file.Files.walkFileTree(
- rootDir.toPath(),
- new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
- throws IOException {
- java.nio.file.Files.deleteIfExists(file);
- return FileVisitResult.CONTINUE;
- }
-
- @Override
- public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
- if (exc != null) {
- return FileVisitResult.TERMINATE;
- }
- java.nio.file.Files.deleteIfExists(dir);
- return FileVisitResult.CONTINUE;
- }
- });
+ rootDir = createTempDir();
}
public void testFileTraverser_emptyDirectory() throws Exception {
diff --git a/android/guava-tests/test/com/google/common/io/FilesTest.java b/android/guava-tests/test/com/google/common/io/FilesTest.java
index 8446da1d5..6ffcf5c81 100644
--- a/android/guava-tests/test/com/google/common/io/FilesTest.java
+++ b/android/guava-tests/test/com/google/common/io/FilesTest.java
@@ -42,13 +42,19 @@ import junit.framework.TestSuite;
/**
* Unit test for {@link Files}.
*
- * <p>Note: {@link Files#fileTraverser()} is tested in {@link FilesFileTraverserTest}.
+ * <p>Some methods are tested in separate files:
+ *
+ * <ul>
+ * <li>{@link Files#fileTraverser()} is tested in {@link FilesFileTraverserTest}.
+ * <li>{@link Files#createTempDir()} is tested in {@link FilesCreateTempDirTest}.
+ * </ul>
*
* @author Chris Nokleberg
*/
public class FilesTest extends IoTestCase {
+ @AndroidIncompatible // suites, ByteSourceTester (b/230620681)
public static TestSuite suite() {
TestSuite suite = new TestSuite();
suite.addTest(
@@ -357,14 +363,6 @@ public class FilesTest extends IoTestCase {
}
}
- public void testCreateTempDir() {
- File temp = Files.createTempDir();
- assertTrue(temp.exists());
- assertTrue(temp.isDirectory());
- assertThat(temp.listFiles()).isEmpty();
- assertTrue(temp.delete());
- }
-
public void testMove() throws IOException {
File i18nFile = getTestFile("i18n.txt");
File temp1 = createTempFile();
diff --git a/android/guava-tests/test/com/google/common/io/IoTestCase.java b/android/guava-tests/test/com/google/common/io/IoTestCase.java
index fa8961905..c79ebcbd2 100644
--- a/android/guava-tests/test/com/google/common/io/IoTestCase.java
+++ b/android/guava-tests/test/com/google/common/io/IoTestCase.java
@@ -28,6 +28,7 @@ import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base test case class for I/O tests.
@@ -92,7 +93,7 @@ public abstract class IoTestCase extends TestCase {
}
/** Returns the file with the given name under the testdata directory. */
- protected final File getTestFile(String name) throws IOException {
+ protected final @Nullable File getTestFile(String name) throws IOException {
File file = new File(getTestDir(), name);
if (!file.exists()) {
URL resourceUrl = IoTestCase.class.getResource("testdata/" + name);
diff --git a/android/guava-tests/test/com/google/common/io/ResourcesTest.java b/android/guava-tests/test/com/google/common/io/ResourcesTest.java
index af2abbbc6..b1a46c698 100644
--- a/android/guava-tests/test/com/google/common/io/ResourcesTest.java
+++ b/android/guava-tests/test/com/google/common/io/ResourcesTest.java
@@ -22,9 +22,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.NullPointerTester;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -42,6 +40,7 @@ import junit.framework.TestSuite;
public class ResourcesTest extends IoTestCase {
+ @AndroidIncompatible // wouldn't run anyway, but strip the source entirely because of b/230620681
public static TestSuite suite() {
TestSuite suite = new TestSuite();
suite.addTest(
@@ -62,9 +61,9 @@ public class ResourcesTest extends IoTestCase {
assertThat(Resources.toString(resource, Charsets.US_ASCII)).isNotEqualTo(I18N);
}
- public void testToToByteArray() throws IOException {
- byte[] data = Resources.toByteArray(classfile(Resources.class));
- assertEquals(0xCAFEBABE, new DataInputStream(new ByteArrayInputStream(data)).readInt());
+ public void testToByteArray() throws IOException {
+ URL resource = getClass().getResource("testdata/i18n.txt");
+ assertThat(Resources.toByteArray(resource)).isEqualTo(I18N.getBytes(Charsets.UTF_8));
}
public void testReadLines() throws IOException {
@@ -160,7 +159,7 @@ public class ResourcesTest extends IoTestCase {
Thread.currentThread().setContextClassLoader(loader);
URL url = Resources.getResource(tempFile.getName());
String text = Resources.toString(url, Charsets.UTF_8);
- assertEquals("rud a chur ar an méar fhada\n", text);
+ assertEquals("rud a chur ar an méar fhada" + System.lineSeparator(), text);
} finally {
Thread.currentThread().setContextClassLoader(oldContextLoader);
}
@@ -181,6 +180,7 @@ public class ResourcesTest extends IoTestCase {
}
}
+ @AndroidIncompatible // .class files aren't available
public void testNulls() {
new NullPointerTester()
.setDefault(URL.class, classfile(ResourcesTest.class))
diff --git a/android/guava-tests/test/com/google/common/io/SourceSinkFactories.java b/android/guava-tests/test/com/google/common/io/SourceSinkFactories.java
index e70370e1d..b6dab3563 100644
--- a/android/guava-tests/test/com/google/common/io/SourceSinkFactories.java
+++ b/android/guava-tests/test/com/google/common/io/SourceSinkFactories.java
@@ -37,7 +37,7 @@ import java.io.Writer;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.logging.Logger;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* {@link SourceSinkFactory} implementations.
@@ -305,7 +305,7 @@ public class SourceSinkFactories {
private final byte[] initialBytes;
- private FileByteSinkFactory(@CheckForNull byte[] initialBytes) {
+ private FileByteSinkFactory(byte @Nullable [] initialBytes) {
this.initialBytes = initialBytes;
}
@@ -375,7 +375,7 @@ public class SourceSinkFactories {
private final String initialString;
- private FileCharSinkFactory(@CheckForNull String initialString) {
+ private FileCharSinkFactory(@Nullable String initialString) {
this.initialString = initialString;
}
diff --git a/android/guava-tests/test/com/google/common/io/SourceSinkTester.java b/android/guava-tests/test/com/google/common/io/SourceSinkTester.java
index 55a302f85..544467f9d 100644
--- a/android/guava-tests/test/com/google/common/io/SourceSinkTester.java
+++ b/android/guava-tests/test/com/google/common/io/SourceSinkTester.java
@@ -35,7 +35,7 @@ import junit.framework.TestCase;
* @param <F> the factory type
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class SourceSinkTester<S, T, F extends SourceSinkFactory<S, T>> extends TestCase {
static final String LOREM_IPSUM =
diff --git a/android/guava-tests/test/com/google/common/math/BigIntegerMathTest.java b/android/guava-tests/test/com/google/common/math/BigIntegerMathTest.java
index 170261bb5..2bfe3a325 100644
--- a/android/guava-tests/test/com/google/common/math/BigIntegerMathTest.java
+++ b/android/guava-tests/test/com/google/common/math/BigIntegerMathTest.java
@@ -40,7 +40,9 @@ import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
@@ -54,6 +56,7 @@ import junit.framework.TestCase;
*
* @author Louis Wasserman
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class BigIntegerMathTest extends TestCase {
public void testCeilingPowerOfTwo() {
@@ -110,6 +113,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantSqrt2PrecomputedBits() {
assertEquals(
@@ -213,6 +217,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -224,6 +229,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10NegativeAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -235,6 +241,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Floor() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -246,6 +253,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Ceiling() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -258,6 +266,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of log10(BigInteger, FLOOR).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Exact() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -272,6 +281,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10HalfUp() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -284,6 +294,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10HalfDown() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -297,6 +308,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of log10(BigInteger, {HALF_UP,HALF_DOWN}).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10HalfEven() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -308,6 +320,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10TrivialOnPowerOf10() {
BigInteger x = BigInteger.TEN.pow(100);
@@ -316,6 +329,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtZeroAlwaysZero() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -323,6 +337,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtNegativeAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -334,6 +349,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtFloor() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -346,6 +362,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtCeiling() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -359,6 +376,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of sqrt(BigInteger, FLOOR).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtExact() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -374,6 +392,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtHalfUp() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -390,6 +409,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtHalfDown() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -407,6 +427,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of sqrt(BigInteger, {HALF_UP,HALF_DOWN}).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtHalfEven() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -418,6 +439,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // slow
public void testDivNonZero() {
@@ -438,6 +460,7 @@ public class BigIntegerMathTest extends TestCase {
private static final BigInteger BAD_FOR_GINGERBREAD_P = new BigInteger("-9223372036854775808");
private static final BigInteger BAD_FOR_GINGERBREAD_Q = new BigInteger("-4294967296");
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // slow
public void testDivNonZeroExact() {
@@ -469,6 +492,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testZeroDivIsAlwaysZero() {
for (BigInteger q : NONZERO_BIGINTEGER_CANDIDATES) {
@@ -478,6 +502,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testDivByZeroAlwaysFails() {
for (BigInteger p : ALL_BIGINTEGER_CANDIDATES) {
@@ -515,6 +540,7 @@ public class BigIntegerMathTest extends TestCase {
runBinomialTest(0, 30);
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testBinomialLarge() {
runBinomialTest(31, 100);
@@ -548,6 +574,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible
private static final class RoundToDoubleTester {
private final BigInteger input;
@@ -558,6 +585,7 @@ public class BigIntegerMathTest extends TestCase {
this.input = input;
}
+ @CanIgnoreReturnValue
RoundToDoubleTester setExpectation(double expectedValue, RoundingMode... modes) {
for (RoundingMode mode : modes) {
Double previous = expectedValues.put(mode, expectedValue);
@@ -568,6 +596,7 @@ public class BigIntegerMathTest extends TestCase {
return this;
}
+ @CanIgnoreReturnValue
public RoundToDoubleTester roundUnnecessaryShouldThrow() {
unnecessaryShouldThrow = true;
return this;
@@ -598,16 +627,19 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_Zero() {
new RoundToDoubleTester(BigInteger.ZERO).setExpectation(0.0, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_smallPositive() {
new RoundToDoubleTester(BigInteger.valueOf(16)).setExpectation(16.0, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxPreciselyRepresentable() {
new RoundToDoubleTester(BigInteger.valueOf(1L << 53))
@@ -615,6 +647,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxPreciselyRepresentablePlusOne() {
double twoToThe53 = Math.pow(2, 53);
@@ -627,6 +660,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_twoToThe54PlusOne() {
double twoToThe54 = Math.pow(2, 54);
@@ -639,6 +673,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_twoToThe54PlusThree() {
double twoToThe54 = Math.pow(2, 54);
@@ -651,6 +686,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_twoToThe54PlusFour() {
new RoundToDoubleTester(BigInteger.valueOf((1L << 54) + 4))
@@ -658,12 +694,14 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxDouble() {
BigInteger maxDoubleAsBI = DoubleMath.roundToBigInteger(Double.MAX_VALUE, UNNECESSARY);
new RoundToDoubleTester(maxDoubleAsBI).setExpectation(Double.MAX_VALUE, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxDoublePlusOne() {
BigInteger maxDoubleAsBI =
@@ -675,6 +713,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_wayTooBig() {
BigInteger bi = BigInteger.ONE.shiftLeft(2 * Double.MAX_EXPONENT);
@@ -685,11 +724,13 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_smallNegative() {
new RoundToDoubleTester(BigInteger.valueOf(-16)).setExpectation(-16.0, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minPreciselyRepresentable() {
new RoundToDoubleTester(BigInteger.valueOf(-1L << 53))
@@ -697,6 +738,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minPreciselyRepresentableMinusOne() {
// the representable doubles are -2^53 and -2^53 - 2.
@@ -708,6 +750,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeTwoToThe54MinusOne() {
new RoundToDoubleTester(BigInteger.valueOf((-1L << 54) - 1))
@@ -717,6 +760,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeTwoToThe54MinusThree() {
new RoundToDoubleTester(BigInteger.valueOf((-1L << 54) - 3))
@@ -727,6 +771,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeTwoToThe54MinusFour() {
new RoundToDoubleTester(BigInteger.valueOf((-1L << 54) - 4))
@@ -734,12 +779,14 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minDouble() {
BigInteger minDoubleAsBI = DoubleMath.roundToBigInteger(-Double.MAX_VALUE, UNNECESSARY);
new RoundToDoubleTester(minDoubleAsBI).setExpectation(-Double.MAX_VALUE, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minDoubleMinusOne() {
BigInteger minDoubleAsBI =
@@ -751,6 +798,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeWayTooBig() {
BigInteger bi = BigInteger.ONE.shiftLeft(2 * Double.MAX_EXPONENT).negate();
@@ -761,6 +809,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
@@ -770,6 +819,7 @@ public class BigIntegerMathTest extends TestCase {
tester.testAllPublicStaticMethods(BigIntegerMath.class);
}
+ @J2ktIncompatible
@GwtIncompatible // String.format
private static void failFormat(String template, Object... args) {
fail(String.format(template, args));
diff --git a/android/guava-tests/test/com/google/common/math/DoubleMathTest.java b/android/guava-tests/test/com/google/common/math/DoubleMathTest.java
index 724ae96d8..93de8c716 100644
--- a/android/guava-tests/test/com/google/common/math/DoubleMathTest.java
+++ b/android/guava-tests/test/com/google/common/math/DoubleMathTest.java
@@ -40,6 +40,7 @@ import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Doubles;
@@ -79,6 +80,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundIntegralDoubleToInt() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -98,6 +100,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundFractionalDoubleToInt() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -120,6 +123,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundExactIntegralDoubleToInt() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -137,6 +141,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundExactFractionalDoubleToIntFails() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -148,6 +153,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundNaNToIntAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -159,6 +165,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundInfiniteToIntAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -175,6 +182,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundIntegralDoubleToLong() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -194,6 +202,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundFractionalDoubleToLong() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -213,6 +222,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundExactIntegralDoubleToLong() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -231,6 +241,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundExactFractionalDoubleToLongFails() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -242,6 +253,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundNaNToLongAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -253,6 +265,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundInfiniteToLongAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -269,6 +282,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundIntegralDoubleToBigInteger() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -279,6 +293,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundFractionalDoubleToBigInteger() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -289,6 +304,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundExactIntegralDoubleToBigInteger() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -297,6 +313,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundExactFractionalDoubleToBigIntegerFails() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -308,6 +325,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundNaNToBigIntegerAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -319,6 +337,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundInfiniteToBigIntegerAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -335,6 +354,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundLog2Floor() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -344,6 +364,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath
public void testRoundLog2Ceiling() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -354,6 +375,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath
public void testRoundLog2Down() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -370,6 +392,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath
public void testRoundLog2Up() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -386,6 +409,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2Half() {
// We don't expect perfect rounding accuracy.
@@ -404,6 +428,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2Exact() {
for (double x : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -418,6 +443,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2ThrowsOnZerosInfinitiesAndNaN() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -432,6 +458,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2ThrowsOnNegative() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -445,6 +472,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isPowerOfTwo, DoubleMath.log2(double, RoundingMode), StrictMath
public void testIsPowerOfTwoYes() {
for (int i = -1074; i <= 1023; i++) {
@@ -452,6 +480,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isPowerOfTwo, DoubleMath.log2(double, RoundingMode), StrictMath
public void testIsPowerOfTwo() {
for (double x : ALL_DOUBLE_CANDIDATES) {
@@ -464,6 +493,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // #trueLog2, Math.ulp
public void testLog2Accuracy() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -496,6 +526,7 @@ public class DoubleMathTest extends TestCase {
assertTrue(Double.isNaN(DoubleMath.log2(Double.NaN)));
}
+ @J2ktIncompatible
@GwtIncompatible // StrictMath
private strictfp double trueLog2(double d) {
double trueLog2 = StrictMath.log(d) / StrictMath.log(2);
@@ -514,6 +545,7 @@ public class DoubleMathTest extends TestCase {
return trueLog2;
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isMathematicalInteger
public void testIsMathematicalIntegerIntegral() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -521,6 +553,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isMathematicalInteger
public void testIsMathematicalIntegerFractional() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -528,6 +561,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isMathematicalInteger
public void testIsMathematicalIntegerNotFinite() {
for (double d : Arrays.asList(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN)) {
@@ -535,6 +569,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Math.ulp
public void testFactorial() {
for (int i = 0; i <= DoubleMath.MAX_FACTORIAL; i++) {
@@ -710,6 +745,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_doubleVarargs() {
assertEquals(-1.375, DoubleMath.mean(1.1, -2.2, 4.4, -8.8), 1.0e-10);
@@ -726,18 +762,21 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_intVarargs() {
assertEquals(-13.75, DoubleMath.mean(11, -22, 44, -88), 1.0e-10);
assertEquals(11.0, DoubleMath.mean(11), 1.0e-10);
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_longVarargs() {
assertEquals(-13.75, DoubleMath.mean(11L, -22L, 44L, -88L), 1.0e-10);
assertEquals(11.0, DoubleMath.mean(11L), 1.0e-10);
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_emptyVarargs() {
try {
@@ -747,6 +786,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_doubleIterable() {
assertEquals(-1.375, DoubleMath.mean(ImmutableList.of(1.1, -2.2, 4.4, -8.8)), 1.0e-10);
@@ -768,6 +808,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_intIterable() {
assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11, -22, 44, -88)), 1.0e-10);
@@ -779,6 +820,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_longIterable() {
assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11L, -22L, 44L, -88L)), 1.0e-10);
@@ -790,6 +832,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_intIterator() {
assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11, -22, 44, -88).iterator()), 1.0e-10);
@@ -801,6 +844,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_longIterator() {
assertEquals(
@@ -813,6 +857,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/math/IntMathTest.java b/android/guava-tests/test/com/google/common/math/IntMathTest.java
index 4db13adbd..30588875d 100644
--- a/android/guava-tests/test/com/google/common/math/IntMathTest.java
+++ b/android/guava-tests/test/com/google/common/math/IntMathTest.java
@@ -30,6 +30,7 @@ import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -110,6 +111,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testConstantMaxPowerOfSqrt2Unsigned() {
assertEquals(
@@ -118,6 +120,7 @@ public class IntMathTest extends TestCase {
/*actual=*/ IntMath.MAX_POWER_OF_SQRT2_UNSIGNED);
}
+ @J2ktIncompatible
@GwtIncompatible // pow()
public void testConstantsPowersOf10() {
for (int i = 0; i < IntMath.powersOf10.length - 1; i++) {
@@ -125,6 +128,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testMaxLog10ForLeadingZeros() {
for (int i = 0; i < Integer.SIZE; i++) {
@@ -134,6 +138,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testConstantsHalfPowersOf10() {
for (int i = 0; i < IntMath.halfPowersOf10.length; i++) {
@@ -160,6 +165,7 @@ public class IntMathTest extends TestCase {
2 * IntMath.biggestBinomials.length, IntMath.biggestBinomials.length)));
}
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testPowersSqrtMaxInt() {
assertEquals(
@@ -180,6 +186,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testIsPowerOfTwo() {
for (int x : ALL_INTEGER_CANDIDATES) {
@@ -212,7 +219,7 @@ public class IntMathTest extends TestCase {
}
}
- // Relies on the correctness of BigIntegrerMath.log2 for all modes except UNNECESSARY.
+ // Relies on the correctness of BigIntegerMath.log2 for all modes except UNNECESSARY.
public void testLog2MatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
@@ -235,6 +242,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // log10
public void testLog10ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -246,6 +254,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // log10
public void testLog10NegativeAlwaysThrows() {
for (int x : NEGATIVE_INTEGER_CANDIDATES) {
@@ -260,6 +269,7 @@ public class IntMathTest extends TestCase {
}
// Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY.
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testLog10MatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -271,6 +281,7 @@ public class IntMathTest extends TestCase {
}
// Relies on the correctness of log10(int, FLOOR) and of pow(int, int).
+ @J2ktIncompatible
@GwtIncompatible // pow()
public void testLog10Exact() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -285,6 +296,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // log10
public void testLog10TrivialOnPowerOfTen() {
int x = 1000000;
@@ -294,6 +306,7 @@ public class IntMathTest extends TestCase {
}
// Simple test to cover sqrt(0) for all types and all modes.
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testSqrtZeroAlwaysZero() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -301,6 +314,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testSqrtNegativeAlwaysThrows() {
for (int x : NEGATIVE_INTEGER_CANDIDATES) {
@@ -315,6 +329,7 @@ public class IntMathTest extends TestCase {
}
/* Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY. */
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testSqrtMatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -328,6 +343,7 @@ public class IntMathTest extends TestCase {
}
/* Relies on the correctness of sqrt(int, FLOOR). */
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testSqrtExactMatchesFloorOrThrows() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -343,6 +359,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // 2147483646^2 expected=4
public void testPow() {
for (int i : ALL_INTEGER_CANDIDATES) {
@@ -353,6 +370,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible // TODO(b/281519661): Fails 2147483646/-2147483648 expected:<1> but was:<-1>
public void testDivNonZero() {
for (int p : NONZERO_INTEGER_CANDIDATES) {
for (int q : NONZERO_INTEGER_CANDIDATES) {
@@ -549,6 +567,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedAdd() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -560,6 +579,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedSubtract() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -575,6 +595,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedMultiply() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -589,6 +610,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedPow() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -674,6 +696,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testMean() {
// Odd-sized ranges have an obvious mean
@@ -745,6 +768,7 @@ public class IntMathTest extends TestCase {
return big.bitLength() <= 31;
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
@@ -752,6 +776,7 @@ public class IntMathTest extends TestCase {
tester.testAllPublicStaticMethods(IntMath.class);
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrime() {
// Defer correctness tests to Long.isPrime
diff --git a/android/guava-tests/test/com/google/common/math/LongMathTest.java b/android/guava-tests/test/com/google/common/math/LongMathTest.java
index 40c2ac9ef..ee6ee1cb8 100644
--- a/android/guava-tests/test/com/google/common/math/LongMathTest.java
+++ b/android/guava-tests/test/com/google/common/math/LongMathTest.java
@@ -33,6 +33,7 @@ import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -54,6 +55,7 @@ public class LongMathTest extends TestCase {
assertFalse(LongMath.isPowerOfTwo(LongMath.MAX_SIGNED_POWER_OF_TWO * 2));
}
+ @J2ktIncompatible // TODO(b/281519661): expected:<-2147483648> but was:<2147483648>
public void testCeilingPowerOfTwo() {
for (long x : POSITIVE_LONG_CANDIDATES) {
BigInteger expectedResult = BigIntegerMath.ceilingPowerOfTwo(BigInteger.valueOf(x));
@@ -69,6 +71,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/281519661): expected:<-2147483648> but was:<2147483648>
public void testFloorPowerOfTwo() {
for (long x : POSITIVE_LONG_CANDIDATES) {
BigInteger expectedResult = BigIntegerMath.floorPowerOfTwo(BigInteger.valueOf(x));
@@ -112,6 +115,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantMaxPowerOfSqrt2Unsigned() {
assertEquals(
@@ -120,6 +124,7 @@ public class LongMathTest extends TestCase {
/*actual=*/ LongMath.MAX_POWER_OF_SQRT2_UNSIGNED);
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testMaxLog10ForLeadingZeros() {
for (int i = 0; i < Long.SIZE; i++) {
@@ -129,6 +134,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsPowersOf10() {
for (int i = 0; i < LongMath.powersOf10.length; i++) {
@@ -141,6 +147,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsHalfPowersOf10() {
for (int i = 0; i < LongMath.halfPowersOf10.length; i++) {
@@ -153,6 +160,7 @@ public class LongMathTest extends TestCase {
assertTrue(nextBigger.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0);
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsSqrtMaxLong() {
assertEquals(
@@ -160,6 +168,7 @@ public class LongMathTest extends TestCase {
/*actual=*/ LongMath.FLOOR_SQRT_MAX_LONG);
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsFactorials() {
long expected = 1;
@@ -174,6 +183,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsBiggestBinomials() {
for (int k = 0; k < LongMath.biggestBinomials.length; k++) {
@@ -189,6 +199,7 @@ public class LongMathTest extends TestCase {
// 2 * k is the smallest value for which we don't replace k with (n-k).
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsBiggestSimpleBinomials() {
for (int k = 0; k < LongMath.biggestSimpleBinomials.length; k++) {
@@ -227,6 +238,7 @@ public class LongMathTest extends TestCase {
}
// Throws an ArithmeticException if "the simple implementation" of binomial coefficients overflows
+ @J2ktIncompatible
@GwtIncompatible // TODO
private long simpleBinomial(int n, int k) {
long accum = 1;
@@ -237,6 +249,7 @@ public class LongMathTest extends TestCase {
return accum;
}
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testIsPowerOfTwo() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -293,6 +306,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -304,6 +318,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10NegativeAlwaysThrows() {
for (long x : NEGATIVE_LONG_CANDIDATES) {
@@ -318,6 +333,7 @@ public class LongMathTest extends TestCase {
}
// Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY.
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10MatchesBigInteger() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -328,6 +344,7 @@ public class LongMathTest extends TestCase {
}
// Relies on the correctness of log10(long, FLOOR) and of pow(long, int).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Exact() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -344,6 +361,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10TrivialOnPowerOf10() {
long x = 1000000000000L;
@@ -352,6 +370,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtNegativeAlwaysThrows() {
for (long x : NEGATIVE_LONG_CANDIDATES) {
@@ -366,6 +385,7 @@ public class LongMathTest extends TestCase {
}
// Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY.
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtMatchesBigInteger() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -378,6 +398,7 @@ public class LongMathTest extends TestCase {
}
/* Relies on the correctness of sqrt(long, FLOOR). */
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtExactMatchesFloorOrThrows() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -393,6 +414,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testPow() {
for (long i : ALL_LONG_CANDIDATES) {
@@ -402,6 +424,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // TODO(cpovirk): File BigDecimal.divide() rounding bug.
public void testDivNonZero() {
@@ -419,6 +442,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // Bug in older versions of Android we test against, since fixed.
public void testDivNonZeroExact() {
@@ -439,6 +463,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testZeroDivIsAlwaysZero() {
for (long q : NONZERO_LONG_CANDIDATES) {
@@ -448,6 +473,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testDivByZeroAlwaysFails() {
for (long p : ALL_LONG_CANDIDATES) {
@@ -461,6 +487,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testIntMod() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -470,6 +497,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testIntModNegativeModulusFails() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -483,6 +511,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testIntModZeroModulusFails() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -495,6 +524,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testMod() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -504,6 +534,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testModNegativeModulusFails() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -517,6 +548,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/281519661): expected:<14> but was:<2>
public void testGCDExhaustive() {
for (long a : POSITIVE_LONG_CANDIDATES) {
for (long b : POSITIVE_LONG_CANDIDATES) {
@@ -525,6 +557,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testGCDZero() {
for (long a : POSITIVE_LONG_CANDIDATES) {
@@ -534,6 +567,7 @@ public class LongMathTest extends TestCase {
assertEquals(0, LongMath.gcd(0, 0));
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testGCDNegativePositiveThrows() {
for (long a : NEGATIVE_LONG_CANDIDATES) {
@@ -550,6 +584,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testGCDNegativeZeroThrows() {
for (long a : NEGATIVE_LONG_CANDIDATES) {
@@ -567,7 +602,6 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
- @GwtIncompatible // TODO
public void testCheckedAdd() {
for (long a : ALL_LONG_CANDIDATES) {
for (long b : ALL_LONG_CANDIDATES) {
@@ -586,6 +620,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // slow
public void testCheckedSubtract() {
@@ -638,6 +673,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testCheckedPow() {
for (long b : ALL_LONG_CANDIDATES) {
@@ -659,6 +695,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedAdd() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -670,6 +707,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedSubtract() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -685,6 +723,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedMultiply() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -699,6 +738,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedPow() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -716,6 +756,7 @@ public class LongMathTest extends TestCase {
}
// Depends on the correctness of BigIntegerMath.factorial.
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testFactorial() {
for (int n = 0; n <= 50; n++) {
@@ -725,6 +766,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testFactorialNegative() {
for (int n : NEGATIVE_INTEGER_CANDIDATES) {
@@ -737,6 +779,7 @@ public class LongMathTest extends TestCase {
}
// Depends on the correctness of BigIntegerMath.binomial.
+ @J2ktIncompatible // TODO(b/281519661): expected:<-2091005866> but was:<2203961430>
public void testBinomial() {
for (int n = 0; n <= 70; n++) {
for (int k = 0; k <= n; k++) {
@@ -748,6 +791,7 @@ public class LongMathTest extends TestCase {
}
+ @J2ktIncompatible
@GwtIncompatible // Slow
public void testBinomial_exhaustiveNotOverflowing() {
// Tests all of the inputs to LongMath.binomial that won't cause it to overflow, that weren't
@@ -785,6 +829,7 @@ public class LongMathTest extends TestCase {
}
+ @J2ktIncompatible
@GwtIncompatible // far too slow
public void testSqrtOfPerfectSquareAsDoubleIsPerfect() {
// This takes just over a minute on my machine.
@@ -800,6 +845,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testMean() {
// Odd-sized ranges have an obvious mean
@@ -884,6 +930,7 @@ public class LongMathTest extends TestCase {
return big.longValue();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
@@ -892,6 +939,7 @@ public class LongMathTest extends TestCase {
tester.testAllPublicStaticMethods(LongMath.class);
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeSmall() {
// Check the first 1000 integers
@@ -900,6 +948,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeManyConstants() {
// Test the thorough test inputs, which also includes special constants in the Miller-Rabin
@@ -909,6 +958,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeOnUniformRandom() {
Random rand = new Random(1);
@@ -921,6 +971,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeOnRandomPrimes() {
Random rand = new Random(1);
@@ -932,6 +983,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeOnRandomComposites() {
Random rand = new Random(1);
@@ -944,6 +996,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeThrowsOnNegative() {
try {
@@ -989,6 +1042,7 @@ public class LongMathTest extends TestCase {
Long.MIN_VALUE
};
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDoubleAgainstBigInteger() {
for (RoundingMode roundingMode : EnumSet.complementOf(EnumSet.of(UNNECESSARY))) {
@@ -999,6 +1053,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDoubleAgainstBigIntegerUnnecessary() {
for (long candidate : roundToDoubleTestCandidates) {
diff --git a/android/guava-tests/test/com/google/common/math/MathPreconditionsTest.java b/android/guava-tests/test/com/google/common/math/MathPreconditionsTest.java
index 5dbe017c1..46c70a3a6 100644
--- a/android/guava-tests/test/com/google/common/math/MathPreconditionsTest.java
+++ b/android/guava-tests/test/com/google/common/math/MathPreconditionsTest.java
@@ -103,7 +103,7 @@ public class MathPreconditionsTest extends TestCase {
}
}
- public void testCheckPositive_postiveBigInteger() {
+ public void testCheckPositive_positiveBigInteger() {
MathPreconditions.checkPositive("BigInteger", BigInteger.ONE);
}
@@ -251,7 +251,7 @@ public class MathPreconditionsTest extends TestCase {
}
}
- public void testCheckRoundingUnnnecessary_success() {
+ public void testCheckRoundingUnnecessary_success() {
MathPreconditions.checkRoundingUnnecessary(true);
}
diff --git a/android/guava-tests/test/com/google/common/math/MathTesting.java b/android/guava-tests/test/com/google/common/math/MathTesting.java
index 6b74f11ee..0e49835d8 100644
--- a/android/guava-tests/test/com/google/common/math/MathTesting.java
+++ b/android/guava-tests/test/com/google/common/math/MathTesting.java
@@ -150,7 +150,7 @@ public class MathTesting {
static {
ImmutableSet.Builder<Long> longValues = ImmutableSet.builder();
- // First of all add all the integer candidate values.
+ // First add all the integer candidate values.
longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG));
// Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63).
longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE);
@@ -185,7 +185,7 @@ public class MathTesting {
static {
ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder();
- // First of all add all the long candidate values.
+ // First add all the long candidate values.
bigValues.addAll(Iterables.transform(POSITIVE_LONG_CANDIDATES, TO_BIGINTEGER));
// Add boundary values manually to avoid over/under flow.
bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE));
diff --git a/android/guava-tests/test/com/google/common/math/QuantilesTest.java b/android/guava-tests/test/com/google/common/math/QuantilesTest.java
index 77c70207c..9c8d8e65a 100644
--- a/android/guava-tests/test/com/google/common/math/QuantilesTest.java
+++ b/android/guava-tests/test/com/google/common/math/QuantilesTest.java
@@ -41,8 +41,8 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Quantiles}.
@@ -92,7 +92,7 @@ public class QuantilesTest extends TestCase {
Correspondence.from(
new BinaryPredicate<Double, Double>() {
@Override
- public boolean apply(@CheckForNull Double actual, @CheckForNull Double expected) {
+ public boolean apply(@Nullable Double actual, @Nullable Double expected) {
// Test for equality to allow non-finite values to match; otherwise, use the finite
// test.
return actual.equals(expected)
@@ -424,12 +424,12 @@ public class QuantilesTest extends TestCase {
1, 1.5,
2, 2.0,
8, 5.0,
- 9, POSITIVE_INFINITY, // interpolating between 5.0 and POSITIVE_INFNINITY
+ 9, POSITIVE_INFINITY, // interpolating between 5.0 and POSITIVE_INFINITY
10, POSITIVE_INFINITY);
}
public void testScale_index_compute_doubleCollection_positiveInfinity() {
- // interpolating between 5.0 and POSITIVE_INFNINITY
+ // interpolating between 5.0 and POSITIVE_INFINITY
assertThat(Quantiles.scale(10).index(9).compute(ONE_TO_FIVE_AND_POSITIVE_INFINITY))
.isPositiveInfinity();
}
@@ -442,7 +442,7 @@ public class QuantilesTest extends TestCase {
.comparingValuesUsing(QUANTILE_CORRESPONDENCE)
.containsExactly(
0, NEGATIVE_INFINITY,
- 1, NEGATIVE_INFINITY, // interpolating between NEGATIVE_INFNINITY and 1.0
+ 1, NEGATIVE_INFINITY, // interpolating between NEGATIVE_INFINITY and 1.0
2, 1.0,
8, 4.0,
9, 4.5,
@@ -450,7 +450,7 @@ public class QuantilesTest extends TestCase {
}
public void testScale_index_compute_doubleCollection_negativeInfinity() {
- // interpolating between NEGATIVE_INFNINITY and 1.0
+ // interpolating between NEGATIVE_INFINITY and 1.0
assertThat(Quantiles.scale(10).index(1).compute(ONE_TO_FIVE_AND_NEGATIVE_INFINITY))
.isNegativeInfinity();
}
@@ -540,7 +540,7 @@ public class QuantilesTest extends TestCase {
// Assert that the dataset contains the same elements after the in-place computation (although
// they may be reordered). We only do this for one index rather than for all indexes, as it is
- // quite expensives (quadratic in the size of PSEUDORANDOM_DATASET).
+ // quite expensive (quadratic in the size of PSEUDORANDOM_DATASET).
double[] dataset = Doubles.toArray(PSEUDORANDOM_DATASET);
@SuppressWarnings("unused")
double actual = percentiles().index(33).computeInPlace(dataset);
diff --git a/android/guava-tests/test/com/google/common/math/StatsTesting.java b/android/guava-tests/test/com/google/common/math/StatsTesting.java
index 12689d3e3..dddf20f94 100644
--- a/android/guava-tests/test/com/google/common/math/StatsTesting.java
+++ b/android/guava-tests/test/com/google/common/math/StatsTesting.java
@@ -63,7 +63,7 @@ class StatsTesting {
+ (-56.78 - TWO_VALUES_MEAN) * (-789.012 - OTHER_TWO_VALUES_MEAN);
/**
- * Helper class for testing with non-finite values. {@link #ALL_MANY_VALUES} gives a number
+ * Helper class for testing with non-finite values. {@link #ALL_MANY_VALUES} gives a number of
* instances with many combinations of finite and non-finite values. All have {@link
* #MANY_VALUES_COUNT} values. If all the values are finite then the mean is {@link
* #MANY_VALUES_MEAN} and the sum-of-squares-of-deltas is {@link
@@ -367,7 +367,7 @@ class StatsTesting {
}
/**
- * Asserts that {@code transformation} is diagonal (i.e. neither horizontal or vertical) and
+ * Asserts that {@code transformation} is diagonal (i.e. neither horizontal nor vertical) and
* passes through both {@code (x1, y1)} and {@code (x1 + xDelta, y1 + yDelta)}. Includes
* assertions about all the public instance methods of {@link LinearTransformation} (on both
* {@code transformation} and its inverse). Since the transformation is expected to be diagonal,
diff --git a/android/guava-tests/test/com/google/common/math/TestPlatform.java b/android/guava-tests/test/com/google/common/math/TestPlatform.java
index 03eb2ec0d..86d8e50a6 100644
--- a/android/guava-tests/test/com/google/common/math/TestPlatform.java
+++ b/android/guava-tests/test/com/google/common/math/TestPlatform.java
@@ -26,6 +26,6 @@ class TestPlatform {
}
static boolean isAndroid() {
- return System.getProperty("java.runtime.name").contains("Android");
+ return System.getProperty("java.runtime.name", "").contains("Android");
}
}
diff --git a/android/guava-tests/test/com/google/common/net/HostAndPortTest.java b/android/guava-tests/test/com/google/common/net/HostAndPortTest.java
index 65e80962b..f10cd163f 100644
--- a/android/guava-tests/test/com/google/common/net/HostAndPortTest.java
+++ b/android/guava-tests/test/com/google/common/net/HostAndPortTest.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link HostAndPort}
@@ -102,7 +103,7 @@ public class HostAndPortTest extends TestCase {
private static void checkFromStringCase(
String hpString,
int defaultPort,
- String expectHost,
+ @Nullable String expectHost,
int expectPort,
boolean expectHasExplicitPort) {
HostAndPort hp;
diff --git a/android/guava-tests/test/com/google/common/net/HttpHeadersTest.java b/android/guava-tests/test/com/google/common/net/HttpHeadersTest.java
index 5361b3fce..ef32ccfe3 100644
--- a/android/guava-tests/test/com/google/common/net/HttpHeadersTest.java
+++ b/android/guava-tests/test/com/google/common/net/HttpHeadersTest.java
@@ -40,6 +40,7 @@ public class HttpHeadersTest extends TestCase {
.put("CDN_LOOP", "CDN-Loop")
.put("ETAG", "ETag")
.put("SOURCE_MAP", "SourceMap")
+ .put("SEC_CH_UA_WOW64", "Sec-CH-UA-WoW64")
.put("SEC_WEBSOCKET_ACCEPT", "Sec-WebSocket-Accept")
.put("SEC_WEBSOCKET_EXTENSIONS", "Sec-WebSocket-Extensions")
.put("SEC_WEBSOCKET_KEY", "Sec-WebSocket-Key")
@@ -47,11 +48,11 @@ public class HttpHeadersTest extends TestCase {
.put("SEC_WEBSOCKET_VERSION", "Sec-WebSocket-Version")
.put("X_WEBKIT_CSP", "X-WebKit-CSP")
.put("X_WEBKIT_CSP_REPORT_ONLY", "X-WebKit-CSP-Report-Only")
- .build();
+ .buildOrThrow();
ImmutableSet<String> uppercaseAcronyms =
ImmutableSet.of(
- "CH", "ID", "DNT", "DNS", "ECT", "HTTP2", "IP", "MD5", "P3P", "RTT", "TE", "UA", "UID",
- "URL", "WWW", "XSS");
+ "CH", "ID", "DNT", "DNS", "DPR", "ECT", "HTTP2", "IP", "MD5", "P3P", "RTT", "TE", "UA",
+ "UID", "URL", "WWW", "XSS");
assertConstantNameMatchesString(HttpHeaders.class, specialCases, uppercaseAcronyms);
}
diff --git a/android/guava-tests/test/com/google/common/net/InetAddressesTest.java b/android/guava-tests/test/com/google/common/net/InetAddressesTest.java
index be77e7b17..7d070e404 100644
--- a/android/guava-tests/test/com/google/common/net/InetAddressesTest.java
+++ b/android/guava-tests/test/com/google/common/net/InetAddressesTest.java
@@ -645,7 +645,7 @@ public class InetAddressesTest extends TestCase {
InetAddresses.getCoercedIPv4Address(
InetAddresses.forString("2001:0000:4136:e378:8000:63bf:3fff:fdd3")));
- // 2 Teredo addresses NOT differing in the their embedded IPv4 addresses should hash to the same
+ // 2 Teredo addresses NOT differing in their embedded IPv4 addresses should hash to the same
// value.
assertThat(
InetAddresses.getCoercedIPv4Address(
diff --git a/android/guava-tests/test/com/google/common/net/PercentEscaperTest.java b/android/guava-tests/test/com/google/common/net/PercentEscaperTest.java
index e600e4c7c..a8b6e2541 100644
--- a/android/guava-tests/test/com/google/common/net/PercentEscaperTest.java
+++ b/android/guava-tests/test/com/google/common/net/PercentEscaperTest.java
@@ -45,7 +45,7 @@ public class PercentEscaperTest extends TestCase {
}
}
- // Testing mutlibyte escape sequences
+ // Testing multibyte escape sequences
assertEscaping(e, "%00", '\u0000'); // nul
assertEscaping(e, "%7F", '\u007f'); // del
assertEscaping(e, "%C2%80", '\u0080'); // xx-00010,x-000000
diff --git a/android/guava-tests/test/com/google/common/primitives/BooleansTest.java b/android/guava-tests/test/com/google/common/primitives/BooleansTest.java
index 43ec04c4a..1b39ef715 100644
--- a/android/guava-tests/test/com/google/common/primitives/BooleansTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/BooleansTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -27,6 +31,7 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Booleans}.
@@ -34,6 +39,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class BooleansTest extends TestCase {
private static final boolean[] EMPTY = {};
private static final boolean[] ARRAY_FALSE = {false};
@@ -43,96 +49,94 @@ public class BooleansTest extends TestCase {
private static final boolean[] VALUES = {false, true};
+ @J2ktIncompatible // TODO(b/285538920): Fix and enable.
public void testHashCode() {
- assertEquals(Boolean.TRUE.hashCode(), Booleans.hashCode(true));
- assertEquals(Boolean.FALSE.hashCode(), Booleans.hashCode(false));
+ assertThat(Booleans.hashCode(true)).isEqualTo(Boolean.TRUE.hashCode());
+ assertThat(Booleans.hashCode(false)).isEqualTo(Boolean.FALSE.hashCode());
}
public void testTrueFirst() {
- assertEquals(0, Booleans.trueFirst().compare(true, true));
- assertEquals(0, Booleans.trueFirst().compare(false, false));
- assertTrue(Booleans.trueFirst().compare(true, false) < 0);
- assertTrue(Booleans.trueFirst().compare(false, true) > 0);
+ assertThat(Booleans.trueFirst().compare(true, true)).isEqualTo(0);
+ assertThat(Booleans.trueFirst().compare(false, false)).isEqualTo(0);
+ assertThat(Booleans.trueFirst().compare(true, false)).isLessThan(0);
+ assertThat(Booleans.trueFirst().compare(false, true)).isGreaterThan(0);
}
public void testFalseFirst() {
- assertEquals(0, Booleans.falseFirst().compare(true, true));
- assertEquals(0, Booleans.falseFirst().compare(false, false));
- assertTrue(Booleans.falseFirst().compare(false, true) < 0);
- assertTrue(Booleans.falseFirst().compare(true, false) > 0);
+ assertThat(Booleans.falseFirst().compare(true, true)).isEqualTo(0);
+ assertThat(Booleans.falseFirst().compare(false, false)).isEqualTo(0);
+ assertThat(Booleans.falseFirst().compare(false, true)).isLessThan(0);
+ assertThat(Booleans.falseFirst().compare(true, false)).isGreaterThan(0);
}
public void testCompare() {
for (boolean x : VALUES) {
for (boolean y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Boolean.valueOf(x).compareTo(y), Booleans.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Booleans.compare(x, y))
+ .isEqualTo(Boolean.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Booleans.contains(EMPTY, false));
- assertFalse(Booleans.contains(ARRAY_FALSE, true));
- assertTrue(Booleans.contains(ARRAY_FALSE, false));
- assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, false));
- assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, true));
+ assertThat(Booleans.contains(EMPTY, false)).isFalse();
+ assertThat(Booleans.contains(ARRAY_FALSE, true)).isFalse();
+ assertThat(Booleans.contains(ARRAY_FALSE, false)).isTrue();
+ assertThat(Booleans.contains(ARRAY_FALSE_TRUE, false)).isTrue();
+ assertThat(Booleans.contains(ARRAY_FALSE_TRUE, true)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Booleans.indexOf(EMPTY, ARRAY_FALSE));
- assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE_TRUE));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE_FALSE, ARRAY_FALSE));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_FALSE));
- assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_TRUE));
- assertEquals(0, Booleans.indexOf(ARRAY_TRUE, new boolean[0]));
+ assertThat(Booleans.indexOf(EMPTY, ARRAY_FALSE)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE_TRUE)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_FALSE, ARRAY_FALSE)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_FALSE)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_TRUE)).isEqualTo(1);
+ assertThat(Booleans.indexOf(ARRAY_TRUE, new boolean[0])).isEqualTo(0);
}
public void testIndexOf_arrays() {
- assertEquals(-1, Booleans.indexOf(EMPTY, false));
- assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, true));
- assertEquals(-1, Booleans.indexOf(ARRAY_FALSE_FALSE, true));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE, false));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, false));
- assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, true));
- assertEquals(2, Booleans.indexOf(new boolean[] {false, false, true}, true));
+ assertThat(Booleans.indexOf(EMPTY, false)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, false)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, false)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, true)).isEqualTo(1);
+ assertThat(Booleans.indexOf(new boolean[] {false, false, true}, true)).isEqualTo(2);
}
public void testLastIndexOf() {
- assertEquals(-1, Booleans.lastIndexOf(EMPTY, false));
- assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE, true));
- assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE_FALSE, true));
- assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE, false));
- assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, false));
- assertEquals(1, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, true));
- assertEquals(2, Booleans.lastIndexOf(new boolean[] {false, true, true}, true));
+ assertThat(Booleans.lastIndexOf(EMPTY, false)).isEqualTo(-1);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE, false)).isEqualTo(0);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE_TRUE, false)).isEqualTo(0);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE_TRUE, true)).isEqualTo(1);
+ assertThat(Booleans.lastIndexOf(new boolean[] {false, true, true}, true)).isEqualTo(2);
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Booleans.concat()));
- assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE)));
- assertNotSame(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE));
- assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(EMPTY, ARRAY_FALSE, EMPTY)));
- assertTrue(
- Arrays.equals(
- new boolean[] {false, false, false},
- Booleans.concat(ARRAY_FALSE, ARRAY_FALSE, ARRAY_FALSE)));
- assertTrue(
- Arrays.equals(
- new boolean[] {false, false, true}, Booleans.concat(ARRAY_FALSE, ARRAY_FALSE_TRUE)));
+ assertThat(Booleans.concat()).isEqualTo(EMPTY);
+ assertThat(Booleans.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Booleans.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Booleans.concat(ARRAY_FALSE)).isEqualTo(ARRAY_FALSE);
+ assertThat(Booleans.concat(ARRAY_FALSE)).isNotSameInstanceAs(ARRAY_FALSE);
+ assertThat(Booleans.concat(EMPTY, ARRAY_FALSE, EMPTY)).isEqualTo(ARRAY_FALSE);
+ assertThat(Booleans.concat(ARRAY_FALSE, ARRAY_FALSE, ARRAY_FALSE))
+ .isEqualTo(new boolean[] {false, false, false});
+ assertThat(Booleans.concat(ARRAY_FALSE, ARRAY_FALSE_TRUE))
+ .isEqualTo(new boolean[] {false, false, true});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Booleans.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 0, 1));
- assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 1, 1));
- assertTrue(
- Arrays.equals(
- new boolean[] {true, false, false},
- Booleans.ensureCapacity(new boolean[] {true}, 2, 1)));
+ assertThat(Booleans.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Booleans.ensureCapacity(ARRAY_FALSE, 0, 1)).isSameInstanceAs(ARRAY_FALSE);
+ assertThat(Booleans.ensureCapacity(ARRAY_FALSE, 1, 1)).isSameInstanceAs(ARRAY_FALSE);
+ assertThat(Booleans.ensureCapacity(new boolean[] {true}, 2, 1))
+ .isEqualTo(new boolean[] {true, false, false});
}
public void testEnsureCapacity_fail() {
@@ -150,10 +154,10 @@ public class BooleansTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Booleans.join(",", EMPTY));
- assertEquals("false", Booleans.join(",", ARRAY_FALSE));
- assertEquals("false,true", Booleans.join(",", false, true));
- assertEquals("falsetruefalse", Booleans.join("", false, true, false));
+ assertThat(Booleans.join(",", EMPTY)).isEmpty();
+ assertThat(Booleans.join(",", ARRAY_FALSE)).isEqualTo("false");
+ assertThat(Booleans.join(",", false, true)).isEqualTo("false,true");
+ assertThat(Booleans.join("", false, true, false)).isEqualTo("falsetruefalse");
}
public void testLexicographicalComparator() {
@@ -172,10 +176,11 @@ public class BooleansTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<boolean[]> comparator = Booleans.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -189,14 +194,14 @@ public class BooleansTest extends TestCase {
private static void testReverse(boolean[] input, boolean[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Booleans.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
boolean[] input, int fromIndex, int toIndex, boolean[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Booleans.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -209,20 +214,251 @@ public class BooleansTest extends TestCase {
new boolean[] {true, true, false, false}, 1, 3, new boolean[] {true, false, true, false});
}
+ private static void testRotate(boolean[] input, int distance, boolean[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Booleans.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ boolean[] input, int distance, int fromIndex, int toIndex, boolean[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Booleans.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new boolean[] {}, -1, new boolean[] {});
+ testRotate(new boolean[] {}, 0, new boolean[] {});
+ testRotate(new boolean[] {}, 1, new boolean[] {});
+
+ testRotate(new boolean[] {true}, -2, new boolean[] {true});
+ testRotate(new boolean[] {true}, -1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 0, new boolean[] {true});
+ testRotate(new boolean[] {true}, 1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 2, new boolean[] {true});
+
+ testRotate(new boolean[] {true, false}, -3, new boolean[] {false, true});
+ testRotate(new boolean[] {true, false}, -1, new boolean[] {false, true});
+ testRotate(new boolean[] {true, false}, -2, new boolean[] {true, false});
+ testRotate(new boolean[] {true, false}, 0, new boolean[] {true, false});
+ testRotate(new boolean[] {true, false}, 1, new boolean[] {false, true});
+ testRotate(new boolean[] {true, false}, 2, new boolean[] {true, false});
+ testRotate(new boolean[] {true, false}, 3, new boolean[] {false, true});
+
+ testRotate(new boolean[] {true, false, true}, -5, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, -4, new boolean[] {false, true, true});
+ testRotate(new boolean[] {true, false, true}, -3, new boolean[] {true, false, true});
+ testRotate(new boolean[] {true, false, true}, -2, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, -1, new boolean[] {false, true, true});
+ testRotate(new boolean[] {true, false, true}, 0, new boolean[] {true, false, true});
+ testRotate(new boolean[] {true, false, true}, 1, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, 2, new boolean[] {false, true, true});
+ testRotate(new boolean[] {true, false, true}, 3, new boolean[] {true, false, true});
+ testRotate(new boolean[] {true, false, true}, 4, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, 5, new boolean[] {false, true, true});
+
+ testRotate(
+ new boolean[] {true, false, true, false}, -9, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, -5, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, -1, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, 0, new boolean[] {true, false, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false}, 1, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, 5, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, 9, new boolean[] {false, true, false, true});
+
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -6,
+ new boolean[] {false, true, false, true, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -4,
+ new boolean[] {true, true, false, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -3,
+ new boolean[] {false, true, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -1,
+ new boolean[] {false, true, false, true, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 0,
+ new boolean[] {true, false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 1,
+ new boolean[] {true, true, false, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 3,
+ new boolean[] {true, false, true, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 4,
+ new boolean[] {false, true, false, true, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 6,
+ new boolean[] {true, true, false, true, false});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new boolean[] {}, 0, 0, 0, new boolean[] {});
+
+ testRotate(new boolean[] {true}, 0, 0, 1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 1, 0, 1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 1, 1, 1, new boolean[] {true});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -6,
+ 1,
+ 6,
+ new boolean[] {false, false, true, false, true, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -1,
+ 1,
+ 6,
+ new boolean[] {false, false, true, false, true, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 0,
+ 1,
+ 6,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 5,
+ 1,
+ 6,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 14,
+ 1,
+ 6,
+ new boolean[] {false, false, true, false, true, true, false});
+
+ // Rotate the first three elements
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -2,
+ 0,
+ 3,
+ new boolean[] {false, false, true, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -1,
+ 0,
+ 3,
+ new boolean[] {true, false, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 0,
+ 0,
+ 3,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 1,
+ 0,
+ 3,
+ new boolean[] {false, false, true, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 2,
+ 0,
+ 3,
+ new boolean[] {true, false, false, true, false, true, false});
+
+ // Rotate the last four elements
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -6,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -5,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -4,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -3,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -2,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -1,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 0,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 1,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 2,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 3,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ }
+
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Boolean> none = Arrays.<Boolean>asList();
- assertTrue(Arrays.equals(EMPTY, Booleans.toArray(none)));
+ assertThat(Booleans.toArray(none)).isEqualTo(EMPTY);
List<Boolean> one = Arrays.asList(false);
- assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.toArray(one)));
+ assertThat(Booleans.toArray(one)).isEqualTo(ARRAY_FALSE);
boolean[] array = {false, false, true};
List<Boolean> three = Arrays.asList(false, false, true);
- assertTrue(Arrays.equals(array, Booleans.toArray(three)));
+ assertThat(Booleans.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Booleans.toArray(Booleans.asList(array))));
+ assertThat(Booleans.toArray(Booleans.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -236,16 +472,16 @@ public class BooleansTest extends TestCase {
Collection<Boolean> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
boolean[] arr = Booleans.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Boolean> list = Arrays.asList(false, true, null);
+ List<@Nullable Boolean> list = Arrays.asList(false, true, null);
try {
Booleans.toArray(list);
fail();
@@ -253,72 +489,80 @@ public class BooleansTest extends TestCase {
}
}
+ @SuppressWarnings({"CollectionIsEmptyTruth", "CollectionIsNotEmptyTruth"})
public void testAsListIsEmpty() {
- assertTrue(Booleans.asList(EMPTY).isEmpty());
- assertFalse(Booleans.asList(ARRAY_FALSE).isEmpty());
+ assertThat(Booleans.asList(EMPTY).isEmpty()).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE).isEmpty()).isFalse();
}
+ @SuppressWarnings("CollectionSizeTruth")
public void testAsListSize() {
- assertEquals(0, Booleans.asList(EMPTY).size());
- assertEquals(1, Booleans.asList(ARRAY_FALSE).size());
- assertEquals(2, Booleans.asList(ARRAY_FALSE_TRUE).size());
+ assertThat(Booleans.asList(EMPTY).size()).isEqualTo(0);
+ assertThat(Booleans.asList(ARRAY_FALSE).size()).isEqualTo(1);
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).size()).isEqualTo(2);
}
+ @SuppressWarnings("BooleanArrayIndexOfBoolean")
public void testAsListIndexOf() {
- assertEquals(-1, Booleans.asList(EMPTY).indexOf((Object) "wrong type"));
- assertEquals(-1, Booleans.asList(EMPTY).indexOf(true));
- assertEquals(-1, Booleans.asList(ARRAY_FALSE).indexOf(true));
- assertEquals(0, Booleans.asList(ARRAY_FALSE).indexOf(false));
- assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).indexOf(true));
+ assertThat(Booleans.asList(EMPTY).indexOf((Object) "wrong type")).isEqualTo(-1);
+ assertThat(Booleans.asList(EMPTY).indexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE).indexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE).indexOf(false)).isEqualTo(0);
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).indexOf(true)).isEqualTo(1);
}
public void testAsListLastIndexOf() {
- assertEquals(-1, Booleans.asList(EMPTY).lastIndexOf((Object) "wrong type"));
- assertEquals(-1, Booleans.asList(EMPTY).lastIndexOf(true));
- assertEquals(-1, Booleans.asList(ARRAY_FALSE).lastIndexOf(true));
- assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true));
- assertEquals(1, Booleans.asList(ARRAY_FALSE_FALSE).lastIndexOf(false));
+ assertThat(Booleans.asList(EMPTY).lastIndexOf((Object) "wrong type")).isEqualTo(-1);
+ assertThat(Booleans.asList(EMPTY).lastIndexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE).lastIndexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true)).isEqualTo(1);
+ assertThat(Booleans.asList(ARRAY_FALSE_FALSE).lastIndexOf(false)).isEqualTo(1);
}
+ @SuppressWarnings({"BooleanArrayContainsBoolean", "CollectionDoesNotContainTruth"})
public void testAsListContains() {
- assertFalse(Booleans.asList(EMPTY).contains((Object) "wrong type"));
- assertFalse(Booleans.asList(EMPTY).contains(true));
- assertFalse(Booleans.asList(ARRAY_FALSE).contains(true));
- assertTrue(Booleans.asList(ARRAY_TRUE).contains(true));
- assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(false));
- assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(true));
+ assertThat(Booleans.asList(EMPTY).contains((Object) "wrong type")).isFalse();
+ assertThat(Booleans.asList(EMPTY).contains(true)).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE).contains(true)).isFalse();
+ assertThat(Booleans.asList(ARRAY_TRUE).contains(true)).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).contains(false)).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).contains(true)).isTrue();
}
public void testAsListEquals() {
- assertEquals(Booleans.asList(EMPTY), Collections.emptyList());
- assertEquals(Booleans.asList(ARRAY_FALSE), Booleans.asList(ARRAY_FALSE));
- assertFalse(Booleans.asList(ARRAY_FALSE).equals(ARRAY_FALSE));
- assertFalse(Booleans.asList(ARRAY_FALSE).equals(null));
- assertFalse(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)));
- assertFalse(Booleans.asList(ARRAY_FALSE_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)));
+ assertThat(Booleans.asList(EMPTY).equals(Collections.emptyList())).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE))).isTrue();
+ @SuppressWarnings("EqualsIncompatibleType")
+ boolean listEqualsArray = Booleans.asList(ARRAY_FALSE).equals(ARRAY_FALSE);
+ assertThat(listEqualsArray).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE).equals(null)).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE))).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)))
+ .isFalse();
assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true));
List<Boolean> reference = Booleans.asList(ARRAY_FALSE);
assertEquals(Booleans.asList(ARRAY_FALSE), reference);
// Explicitly call `equals`; `assertEquals` might return fast
- assertTrue(reference.equals(reference));
+ assertThat(reference.equals(reference)).isTrue();
}
public void testAsListHashcode() {
- assertEquals(1, Booleans.asList(EMPTY).hashCode());
- assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), Booleans.asList(ARRAY_FALSE).hashCode());
+ assertThat(Booleans.asList(EMPTY).hashCode()).isEqualTo(1);
+ assertThat(Booleans.asList(ARRAY_FALSE).hashCode())
+ .isEqualTo(Booleans.asList(ARRAY_FALSE).hashCode());
List<Boolean> reference = Booleans.asList(ARRAY_FALSE);
- assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), reference.hashCode());
+ assertThat(reference.hashCode()).isEqualTo(Booleans.asList(ARRAY_FALSE).hashCode());
}
public void testAsListToString() {
- assertEquals("[false]", Booleans.asList(ARRAY_FALSE).toString());
- assertEquals("[false, true]", Booleans.asList(ARRAY_FALSE_TRUE).toString());
+ assertThat(Booleans.asList(ARRAY_FALSE).toString()).isEqualTo("[false]");
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).toString()).isEqualTo("[false, true]");
}
public void testAsListSet() {
List<Boolean> list = Booleans.asList(ARRAY_FALSE);
- assertFalse(list.set(0, true));
- assertTrue(list.set(0, false));
+ assertThat(list.set(0, true)).isFalse();
+ assertThat(list.set(0, false)).isTrue();
try {
list.set(0, null);
fail();
@@ -331,14 +575,29 @@ public class BooleansTest extends TestCase {
}
}
+ public void testAsListCanonicalValues() {
+ List<Boolean> list = Booleans.asList(true, false);
+ assertThat(list.get(0)).isSameInstanceAs(true);
+ assertThat(list.get(1)).isSameInstanceAs(false);
+ @SuppressWarnings("deprecation")
+ Boolean anotherTrue = new Boolean(true);
+ @SuppressWarnings("deprecation")
+ Boolean anotherFalse = new Boolean(false);
+ list.set(0, anotherTrue);
+ assertThat(list.get(0)).isSameInstanceAs(true);
+ list.set(1, anotherFalse);
+ assertThat(list.get(1)).isSameInstanceAs(false);
+ }
+
public void testCountTrue() {
- assertEquals(0, Booleans.countTrue());
- assertEquals(0, Booleans.countTrue(false));
- assertEquals(1, Booleans.countTrue(true));
- assertEquals(3, Booleans.countTrue(false, true, false, true, false, true));
- assertEquals(1, Booleans.countTrue(false, false, true, false, false));
+ assertThat(Booleans.countTrue()).isEqualTo(0);
+ assertThat(Booleans.countTrue(false)).isEqualTo(0);
+ assertThat(Booleans.countTrue(true)).isEqualTo(1);
+ assertThat(Booleans.countTrue(false, true, false, true, false, true)).isEqualTo(3);
+ assertThat(Booleans.countTrue(false, false, true, false, false)).isEqualTo(1);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Booleans.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java
index c3d0be1ab..c7e693655 100644
--- a/android/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class ByteArrayAsListTest extends TestCase {
return Bytes.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Byte>> builders =
diff --git a/android/guava-tests/test/com/google/common/primitives/BytesTest.java b/android/guava-tests/test/com/google/common/primitives/BytesTest.java
index 233a0150c..55302d7bc 100644
--- a/android/guava-tests/test/com/google/common/primitives/BytesTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/BytesTest.java
@@ -16,8 +16,11 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import java.util.Arrays;
@@ -25,12 +28,14 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Bytes}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class BytesTest extends TestCase {
private static final byte[] EMPTY = {};
@@ -41,97 +46,97 @@ public class BytesTest extends TestCase {
public void testHashCode() {
for (byte value : VALUES) {
- assertEquals(((Byte) value).hashCode(), Bytes.hashCode(value));
+ assertThat(Bytes.hashCode(value)).isEqualTo(((Byte) value).hashCode());
}
}
public void testContains() {
- assertFalse(Bytes.contains(EMPTY, (byte) 1));
- assertFalse(Bytes.contains(ARRAY1, (byte) 2));
- assertFalse(Bytes.contains(ARRAY234, (byte) 1));
- assertTrue(Bytes.contains(new byte[] {(byte) -1}, (byte) -1));
- assertTrue(Bytes.contains(ARRAY234, (byte) 2));
- assertTrue(Bytes.contains(ARRAY234, (byte) 3));
- assertTrue(Bytes.contains(ARRAY234, (byte) 4));
+ assertThat(Bytes.contains(EMPTY, (byte) 1)).isFalse();
+ assertThat(Bytes.contains(ARRAY1, (byte) 2)).isFalse();
+ assertThat(Bytes.contains(ARRAY234, (byte) 1)).isFalse();
+ assertThat(Bytes.contains(new byte[] {(byte) -1}, (byte) -1)).isTrue();
+ assertThat(Bytes.contains(ARRAY234, (byte) 2)).isTrue();
+ assertThat(Bytes.contains(ARRAY234, (byte) 3)).isTrue();
+ assertThat(Bytes.contains(ARRAY234, (byte) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Bytes.indexOf(EMPTY, (byte) 1));
- assertEquals(-1, Bytes.indexOf(ARRAY1, (byte) 2));
- assertEquals(-1, Bytes.indexOf(ARRAY234, (byte) 1));
- assertEquals(0, Bytes.indexOf(new byte[] {(byte) -1}, (byte) -1));
- assertEquals(0, Bytes.indexOf(ARRAY234, (byte) 2));
- assertEquals(1, Bytes.indexOf(ARRAY234, (byte) 3));
- assertEquals(2, Bytes.indexOf(ARRAY234, (byte) 4));
- assertEquals(1, Bytes.indexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3));
+ assertThat(Bytes.indexOf(EMPTY, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY1, (byte) 2)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(new byte[] {(byte) -1}, (byte) -1)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 2)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 3)).isEqualTo(1);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 4)).isEqualTo(2);
+ assertThat(Bytes.indexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Bytes.indexOf(EMPTY, EMPTY));
- assertEquals(0, Bytes.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Bytes.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Bytes.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Bytes.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Bytes.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Bytes.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Bytes.indexOf(ARRAY234, new byte[] {(byte) 2, (byte) 3}));
- assertEquals(1, Bytes.indexOf(ARRAY234, new byte[] {(byte) 3, (byte) 4}));
- assertEquals(1, Bytes.indexOf(ARRAY234, new byte[] {(byte) 3}));
- assertEquals(2, Bytes.indexOf(ARRAY234, new byte[] {(byte) 4}));
- assertEquals(
- 1,
- Bytes.indexOf(
- new byte[] {(byte) 2, (byte) 3, (byte) 3, (byte) 3, (byte) 3}, new byte[] {(byte) 3}));
- assertEquals(
- 2,
- Bytes.indexOf(
- new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3},
- new byte[] {(byte) 2, (byte) 3, (byte) 4}));
- assertEquals(
- 1,
- Bytes.indexOf(
- new byte[] {(byte) 2, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3, (byte) 4},
- new byte[] {(byte) 2, (byte) 3, (byte) 4}));
- assertEquals(
- -1,
- Bytes.indexOf(
- new byte[] {(byte) 4, (byte) 3, (byte) 2}, new byte[] {(byte) 2, (byte) 3, (byte) 4}));
+ assertThat(Bytes.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Bytes.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 2, (byte) 3})).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 3, (byte) 4})).isEqualTo(1);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 3})).isEqualTo(1);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 4})).isEqualTo(2);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 2, (byte) 3, (byte) 3, (byte) 3, (byte) 3},
+ new byte[] {(byte) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3},
+ new byte[] {(byte) 2, (byte) 3, (byte) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 2, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3, (byte) 4},
+ new byte[] {(byte) 2, (byte) 3, (byte) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 4, (byte) 3, (byte) 2},
+ new byte[] {(byte) 2, (byte) 3, (byte) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Bytes.lastIndexOf(EMPTY, (byte) 1));
- assertEquals(-1, Bytes.lastIndexOf(ARRAY1, (byte) 2));
- assertEquals(-1, Bytes.lastIndexOf(ARRAY234, (byte) 1));
- assertEquals(0, Bytes.lastIndexOf(new byte[] {(byte) -1}, (byte) -1));
- assertEquals(0, Bytes.lastIndexOf(ARRAY234, (byte) 2));
- assertEquals(1, Bytes.lastIndexOf(ARRAY234, (byte) 3));
- assertEquals(2, Bytes.lastIndexOf(ARRAY234, (byte) 4));
- assertEquals(
- 3, Bytes.lastIndexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3));
+ assertThat(Bytes.lastIndexOf(EMPTY, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.lastIndexOf(ARRAY1, (byte) 2)).isEqualTo(-1);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.lastIndexOf(new byte[] {(byte) -1}, (byte) -1)).isEqualTo(0);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 2)).isEqualTo(0);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 3)).isEqualTo(1);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 4)).isEqualTo(2);
+ assertThat(Bytes.lastIndexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3))
+ .isEqualTo(3);
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Bytes.concat()));
- assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Bytes.concat(ARRAY1)));
- assertNotSame(ARRAY1, Bytes.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Bytes.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 1, (byte) 1, (byte) 1}, Bytes.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 1, (byte) 2, (byte) 3, (byte) 4}, Bytes.concat(ARRAY1, ARRAY234)));
+ assertThat(Bytes.concat()).isEqualTo(EMPTY);
+ assertThat(Bytes.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Bytes.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Bytes.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Bytes.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Bytes.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Bytes.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new byte[] {(byte) 1, (byte) 1, (byte) 1});
+ assertThat(Bytes.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new byte[] {(byte) 1, (byte) 2, (byte) 3, (byte) 4});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Bytes.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 1, (byte) 0, (byte) 0}, Bytes.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Bytes.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Bytes.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Bytes.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Bytes.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new byte[] {(byte) 1, (byte) 0, (byte) 0});
}
public void testEnsureCapacity_fail() {
@@ -151,17 +156,17 @@ public class BytesTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Byte> none = Arrays.<Byte>asList();
- assertTrue(Arrays.equals(EMPTY, Bytes.toArray(none)));
+ assertThat(Bytes.toArray(none)).isEqualTo(EMPTY);
List<Byte> one = Arrays.asList((byte) 1);
- assertTrue(Arrays.equals(ARRAY1, Bytes.toArray(one)));
+ assertThat(Bytes.toArray(one)).isEqualTo(ARRAY1);
byte[] array = {(byte) 0, (byte) 1, (byte) 0x55};
List<Byte> three = Arrays.asList((byte) 0, (byte) 1, (byte) 0x55);
- assertTrue(Arrays.equals(array, Bytes.toArray(three)));
+ assertThat(Bytes.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Bytes.toArray(Bytes.asList(array))));
+ assertThat(Bytes.toArray(Bytes.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -171,16 +176,16 @@ public class BytesTest extends TestCase {
Collection<Byte> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
byte[] arr = Bytes.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Byte> list = Arrays.asList((byte) 0, (byte) 1, null);
+ List<@Nullable Byte> list = Arrays.asList((byte) 0, (byte) 1, null);
try {
Bytes.toArray(list);
fail();
@@ -198,21 +203,22 @@ public class BytesTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Bytes.toArray(bytes)));
- assertTrue(Arrays.equals(array, Bytes.toArray(shorts)));
- assertTrue(Arrays.equals(array, Bytes.toArray(ints)));
- assertTrue(Arrays.equals(array, Bytes.toArray(floats)));
- assertTrue(Arrays.equals(array, Bytes.toArray(longs)));
- assertTrue(Arrays.equals(array, Bytes.toArray(doubles)));
+ assertThat(Bytes.toArray(bytes)).isEqualTo(array);
+ assertThat(Bytes.toArray(shorts)).isEqualTo(array);
+ assertThat(Bytes.toArray(ints)).isEqualTo(array);
+ assertThat(Bytes.toArray(floats)).isEqualTo(array);
+ assertThat(Bytes.toArray(longs)).isEqualTo(array);
+ assertThat(Bytes.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // TODO(b/278877942): Enable
public void testAsList_isAView() {
byte[] array = {(byte) 0, (byte) 1};
List<Byte> list = Bytes.asList(array);
list.set(0, (byte) 2);
- assertTrue(Arrays.equals(new byte[] {(byte) 2, (byte) 1}, array));
+ assertThat(array).isEqualTo(new byte[] {(byte) 2, (byte) 1});
array[1] = (byte) 3;
- assertEquals(Arrays.asList((byte) 2, (byte) 3), list);
+ assertThat(list).containsExactly((byte) 2, (byte) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -222,21 +228,21 @@ public class BytesTest extends TestCase {
// Make sure it returned a copy
list.set(0, (byte) 4);
- assertTrue(Arrays.equals(new byte[] {(byte) 0, (byte) 1, (byte) 2}, newArray));
+ assertThat(newArray).isEqualTo(new byte[] {(byte) 0, (byte) 1, (byte) 2});
newArray[1] = (byte) 5;
- assertEquals((byte) 1, (byte) list.get(1));
+ assertThat((byte) list.get(1)).isEqualTo((byte) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
byte[] array = {(byte) 0, (byte) 1, (byte) 2, (byte) 3};
List<Byte> list = Bytes.asList(array);
- assertTrue(Arrays.equals(new byte[] {(byte) 1, (byte) 2}, Bytes.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new byte[] {}, Bytes.toArray(list.subList(2, 2))));
+ assertThat(Bytes.toArray(list.subList(1, 3))).isEqualTo(new byte[] {(byte) 1, (byte) 2});
+ assertThat(Bytes.toArray(list.subList(2, 2))).isEqualTo(new byte[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Bytes.asList(EMPTY));
+ assertThat(Bytes.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
public void testReverse() {
@@ -250,13 +256,13 @@ public class BytesTest extends TestCase {
private static void testReverse(byte[] input, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Bytes.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(byte[] input, int fromIndex, int toIndex, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Bytes.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -268,6 +274,104 @@ public class BytesTest extends TestCase {
testReverse(new byte[] {-1, 1, -2, 2}, 1, 3, new byte[] {-1, -2, 1, 2});
}
+ private static void testRotate(byte[] input, int distance, byte[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Bytes.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ byte[] input, int distance, int fromIndex, int toIndex, byte[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Bytes.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new byte[] {}, -1, new byte[] {});
+ testRotate(new byte[] {}, 0, new byte[] {});
+ testRotate(new byte[] {}, 1, new byte[] {});
+
+ testRotate(new byte[] {1}, -2, new byte[] {1});
+ testRotate(new byte[] {1}, -1, new byte[] {1});
+ testRotate(new byte[] {1}, 0, new byte[] {1});
+ testRotate(new byte[] {1}, 1, new byte[] {1});
+ testRotate(new byte[] {1}, 2, new byte[] {1});
+
+ testRotate(new byte[] {1, 2}, -3, new byte[] {2, 1});
+ testRotate(new byte[] {1, 2}, -1, new byte[] {2, 1});
+ testRotate(new byte[] {1, 2}, -2, new byte[] {1, 2});
+ testRotate(new byte[] {1, 2}, 0, new byte[] {1, 2});
+ testRotate(new byte[] {1, 2}, 1, new byte[] {2, 1});
+ testRotate(new byte[] {1, 2}, 2, new byte[] {1, 2});
+ testRotate(new byte[] {1, 2}, 3, new byte[] {2, 1});
+
+ testRotate(new byte[] {1, 2, 3}, -5, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, -4, new byte[] {2, 3, 1});
+ testRotate(new byte[] {1, 2, 3}, -3, new byte[] {1, 2, 3});
+ testRotate(new byte[] {1, 2, 3}, -2, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, -1, new byte[] {2, 3, 1});
+ testRotate(new byte[] {1, 2, 3}, 0, new byte[] {1, 2, 3});
+ testRotate(new byte[] {1, 2, 3}, 1, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, 2, new byte[] {2, 3, 1});
+ testRotate(new byte[] {1, 2, 3}, 3, new byte[] {1, 2, 3});
+ testRotate(new byte[] {1, 2, 3}, 4, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, 5, new byte[] {2, 3, 1});
+
+ testRotate(new byte[] {1, 2, 3, 4}, -9, new byte[] {2, 3, 4, 1});
+ testRotate(new byte[] {1, 2, 3, 4}, -5, new byte[] {2, 3, 4, 1});
+ testRotate(new byte[] {1, 2, 3, 4}, -1, new byte[] {2, 3, 4, 1});
+ testRotate(new byte[] {1, 2, 3, 4}, 0, new byte[] {1, 2, 3, 4});
+ testRotate(new byte[] {1, 2, 3, 4}, 1, new byte[] {4, 1, 2, 3});
+ testRotate(new byte[] {1, 2, 3, 4}, 5, new byte[] {4, 1, 2, 3});
+ testRotate(new byte[] {1, 2, 3, 4}, 9, new byte[] {4, 1, 2, 3});
+
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -6, new byte[] {2, 3, 4, 5, 1});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -4, new byte[] {5, 1, 2, 3, 4});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -3, new byte[] {4, 5, 1, 2, 3});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -1, new byte[] {2, 3, 4, 5, 1});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 0, new byte[] {1, 2, 3, 4, 5});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 1, new byte[] {5, 1, 2, 3, 4});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 3, new byte[] {3, 4, 5, 1, 2});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 4, new byte[] {2, 3, 4, 5, 1});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 6, new byte[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new byte[] {}, 0, 0, 0, new byte[] {});
+
+ testRotate(new byte[] {1}, 0, 0, 1, new byte[] {1});
+ testRotate(new byte[] {1}, 1, 0, 1, new byte[] {1});
+ testRotate(new byte[] {1}, 1, 1, 1, new byte[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new byte[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new byte[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new byte[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new byte[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new byte[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new byte[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new byte[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new byte[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new byte[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new byte[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new byte[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new byte[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new byte[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new byte[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new byte[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Bytes.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java
index fa2a53dab..7e521f1a7 100644
--- a/android/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class CharArrayAsListTest extends TestCase {
return Chars.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Character>> builders =
diff --git a/android/guava-tests/test/com/google/common/primitives/CharsTest.java b/android/guava-tests/test/com/google/common/primitives/CharsTest.java
index f1da7fd8e..7a6280f30 100644
--- a/android/guava-tests/test/com/google/common/primitives/CharsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/CharsTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -28,6 +32,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Chars}.
@@ -35,6 +40,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class CharsTest extends TestCase {
private static final char[] EMPTY = {};
@@ -48,13 +54,13 @@ public class CharsTest extends TestCase {
public void testHashCode() {
for (char value : VALUES) {
- assertEquals(((Character) value).hashCode(), Chars.hashCode(value));
+ assertThat(Chars.hashCode(value)).isEqualTo(((Character) value).hashCode());
}
}
public void testCheckedCast() {
for (char value : VALUES) {
- assertEquals(value, Chars.checkedCast((long) value));
+ assertThat(Chars.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -64,12 +70,12 @@ public class CharsTest extends TestCase {
public void testSaturatedCast() {
for (char value : VALUES) {
- assertEquals(value, Chars.saturatedCast((long) value));
+ assertThat(Chars.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, Chars.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, Chars.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, Chars.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, Chars.saturatedCast(Long.MIN_VALUE));
+ assertThat(Chars.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(Chars.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(Chars.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(Chars.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private void assertCastFails(long value) {
@@ -77,84 +83,90 @@ public class CharsTest extends TestCase {
Chars.checkedCast(value);
fail("Cast to char should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
+ @J2ktIncompatible // TODO(b/285538920): Fix and enable.
public void testCompare() {
for (char x : VALUES) {
for (char y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Character.valueOf(x).compareTo(y), Chars.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Chars.compare(x, y))
+ .isEqualTo(Character.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Chars.contains(EMPTY, (char) 1));
- assertFalse(Chars.contains(ARRAY1, (char) 2));
- assertFalse(Chars.contains(ARRAY234, (char) 1));
- assertTrue(Chars.contains(new char[] {(char) -1}, (char) -1));
- assertTrue(Chars.contains(ARRAY234, (char) 2));
- assertTrue(Chars.contains(ARRAY234, (char) 3));
- assertTrue(Chars.contains(ARRAY234, (char) 4));
+ assertThat(Chars.contains(EMPTY, (char) 1)).isFalse();
+ assertThat(Chars.contains(ARRAY1, (char) 2)).isFalse();
+ assertThat(Chars.contains(ARRAY234, (char) 1)).isFalse();
+ assertThat(Chars.contains(new char[] {(char) -1}, (char) -1)).isTrue();
+ assertThat(Chars.contains(ARRAY234, (char) 2)).isTrue();
+ assertThat(Chars.contains(ARRAY234, (char) 3)).isTrue();
+ assertThat(Chars.contains(ARRAY234, (char) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Chars.indexOf(EMPTY, (char) 1));
- assertEquals(-1, Chars.indexOf(ARRAY1, (char) 2));
- assertEquals(-1, Chars.indexOf(ARRAY234, (char) 1));
- assertEquals(0, Chars.indexOf(new char[] {(char) -1}, (char) -1));
- assertEquals(0, Chars.indexOf(ARRAY234, (char) 2));
- assertEquals(1, Chars.indexOf(ARRAY234, (char) 3));
- assertEquals(2, Chars.indexOf(ARRAY234, (char) 4));
- assertEquals(1, Chars.indexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3));
+ assertThat(Chars.indexOf(EMPTY, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY1, (char) 2)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY234, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.indexOf(new char[] {(char) -1}, (char) -1)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, (char) 2)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, (char) 3)).isEqualTo(1);
+ assertThat(Chars.indexOf(ARRAY234, (char) 4)).isEqualTo(2);
+ assertThat(Chars.indexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Chars.indexOf(EMPTY, EMPTY));
- assertEquals(0, Chars.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Chars.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Chars.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Chars.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Chars.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Chars.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Chars.indexOf(ARRAY234, new char[] {(char) 2, (char) 3}));
- assertEquals(1, Chars.indexOf(ARRAY234, new char[] {(char) 3, (char) 4}));
- assertEquals(1, Chars.indexOf(ARRAY234, new char[] {(char) 3}));
- assertEquals(2, Chars.indexOf(ARRAY234, new char[] {(char) 4}));
- assertEquals(
- 1,
- Chars.indexOf(
- new char[] {(char) 2, (char) 3, (char) 3, (char) 3, (char) 3}, new char[] {(char) 3}));
- assertEquals(
- 2,
- Chars.indexOf(
- new char[] {(char) 2, (char) 3, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3},
- new char[] {(char) 2, (char) 3, (char) 4}));
- assertEquals(
- 1,
- Chars.indexOf(
- new char[] {(char) 2, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3, (char) 4},
- new char[] {(char) 2, (char) 3, (char) 4}));
- assertEquals(
- -1,
- Chars.indexOf(
- new char[] {(char) 4, (char) 3, (char) 2}, new char[] {(char) 2, (char) 3, (char) 4}));
+ assertThat(Chars.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Chars.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 2, (char) 3})).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 3, (char) 4})).isEqualTo(1);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 3})).isEqualTo(1);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 4})).isEqualTo(2);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 2, (char) 3, (char) 3, (char) 3, (char) 3},
+ new char[] {(char) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 2, (char) 3, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3},
+ new char[] {(char) 2, (char) 3, (char) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 2, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3, (char) 4},
+ new char[] {(char) 2, (char) 3, (char) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 4, (char) 3, (char) 2},
+ new char[] {(char) 2, (char) 3, (char) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Chars.lastIndexOf(EMPTY, (char) 1));
- assertEquals(-1, Chars.lastIndexOf(ARRAY1, (char) 2));
- assertEquals(-1, Chars.lastIndexOf(ARRAY234, (char) 1));
- assertEquals(0, Chars.lastIndexOf(new char[] {(char) -1}, (char) -1));
- assertEquals(0, Chars.lastIndexOf(ARRAY234, (char) 2));
- assertEquals(1, Chars.lastIndexOf(ARRAY234, (char) 3));
- assertEquals(2, Chars.lastIndexOf(ARRAY234, (char) 4));
- assertEquals(
- 3, Chars.lastIndexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3));
+ assertThat(Chars.lastIndexOf(EMPTY, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.lastIndexOf(ARRAY1, (char) 2)).isEqualTo(-1);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.lastIndexOf(new char[] {(char) -1}, (char) -1)).isEqualTo(0);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 2)).isEqualTo(0);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 3)).isEqualTo(1);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 4)).isEqualTo(2);
+ assertThat(Chars.lastIndexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3))
+ .isEqualTo(3);
}
public void testMax_noArgs() {
@@ -166,10 +178,10 @@ public class CharsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Chars.max(LEAST));
- assertEquals(GREATEST, Chars.max(GREATEST));
- assertEquals(
- (char) 9, Chars.max((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9));
+ assertThat(Chars.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Chars.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Chars.max((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9))
+ .isEqualTo((char) 9);
}
public void testMin_noArgs() {
@@ -181,18 +193,18 @@ public class CharsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Chars.min(LEAST));
- assertEquals(GREATEST, Chars.min(GREATEST));
- assertEquals(
- (char) 0, Chars.min((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9));
+ assertThat(Chars.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Chars.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Chars.min((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9))
+ .isEqualTo((char) 0);
}
public void testConstrainToRange() {
- assertEquals((char) 1, Chars.constrainToRange((char) 1, (char) 0, (char) 5));
- assertEquals((char) 1, Chars.constrainToRange((char) 1, (char) 1, (char) 5));
- assertEquals((char) 3, Chars.constrainToRange((char) 1, (char) 3, (char) 5));
- assertEquals((char) 254, Chars.constrainToRange((char) 255, (char) 250, (char) 254));
- assertEquals((char) 2, Chars.constrainToRange((char) 5, (char) 2, (char) 2));
+ assertThat(Chars.constrainToRange((char) 1, (char) 0, (char) 5)).isEqualTo((char) 1);
+ assertThat(Chars.constrainToRange((char) 1, (char) 1, (char) 5)).isEqualTo((char) 1);
+ assertThat(Chars.constrainToRange((char) 1, (char) 3, (char) 5)).isEqualTo((char) 3);
+ assertThat(Chars.constrainToRange((char) 255, (char) 250, (char) 254)).isEqualTo((char) 254);
+ assertThat(Chars.constrainToRange((char) 5, (char) 2, (char) 2)).isEqualTo((char) 2);
try {
Chars.constrainToRange((char) 1, (char) 3, (char) 2);
fail();
@@ -201,26 +213,26 @@ public class CharsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Chars.concat()));
- assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Chars.concat(ARRAY1)));
- assertNotSame(ARRAY1, Chars.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Chars.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new char[] {(char) 1, (char) 1, (char) 1}, Chars.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new char[] {(char) 1, (char) 2, (char) 3, (char) 4}, Chars.concat(ARRAY1, ARRAY234)));
- }
-
+ assertThat(Chars.concat()).isEqualTo(EMPTY);
+ assertThat(Chars.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Chars.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Chars.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Chars.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Chars.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Chars.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new char[] {(char) 1, (char) 1, (char) 1});
+ assertThat(Chars.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new char[] {(char) 1, (char) 2, (char) 3, (char) 4});
+ }
+
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray
public void testFromByteArray() {
- assertEquals('\u2345', Chars.fromByteArray(new byte[] {0x23, 0x45, (byte) 0xDC}));
- assertEquals('\uFEDC', Chars.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC}));
+ assertThat(Chars.fromByteArray(new byte[] {0x23, 0x45, (byte) 0xDC})).isEqualTo('\u2345');
+ assertThat(Chars.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC})).isEqualTo('\uFEDC');
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray
public void testFromByteArrayFails() {
try {
@@ -230,34 +242,42 @@ public class CharsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromBytes
public void testFromBytes() {
- assertEquals('\u2345', Chars.fromBytes((byte) 0x23, (byte) 0x45));
- assertEquals('\uFEDC', Chars.fromBytes((byte) 0xFE, (byte) 0xDC));
+ assertThat(Chars.fromBytes((byte) 0x23, (byte) 0x45)).isEqualTo('\u2345');
+ assertThat(Chars.fromBytes((byte) 0xFE, (byte) 0xDC)).isEqualTo('\uFEDC');
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray, Chars.toByteArray
public void testByteArrayRoundTrips() {
char c = 0;
for (int hi = 0; hi < 256; hi++) {
for (int lo = 0; lo < 256; lo++) {
char result = Chars.fromByteArray(new byte[] {(byte) hi, (byte) lo});
- assertEquals(
- String.format(
- Locale.ROOT, "hi=%s, lo=%s, expected=%s, result=%s", hi, lo, (int) c, (int) result),
- c,
- result);
+ assertWithMessage(
+ String.format(
+ Locale.ROOT,
+ "hi=%s, lo=%s, expected=%s, result=%s",
+ hi,
+ lo,
+ (int) c,
+ (int) result))
+ .that(result)
+ .isEqualTo(c);
byte[] bytes = Chars.toByteArray(c);
- assertEquals((byte) hi, bytes[0]);
- assertEquals((byte) lo, bytes[1]);
+ assertThat(bytes[0]).isEqualTo((byte) hi);
+ assertThat(bytes[1]).isEqualTo((byte) lo);
c++;
}
}
- assertEquals((char) 0, c); // sanity check
+ assertThat(c).isEqualTo((char) 0); // sanity check
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray, Chars.toByteArray
public void testByteArrayRoundTripsFails() {
try {
@@ -268,12 +288,11 @@ public class CharsTest extends TestCase {
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Chars.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new char[] {(char) 1, (char) 0, (char) 0}, Chars.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Chars.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Chars.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Chars.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Chars.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new char[] {(char) 1, (char) 0, (char) 0});
}
public void testEnsureCapacity_fail() {
@@ -291,10 +310,10 @@ public class CharsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Chars.join(",", EMPTY));
- assertEquals("1", Chars.join(",", '1'));
- assertEquals("1,2", Chars.join(",", '1', '2'));
- assertEquals("123", Chars.join("", '1', '2', '3'));
+ assertThat(Chars.join(",", EMPTY)).isEmpty();
+ assertThat(Chars.join(",", '1')).isEqualTo("1");
+ assertThat(Chars.join(",", '1', '2')).isEqualTo("1,2");
+ assertThat(Chars.join("", '1', '2', '3')).isEqualTo("123");
}
public void testLexicographicalComparator() {
@@ -314,10 +333,11 @@ public class CharsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<char[]> comparator = Chars.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -331,13 +351,13 @@ public class CharsTest extends TestCase {
private static void testReverse(char[] input, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(char[] input, int fromIndex, int toIndex, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -349,6 +369,203 @@ public class CharsTest extends TestCase {
testReverse(new char[] {'A', '1', 'B', '2'}, 1, 3, new char[] {'A', 'B', '1', '2'});
}
+ private static void testRotate(char[] input, int distance, char[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Chars.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ char[] input, int distance, int fromIndex, int toIndex, char[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Chars.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new char[] {}, -1, new char[] {});
+ testRotate(new char[] {}, 0, new char[] {});
+ testRotate(new char[] {}, 1, new char[] {});
+
+ testRotate(new char[] {'1'}, -2, new char[] {'1'});
+ testRotate(new char[] {'1'}, -1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 0, new char[] {'1'});
+ testRotate(new char[] {'1'}, 1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 2, new char[] {'1'});
+
+ testRotate(new char[] {'1', '2'}, -3, new char[] {'2', '1'});
+ testRotate(new char[] {'1', '2'}, -1, new char[] {'2', '1'});
+ testRotate(new char[] {'1', '2'}, -2, new char[] {'1', '2'});
+ testRotate(new char[] {'1', '2'}, 0, new char[] {'1', '2'});
+ testRotate(new char[] {'1', '2'}, 1, new char[] {'2', '1'});
+ testRotate(new char[] {'1', '2'}, 2, new char[] {'1', '2'});
+ testRotate(new char[] {'1', '2'}, 3, new char[] {'2', '1'});
+
+ testRotate(new char[] {'1', '2', '3'}, -5, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, -4, new char[] {'2', '3', '1'});
+ testRotate(new char[] {'1', '2', '3'}, -3, new char[] {'1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3'}, -2, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, -1, new char[] {'2', '3', '1'});
+ testRotate(new char[] {'1', '2', '3'}, 0, new char[] {'1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3'}, 1, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, 2, new char[] {'2', '3', '1'});
+ testRotate(new char[] {'1', '2', '3'}, 3, new char[] {'1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3'}, 4, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, 5, new char[] {'2', '3', '1'});
+
+ testRotate(new char[] {'1', '2', '3', '4'}, -9, new char[] {'2', '3', '4', '1'});
+ testRotate(new char[] {'1', '2', '3', '4'}, -5, new char[] {'2', '3', '4', '1'});
+ testRotate(new char[] {'1', '2', '3', '4'}, -1, new char[] {'2', '3', '4', '1'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 0, new char[] {'1', '2', '3', '4'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 1, new char[] {'4', '1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 5, new char[] {'4', '1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 9, new char[] {'4', '1', '2', '3'});
+
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -6, new char[] {'2', '3', '4', '5', '1'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -4, new char[] {'5', '1', '2', '3', '4'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -3, new char[] {'4', '5', '1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -1, new char[] {'2', '3', '4', '5', '1'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 0, new char[] {'1', '2', '3', '4', '5'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 1, new char[] {'5', '1', '2', '3', '4'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 3, new char[] {'3', '4', '5', '1', '2'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 4, new char[] {'2', '3', '4', '5', '1'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 6, new char[] {'5', '1', '2', '3', '4'});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new char[] {}, 0, 0, 0, new char[] {});
+
+ testRotate(new char[] {'1'}, 0, 0, 1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 1, 0, 1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 1, 1, 1, new char[] {'1'});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -6,
+ 1,
+ 6,
+ new char[] {'0', '2', '3', '4', '5', '1', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -1,
+ 1,
+ 6,
+ new char[] {'0', '2', '3', '4', '5', '1', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 0,
+ 1,
+ 6,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 5,
+ 1,
+ 6,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 14,
+ 1,
+ 6,
+ new char[] {'0', '2', '3', '4', '5', '1', '6'});
+
+ // Rotate the first three elements
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -2,
+ 0,
+ 3,
+ new char[] {'2', '0', '1', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -1,
+ 0,
+ 3,
+ new char[] {'1', '2', '0', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 0,
+ 0,
+ 3,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 1,
+ 0,
+ 3,
+ new char[] {'2', '0', '1', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 2,
+ 0,
+ 3,
+ new char[] {'1', '2', '0', '3', '4', '5', '6'});
+
+ // Rotate the last four elements
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -6,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '5', '6', '3', '4'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -5,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '4', '5', '6', '3'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -4,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -3,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '6', '3', '4', '5'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -2,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '5', '6', '3', '4'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -1,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '4', '5', '6', '3'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 0,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 1,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '6', '3', '4', '5'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 2,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '5', '6', '3', '4'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 3,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '4', '5', '6', '3'});
+ }
+
public void testSortDescending() {
testSortDescending(new char[] {}, new char[] {});
testSortDescending(new char[] {'1'}, new char[] {'1'});
@@ -360,14 +577,14 @@ public class CharsTest extends TestCase {
private static void testSortDescending(char[] input, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
char[] input, int fromIndex, int toIndex, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -382,17 +599,17 @@ public class CharsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Character> none = Arrays.<Character>asList();
- assertTrue(Arrays.equals(EMPTY, Chars.toArray(none)));
+ assertThat(Chars.toArray(none)).isEqualTo(EMPTY);
List<Character> one = Arrays.asList((char) 1);
- assertTrue(Arrays.equals(ARRAY1, Chars.toArray(one)));
+ assertThat(Chars.toArray(one)).isEqualTo(ARRAY1);
char[] array = {(char) 0, (char) 1, 'A'};
List<Character> three = Arrays.asList((char) 0, (char) 1, 'A');
- assertTrue(Arrays.equals(array, Chars.toArray(three)));
+ assertThat(Chars.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Chars.toArray(Chars.asList(array))));
+ assertThat(Chars.toArray(Chars.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -402,16 +619,16 @@ public class CharsTest extends TestCase {
Collection<Character> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
char[] arr = Chars.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Character> list = Arrays.asList((char) 0, (char) 1, null);
+ List<@Nullable Character> list = Arrays.asList((char) 0, (char) 1, null);
try {
Chars.toArray(list);
fail();
@@ -419,13 +636,14 @@ public class CharsTest extends TestCase {
}
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
char[] array = {(char) 0, (char) 1};
List<Character> list = Chars.asList(array);
list.set(0, (char) 2);
- assertTrue(Arrays.equals(new char[] {(char) 2, (char) 1}, array));
+ assertThat(array).isEqualTo(new char[] {(char) 2, (char) 1});
array[1] = (char) 3;
- assertEquals(Arrays.asList((char) 2, (char) 3), list);
+ assertThat(list).containsExactly((char) 2, (char) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -435,23 +653,24 @@ public class CharsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (char) 4);
- assertTrue(Arrays.equals(new char[] {(char) 0, (char) 1, (char) 2}, newArray));
+ assertThat(newArray).isEqualTo(new char[] {(char) 0, (char) 1, (char) 2});
newArray[1] = (char) 5;
- assertEquals((char) 1, (char) list.get(1));
+ assertThat((char) list.get(1)).isEqualTo((char) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
char[] array = {(char) 0, (char) 1, (char) 2, (char) 3};
List<Character> list = Chars.asList(array);
- assertTrue(Arrays.equals(new char[] {(char) 1, (char) 2}, Chars.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new char[] {}, Chars.toArray(list.subList(2, 2))));
+ assertThat(Chars.toArray(list.subList(1, 3))).isEqualTo(new char[] {(char) 1, (char) 2});
+ assertThat(Chars.toArray(list.subList(2, 2))).isEqualTo(new char[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Chars.asList(EMPTY));
+ assertThat(Chars.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Chars.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java
index 23a7ca140..e7cd4f38e 100644
--- a/android/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,12 +49,13 @@ public class DoubleArrayAsListTest extends TestCase {
return Doubles.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Double>> builders =
ImmutableList.of(
ListTestSuiteBuilder.using(new DoublesAsListGenerator()).named("Doubles.asList"),
- ListTestSuiteBuilder.using(new DoublsAsListHeadSubListGenerator())
+ ListTestSuiteBuilder.using(new DoublesAsListHeadSubListGenerator())
.named("Doubles.asList, head subList"),
ListTestSuiteBuilder.using(new DoublesAsListTailSubListGenerator())
.named("Doubles.asList, tail subList"),
@@ -84,7 +86,7 @@ public class DoubleArrayAsListTest extends TestCase {
}
}
- public static final class DoublsAsListHeadSubListGenerator extends TestDoubleListGenerator {
+ public static final class DoublesAsListHeadSubListGenerator extends TestDoubleListGenerator {
@Override
protected List<Double> create(Double[] elements) {
Double[] suffix = {Double.MIN_VALUE, Double.MAX_VALUE};
diff --git a/android/guava-tests/test/com/google/common/primitives/DoublesTest.java b/android/guava-tests/test/com/google/common/primitives/DoublesTest.java
index 871b84c28..2483f42bc 100644
--- a/android/guava-tests/test/com/google/common/primitives/DoublesTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/DoublesTest.java
@@ -17,10 +17,12 @@
package com.google.common.primitives;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Double.NaN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.Helpers;
@@ -33,14 +35,15 @@ import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Doubles}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
-@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class DoublesTest extends TestCase {
private static final double[] EMPTY = {};
private static final double[] ARRAY1 = {(double) 1};
@@ -77,13 +80,14 @@ public class DoublesTest extends TestCase {
public void testHashCode() {
for (double value : VALUES) {
- assertEquals(((Double) value).hashCode(), Doubles.hashCode(value));
+ assertThat(Doubles.hashCode(value)).isEqualTo(((Double) value).hashCode());
}
}
public void testIsFinite() {
for (double value : NUMBERS) {
- assertEquals(!(Double.isNaN(value) || Double.isInfinite(value)), Doubles.isFinite(value));
+ assertThat(Doubles.isFinite(value))
+ .isEqualTo(!(Double.isNaN(value) || Double.isInfinite(value)));
}
}
@@ -91,109 +95,119 @@ public class DoublesTest extends TestCase {
for (double x : VALUES) {
for (double y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Double.valueOf(x).compareTo(y), Doubles.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Doubles.compare(x, y))
+ .isEqualTo(Double.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Doubles.contains(EMPTY, (double) 1));
- assertFalse(Doubles.contains(ARRAY1, (double) 2));
- assertFalse(Doubles.contains(ARRAY234, (double) 1));
- assertTrue(Doubles.contains(new double[] {(double) -1}, (double) -1));
- assertTrue(Doubles.contains(ARRAY234, (double) 2));
- assertTrue(Doubles.contains(ARRAY234, (double) 3));
- assertTrue(Doubles.contains(ARRAY234, (double) 4));
+ assertThat(Doubles.contains(EMPTY, (double) 1)).isFalse();
+ assertThat(Doubles.contains(ARRAY1, (double) 2)).isFalse();
+ assertThat(Doubles.contains(ARRAY234, (double) 1)).isFalse();
+ assertThat(Doubles.contains(new double[] {(double) -1}, (double) -1)).isTrue();
+ assertThat(Doubles.contains(ARRAY234, (double) 2)).isTrue();
+ assertThat(Doubles.contains(ARRAY234, (double) 3)).isTrue();
+ assertThat(Doubles.contains(ARRAY234, (double) 4)).isTrue();
for (double value : NUMBERS) {
- assertTrue("" + value, Doubles.contains(new double[] {5.0, value}, value));
+ assertWithMessage("" + value)
+ .that(Doubles.contains(new double[] {5.0, value}, value))
+ .isTrue();
}
- assertFalse(Doubles.contains(new double[] {5.0, NaN}, NaN));
+ assertThat(Doubles.contains(new double[] {5.0, NaN}, NaN)).isFalse();
}
public void testIndexOf() {
- assertEquals(-1, Doubles.indexOf(EMPTY, (double) 1));
- assertEquals(-1, Doubles.indexOf(ARRAY1, (double) 2));
- assertEquals(-1, Doubles.indexOf(ARRAY234, (double) 1));
- assertEquals(0, Doubles.indexOf(new double[] {(double) -1}, (double) -1));
- assertEquals(0, Doubles.indexOf(ARRAY234, (double) 2));
- assertEquals(1, Doubles.indexOf(ARRAY234, (double) 3));
- assertEquals(2, Doubles.indexOf(ARRAY234, (double) 4));
- assertEquals(
- 1,
- Doubles.indexOf(new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3));
+ assertThat(Doubles.indexOf(EMPTY, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY1, (double) 2)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(new double[] {(double) -1}, (double) -1)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 2)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 3)).isEqualTo(1);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 4)).isEqualTo(2);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3))
+ .isEqualTo(1);
for (double value : NUMBERS) {
- assertEquals("" + value, 1, Doubles.indexOf(new double[] {5.0, value}, value));
+ assertWithMessage("" + value)
+ .that(Doubles.indexOf(new double[] {5.0, value}, value))
+ .isEqualTo(1);
}
- assertEquals(-1, Doubles.indexOf(new double[] {5.0, NaN}, NaN));
+ assertThat(Doubles.indexOf(new double[] {5.0, NaN}, NaN)).isEqualTo(-1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Doubles.indexOf(EMPTY, EMPTY));
- assertEquals(0, Doubles.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Doubles.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Doubles.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Doubles.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Doubles.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Doubles.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Doubles.indexOf(ARRAY234, new double[] {(double) 2, (double) 3}));
- assertEquals(1, Doubles.indexOf(ARRAY234, new double[] {(double) 3, (double) 4}));
- assertEquals(1, Doubles.indexOf(ARRAY234, new double[] {(double) 3}));
- assertEquals(2, Doubles.indexOf(ARRAY234, new double[] {(double) 4}));
- assertEquals(
- 1,
- Doubles.indexOf(
- new double[] {(double) 2, (double) 3, (double) 3, (double) 3, (double) 3},
- new double[] {(double) 3}));
- assertEquals(
- 2,
- Doubles.indexOf(
- new double[] {
- (double) 2, (double) 3, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3
- },
- new double[] {(double) 2, (double) 3, (double) 4}));
- assertEquals(
- 1,
- Doubles.indexOf(
- new double[] {
- (double) 2, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3, (double) 4
- },
- new double[] {(double) 2, (double) 3, (double) 4}));
- assertEquals(
- -1,
- Doubles.indexOf(
- new double[] {(double) 4, (double) 3, (double) 2},
- new double[] {(double) 2, (double) 3, (double) 4}));
+ assertThat(Doubles.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Doubles.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 2, (double) 3})).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 3, (double) 4})).isEqualTo(1);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 3})).isEqualTo(1);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 4})).isEqualTo(2);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {(double) 2, (double) 3, (double) 3, (double) 3, (double) 3},
+ new double[] {(double) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {
+ (double) 2, (double) 3, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3
+ },
+ new double[] {(double) 2, (double) 3, (double) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {
+ (double) 2, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3, (double) 4
+ },
+ new double[] {(double) 2, (double) 3, (double) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {(double) 4, (double) 3, (double) 2},
+ new double[] {(double) 2, (double) 3, (double) 4}))
+ .isEqualTo(-1);
for (double value : NUMBERS) {
- assertEquals(
- "" + value,
- 1,
- Doubles.indexOf(new double[] {5.0, value, value, 5.0}, new double[] {value, value}));
+ assertWithMessage("" + value)
+ .that(Doubles.indexOf(new double[] {5.0, value, value, 5.0}, new double[] {value, value}))
+ .isEqualTo(1);
}
- assertEquals(-1, Doubles.indexOf(new double[] {5.0, NaN, NaN, 5.0}, new double[] {NaN, NaN}));
+ assertThat(Doubles.indexOf(new double[] {5.0, NaN, NaN, 5.0}, new double[] {NaN, NaN}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Doubles.lastIndexOf(EMPTY, (double) 1));
- assertEquals(-1, Doubles.lastIndexOf(ARRAY1, (double) 2));
- assertEquals(-1, Doubles.lastIndexOf(ARRAY234, (double) 1));
- assertEquals(0, Doubles.lastIndexOf(new double[] {(double) -1}, (double) -1));
- assertEquals(0, Doubles.lastIndexOf(ARRAY234, (double) 2));
- assertEquals(1, Doubles.lastIndexOf(ARRAY234, (double) 3));
- assertEquals(2, Doubles.lastIndexOf(ARRAY234, (double) 4));
- assertEquals(
- 3,
- Doubles.lastIndexOf(
- new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3));
+ assertThat(Doubles.lastIndexOf(EMPTY, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.lastIndexOf(ARRAY1, (double) 2)).isEqualTo(-1);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.lastIndexOf(new double[] {(double) -1}, (double) -1)).isEqualTo(0);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 2)).isEqualTo(0);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 3)).isEqualTo(1);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 4)).isEqualTo(2);
+ assertThat(
+ Doubles.lastIndexOf(
+ new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3))
+ .isEqualTo(3);
for (double value : NUMBERS) {
- assertEquals("" + value, 0, Doubles.lastIndexOf(new double[] {value, 5.0}, value));
+ assertWithMessage("" + value)
+ .that(Doubles.lastIndexOf(new double[] {value, 5.0}, value))
+ .isEqualTo(0);
}
- assertEquals(-1, Doubles.lastIndexOf(new double[] {NaN, 5.0}, NaN));
+ assertThat(Doubles.lastIndexOf(new double[] {NaN, 5.0}, NaN)).isEqualTo(-1);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -204,19 +218,20 @@ public class DoublesTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Doubles.max(LEAST));
- assertEquals(GREATEST, Doubles.max(GREATEST));
- assertEquals(
- (double) 9,
- Doubles.max(
- (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9));
+ assertThat(Doubles.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Doubles.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Doubles.max(
+ (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9))
+ .isEqualTo((double) 9);
- assertEquals(0.0, Doubles.max(-0.0, 0.0));
- assertEquals(0.0, Doubles.max(0.0, -0.0));
- assertEquals(GREATEST, Doubles.max(NUMBERS));
- assertTrue(Double.isNaN(Doubles.max(VALUES)));
+ assertThat(Doubles.max(-0.0, 0.0)).isEqualTo(0.0);
+ assertThat(Doubles.max(0.0, -0.0)).isEqualTo(0.0);
+ assertThat(Doubles.max(NUMBERS)).isEqualTo(GREATEST);
+ assertThat(Double.isNaN(Doubles.max(VALUES))).isTrue();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -227,31 +242,26 @@ public class DoublesTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Doubles.min(LEAST));
- assertEquals(GREATEST, Doubles.min(GREATEST));
- assertEquals(
- (double) 0,
- Doubles.min(
- (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9));
+ assertThat(Doubles.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Doubles.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Doubles.min(
+ (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9))
+ .isEqualTo((double) 0);
- assertEquals(-0.0, Doubles.min(-0.0, 0.0));
- assertEquals(-0.0, Doubles.min(0.0, -0.0));
- assertEquals(LEAST, Doubles.min(NUMBERS));
- assertTrue(Double.isNaN(Doubles.min(VALUES)));
+ assertThat(Doubles.min(-0.0, 0.0)).isEqualTo(-0.0);
+ assertThat(Doubles.min(0.0, -0.0)).isEqualTo(-0.0);
+ assertThat(Doubles.min(NUMBERS)).isEqualTo(LEAST);
+ assertThat(Double.isNaN(Doubles.min(VALUES))).isTrue();
}
public void testConstrainToRange() {
- double tolerance = 1e-10;
- assertEquals(
- (double) 1, Doubles.constrainToRange((double) 1, (double) 0, (double) 5), tolerance);
- assertEquals(
- (double) 1, Doubles.constrainToRange((double) 1, (double) 1, (double) 5), tolerance);
- assertEquals(
- (double) 3, Doubles.constrainToRange((double) 1, (double) 3, (double) 5), tolerance);
- assertEquals(
- (double) -1, Doubles.constrainToRange((double) 0, (double) -5, (double) -1), tolerance);
- assertEquals(
- (double) 2, Doubles.constrainToRange((double) 5, (double) 2, (double) 2), tolerance);
+ assertThat(Doubles.constrainToRange((double) 1, (double) 0, (double) 5)).isEqualTo((double) 1);
+ assertThat(Doubles.constrainToRange((double) 1, (double) 1, (double) 5)).isEqualTo((double) 1);
+ assertThat(Doubles.constrainToRange((double) 1, (double) 3, (double) 5)).isEqualTo((double) 3);
+ assertThat(Doubles.constrainToRange((double) 0, (double) -5, (double) -1))
+ .isEqualTo((double) -1);
+ assertThat(Doubles.constrainToRange((double) 5, (double) 2, (double) 2)).isEqualTo((double) 2);
try {
Doubles.constrainToRange((double) 1, (double) 3, (double) 2);
fail();
@@ -260,30 +270,27 @@ public class DoublesTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Doubles.concat()));
- assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Doubles.concat(ARRAY1)));
- assertNotSame(ARRAY1, Doubles.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Doubles.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new double[] {(double) 1, (double) 1, (double) 1},
- Doubles.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new double[] {(double) 1, (double) 2, (double) 3, (double) 4},
- Doubles.concat(ARRAY1, ARRAY234)));
+ assertThat(Doubles.concat()).isEqualTo(EMPTY);
+ assertThat(Doubles.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Doubles.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Doubles.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Doubles.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Doubles.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Doubles.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new double[] {(double) 1, (double) 1, (double) 1});
+ assertThat(Doubles.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new double[] {(double) 1, (double) 2, (double) 3, (double) 4});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Doubles.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new double[] {(double) 1, (double) 0, (double) 0},
- Doubles.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Doubles.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Doubles.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Doubles.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(
+ Arrays.equals(
+ new double[] {(double) 1, (double) 0, (double) 0},
+ Doubles.ensureCapacity(ARRAY1, 2, 1)))
+ .isTrue();
}
public void testEnsureCapacity_fail() {
@@ -300,19 +307,20 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Double.toString returns different value in GWT.
public void testJoin() {
- assertEquals("", Doubles.join(",", EMPTY));
- assertEquals("1.0", Doubles.join(",", ARRAY1));
- assertEquals("1.0,2.0", Doubles.join(",", (double) 1, (double) 2));
- assertEquals("1.02.03.0", Doubles.join("", (double) 1, (double) 2, (double) 3));
+ assertThat(Doubles.join(",", EMPTY)).isEmpty();
+ assertThat(Doubles.join(",", ARRAY1)).isEqualTo("1.0");
+ assertThat(Doubles.join(",", (double) 1, (double) 2)).isEqualTo("1.0,2.0");
+ assertThat(Doubles.join("", (double) 1, (double) 2, (double) 3)).isEqualTo("1.02.03.0");
}
public void testJoinNonTrivialDoubles() {
- assertEquals("", Doubles.join(",", EMPTY));
- assertEquals("1.2", Doubles.join(",", 1.2));
- assertEquals("1.3,2.4", Doubles.join(",", 1.3, 2.4));
- assertEquals("1.42.53.6", Doubles.join("", 1.4, 2.5, 3.6));
+ assertThat(Doubles.join(",", EMPTY)).isEmpty();
+ assertThat(Doubles.join(",", 1.2)).isEqualTo("1.2");
+ assertThat(Doubles.join(",", 1.3, 2.4)).isEqualTo("1.3,2.4");
+ assertThat(Doubles.join("", 1.4, 2.5, 3.6)).isEqualTo("1.42.53.6");
}
public void testLexicographicalComparator() {
@@ -343,14 +351,14 @@ public class DoublesTest extends TestCase {
private static void testReverse(double[] input, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
double[] input, int fromIndex, int toIndex, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -362,6 +370,103 @@ public class DoublesTest extends TestCase {
testReverse(new double[] {-1, 1, -2, 2}, 1, 3, new double[] {-1, -2, 1, 2});
}
+ private static void testRotate(double[] input, int distance, double[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Doubles.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ double[] input, int distance, int fromIndex, int toIndex, double[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Doubles.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new double[] {}, -1, new double[] {});
+ testRotate(new double[] {}, 0, new double[] {});
+ testRotate(new double[] {}, 1, new double[] {});
+
+ testRotate(new double[] {1}, -2, new double[] {1});
+ testRotate(new double[] {1}, -1, new double[] {1});
+ testRotate(new double[] {1}, 0, new double[] {1});
+ testRotate(new double[] {1}, 1, new double[] {1});
+ testRotate(new double[] {1}, 2, new double[] {1});
+
+ testRotate(new double[] {1, 2}, -3, new double[] {2, 1});
+ testRotate(new double[] {1, 2}, -1, new double[] {2, 1});
+ testRotate(new double[] {1, 2}, -2, new double[] {1, 2});
+ testRotate(new double[] {1, 2}, 0, new double[] {1, 2});
+ testRotate(new double[] {1, 2}, 1, new double[] {2, 1});
+ testRotate(new double[] {1, 2}, 2, new double[] {1, 2});
+ testRotate(new double[] {1, 2}, 3, new double[] {2, 1});
+
+ testRotate(new double[] {1, 2, 3}, -5, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, -4, new double[] {2, 3, 1});
+ testRotate(new double[] {1, 2, 3}, -3, new double[] {1, 2, 3});
+ testRotate(new double[] {1, 2, 3}, -2, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, -1, new double[] {2, 3, 1});
+ testRotate(new double[] {1, 2, 3}, 0, new double[] {1, 2, 3});
+ testRotate(new double[] {1, 2, 3}, 1, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, 2, new double[] {2, 3, 1});
+ testRotate(new double[] {1, 2, 3}, 3, new double[] {1, 2, 3});
+ testRotate(new double[] {1, 2, 3}, 4, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, 5, new double[] {2, 3, 1});
+
+ testRotate(new double[] {1, 2, 3, 4}, -9, new double[] {2, 3, 4, 1});
+ testRotate(new double[] {1, 2, 3, 4}, -5, new double[] {2, 3, 4, 1});
+ testRotate(new double[] {1, 2, 3, 4}, -1, new double[] {2, 3, 4, 1});
+ testRotate(new double[] {1, 2, 3, 4}, 0, new double[] {1, 2, 3, 4});
+ testRotate(new double[] {1, 2, 3, 4}, 1, new double[] {4, 1, 2, 3});
+ testRotate(new double[] {1, 2, 3, 4}, 5, new double[] {4, 1, 2, 3});
+ testRotate(new double[] {1, 2, 3, 4}, 9, new double[] {4, 1, 2, 3});
+
+ testRotate(new double[] {1, 2, 3, 4, 5}, -6, new double[] {2, 3, 4, 5, 1});
+ testRotate(new double[] {1, 2, 3, 4, 5}, -4, new double[] {5, 1, 2, 3, 4});
+ testRotate(new double[] {1, 2, 3, 4, 5}, -3, new double[] {4, 5, 1, 2, 3});
+ testRotate(new double[] {1, 2, 3, 4, 5}, -1, new double[] {2, 3, 4, 5, 1});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 0, new double[] {1, 2, 3, 4, 5});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 1, new double[] {5, 1, 2, 3, 4});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 3, new double[] {3, 4, 5, 1, 2});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 4, new double[] {2, 3, 4, 5, 1});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 6, new double[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new double[] {}, 0, 0, 0, new double[] {});
+
+ testRotate(new double[] {1}, 0, 0, 1, new double[] {1});
+ testRotate(new double[] {1}, 1, 0, 1, new double[] {1});
+ testRotate(new double[] {1}, 1, 1, 1, new double[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new double[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new double[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new double[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new double[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new double[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new double[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new double[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new double[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new double[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new double[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new double[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new double[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new double[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new double[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new double[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new double[] {}, new double[] {});
testSortDescending(new double[] {1}, new double[] {1});
@@ -369,16 +474,15 @@ public class DoublesTest extends TestCase {
testSortDescending(new double[] {1, 3, 1}, new double[] {3, 1, 1});
testSortDescending(new double[] {-1, 1, -2, 2}, new double[] {2, 1, -1, -2});
testSortDescending(
- new double[] {-1, 1, Double.NaN, -2, -0, 0, 2},
- new double[] {Double.NaN, 2, 1, 0, -0, -1, -2});
+ new double[] {-1, 1, Double.NaN, -2, -0.0, 0, 2},
+ new double[] {Double.NaN, 2, 1, 0, -0.0, -1, -2});
}
private static void testSortDescending(double[] input, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.sortDescending(input);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Double.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -386,9 +490,8 @@ public class DoublesTest extends TestCase {
double[] input, int fromIndex, int toIndex, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.sortDescending(input, fromIndex, toIndex);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Double.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -403,12 +506,14 @@ public class DoublesTest extends TestCase {
new double[] {-1, 1, Double.NaN, -2, 2}, 1, 4, new double[] {-1, Double.NaN, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<double[]> comparator = Doubles.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Doubles.stringConverter());
@@ -417,17 +522,17 @@ public class DoublesTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Double> none = Arrays.<Double>asList();
- assertTrue(Arrays.equals(EMPTY, Doubles.toArray(none)));
+ assertThat(Doubles.toArray(none)).isEqualTo(EMPTY);
List<Double> one = Arrays.asList((double) 1);
- assertTrue(Arrays.equals(ARRAY1, Doubles.toArray(one)));
+ assertThat(Doubles.toArray(one)).isEqualTo(ARRAY1);
double[] array = {(double) 0, (double) 1, Math.PI};
List<Double> three = Arrays.asList((double) 0, (double) 1, Math.PI);
- assertTrue(Arrays.equals(array, Doubles.toArray(three)));
+ assertThat(Doubles.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Doubles.toArray(Doubles.asList(array))));
+ assertThat(Doubles.toArray(Doubles.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -437,16 +542,16 @@ public class DoublesTest extends TestCase {
Collection<Double> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
double[] arr = Doubles.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr.length).isEqualTo(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Double> list = Arrays.asList((double) 0, (double) 1, null);
+ List<@Nullable Double> list = Arrays.asList((double) 0, (double) 1, null);
try {
Doubles.toArray(list);
fail();
@@ -464,19 +569,20 @@ public class DoublesTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Doubles.toArray(bytes)));
- assertTrue(Arrays.equals(array, Doubles.toArray(shorts)));
- assertTrue(Arrays.equals(array, Doubles.toArray(ints)));
- assertTrue(Arrays.equals(array, Doubles.toArray(floats)));
- assertTrue(Arrays.equals(array, Doubles.toArray(longs)));
- assertTrue(Arrays.equals(array, Doubles.toArray(doubles)));
+ assertThat(Doubles.toArray(bytes)).isEqualTo(array);
+ assertThat(Doubles.toArray(shorts)).isEqualTo(array);
+ assertThat(Doubles.toArray(ints)).isEqualTo(array);
+ assertThat(Doubles.toArray(floats)).isEqualTo(array);
+ assertThat(Doubles.toArray(longs)).isEqualTo(array);
+ assertThat(Doubles.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
double[] array = {(double) 0, (double) 1};
List<Double> list = Doubles.asList(array);
list.set(0, (double) 2);
- assertTrue(Arrays.equals(new double[] {(double) 2, (double) 1}, array));
+ assertThat(array).isEqualTo(new double[] {(double) 2, (double) 1});
array[1] = (double) 3;
assertThat(list).containsExactly((double) 2, (double) 3).inOrder();
}
@@ -488,29 +594,29 @@ public class DoublesTest extends TestCase {
// Make sure it returned a copy
list.set(0, (double) 4);
- assertTrue(Arrays.equals(new double[] {(double) 0, (double) 1, (double) 2}, newArray));
+ assertThat(newArray).isEqualTo(new double[] {(double) 0, (double) 1, (double) 2});
newArray[1] = (double) 5;
- assertEquals((double) 1, (double) list.get(1));
+ assertThat((double) list.get(1)).isEqualTo((double) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
double[] array = {(double) 0, (double) 1, (double) 2, (double) 3};
List<Double> list = Doubles.asList(array);
- assertTrue(
- Arrays.equals(new double[] {(double) 1, (double) 2}, Doubles.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new double[] {}, Doubles.toArray(list.subList(2, 2))));
+ assertThat(Doubles.toArray(list.subList(1, 3)))
+ .isEqualTo(new double[] {(double) 1, (double) 2});
+ assertThat(Doubles.toArray(list.subList(2, 2))).isEmpty();
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Doubles.asList(EMPTY));
+ assertThat(Doubles.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
/**
* A reference implementation for {@code tryParse} that just catches the exception from {@link
* Double#valueOf}.
*/
- private static Double referenceTryParse(String input) {
+ private static @Nullable Double referenceTryParse(String input) {
if (input.trim().length() < input.length()) {
return null;
}
@@ -521,10 +627,11 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
private static void checkTryParse(String input) {
Double expected = referenceTryParse(input);
- assertEquals(expected, Doubles.tryParse(input));
+ assertThat(Doubles.tryParse(input)).isEqualTo(expected);
if (expected != null && !Doubles.FLOATING_POINT_PATTERN.matcher(input).matches()) {
// TODO(cpovirk): Use SourceCodeEscapers if it is added to Guava.
StringBuilder escapedInput = new StringBuilder();
@@ -539,15 +646,17 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
private static void checkTryParse(double expected, String input) {
- assertEquals(Double.valueOf(expected), Doubles.tryParse(input));
+ assertThat(Doubles.tryParse(input)).isEqualTo(Double.valueOf(expected));
assertThat(input)
.matches(
Pattern.compile(
Doubles.FLOATING_POINT_PATTERN.pattern(), Doubles.FLOATING_POINT_PATTERN.flags()));
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseHex() {
for (String signChar : ImmutableList.of("", "+", "-")) {
@@ -569,6 +678,7 @@ public class DoublesTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseAllCodePoints() {
// Exercise non-ASCII digit test cases and the like.
@@ -579,6 +689,7 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseOfToStringIsOriginal() {
for (double d : NUMBERS) {
@@ -586,6 +697,7 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseOfToHexStringIsOriginal() {
for (double d : NUMBERS) {
@@ -593,6 +705,7 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseNaN() {
checkTryParse("NaN");
@@ -600,6 +713,7 @@ public class DoublesTest extends TestCase {
checkTryParse("-NaN");
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseInfinity() {
checkTryParse(Double.POSITIVE_INFINITY, "Infinity");
@@ -624,6 +738,7 @@ public class DoublesTest extends TestCase {
"InfinityF"
};
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseFailures() {
for (String badInput : BAD_TRY_PARSE_INPUTS) {
@@ -632,11 +747,12 @@ public class DoublesTest extends TestCase {
Pattern.compile(
Doubles.FLOATING_POINT_PATTERN.pattern(),
Doubles.FLOATING_POINT_PATTERN.flags()));
- assertEquals(referenceTryParse(badInput), Doubles.tryParse(badInput));
- assertNull(Doubles.tryParse(badInput));
+ assertThat(Doubles.tryParse(badInput)).isEqualTo(referenceTryParse(badInput));
+ assertThat(Doubles.tryParse(badInput)).isNull();
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Doubles.class);
@@ -644,14 +760,14 @@ public class DoublesTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Double> converter = Doubles.stringConverter();
- assertEquals((Double) 1.0, converter.convert("1.0"));
- assertEquals((Double) 0.0, converter.convert("0.0"));
- assertEquals((Double) (-1.0), converter.convert("-1.0"));
- assertEquals((Double) 1.0, converter.convert("1"));
- assertEquals((Double) 0.0, converter.convert("0"));
- assertEquals((Double) (-1.0), converter.convert("-1"));
- assertEquals((Double) 1e6, converter.convert("1e6"));
- assertEquals((Double) 1e-6, converter.convert("1e-6"));
+ assertThat(converter.convert("1.0")).isEqualTo((Double) 1.0);
+ assertThat(converter.convert("0.0")).isEqualTo((Double) 0.0);
+ assertThat(converter.convert("-1.0")).isEqualTo((Double) (-1.0));
+ assertThat(converter.convert("1")).isEqualTo((Double) 1.0);
+ assertThat(converter.convert("0")).isEqualTo((Double) 0.0);
+ assertThat(converter.convert("-1")).isEqualTo((Double) (-1.0));
+ assertThat(converter.convert("1e6")).isEqualTo((Double) 1e6);
+ assertThat(converter.convert("1e-6")).isEqualTo((Double) 1e-6);
}
public void testStringConverter_convertError() {
@@ -663,29 +779,32 @@ public class DoublesTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Doubles.stringConverter().convert(null));
- assertNull(Doubles.stringConverter().reverse().convert(null));
+ assertThat(Doubles.stringConverter().convert(null)).isNull();
+ assertThat(Doubles.stringConverter().reverse().convert(null)).isNull();
}
+ @J2ktIncompatible
@GwtIncompatible // Double.toString returns different value in GWT.
public void testStringConverter_reverse() {
Converter<String, Double> converter = Doubles.stringConverter();
- assertEquals("1.0", converter.reverse().convert(1.0));
- assertEquals("0.0", converter.reverse().convert(0.0));
- assertEquals("-1.0", converter.reverse().convert(-1.0));
- assertEquals("1000000.0", converter.reverse().convert(1e6));
- assertEquals("1.0E-6", converter.reverse().convert(1e-6));
+ assertThat(converter.reverse().convert(1.0)).isEqualTo("1.0");
+ assertThat(converter.reverse().convert(0.0)).isEqualTo("0.0");
+ assertThat(converter.reverse().convert(-1.0)).isEqualTo("-1.0");
+ assertThat(converter.reverse().convert(1e6)).isEqualTo("1000000.0");
+ assertThat(converter.reverse().convert(1e-6)).isEqualTo("1.0E-6");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicInstanceMethods(Doubles.stringConverter());
}
+ @J2ktIncompatible
@GwtIncompatible
public void testTryParse_withNullNoGwt() {
- assertNull(Doubles.tryParse("null"));
+ assertThat(Doubles.tryParse("null")).isNull();
try {
Doubles.tryParse(null);
fail("Expected NPE");
diff --git a/android/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java
index 233a0211b..c70a8b5d0 100644
--- a/android/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class FloatArrayAsListTest extends TestCase {
return Floats.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Float>> builders =
diff --git a/android/guava-tests/test/com/google/common/primitives/FloatsTest.java b/android/guava-tests/test/com/google/common/primitives/FloatsTest.java
index fd59ad4d8..4a1e8fbc8 100644
--- a/android/guava-tests/test/com/google/common/primitives/FloatsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/FloatsTest.java
@@ -17,10 +17,12 @@
package com.google.common.primitives;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Float.NaN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.Helpers;
@@ -32,14 +34,15 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Floats}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
-@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class FloatsTest extends TestCase {
private static final float[] EMPTY = {};
private static final float[] ARRAY1 = {(float) 1};
@@ -72,13 +75,14 @@ public class FloatsTest extends TestCase {
public void testHashCode() {
for (float value : VALUES) {
- assertEquals(((Float) value).hashCode(), Floats.hashCode(value));
+ assertThat(Floats.hashCode(value)).isEqualTo(((Float) value).hashCode());
}
}
public void testIsFinite() {
for (float value : NUMBERS) {
- assertEquals(!(Float.isInfinite(value) || Float.isNaN(value)), Floats.isFinite(value));
+ assertThat(Floats.isFinite(value))
+ .isEqualTo(!(Float.isInfinite(value) || Float.isNaN(value)));
}
}
@@ -86,106 +90,114 @@ public class FloatsTest extends TestCase {
for (float x : VALUES) {
for (float y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Float.valueOf(x).compareTo(y), Floats.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Floats.compare(x, y))
+ .isEqualTo(Float.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Floats.contains(EMPTY, (float) 1));
- assertFalse(Floats.contains(ARRAY1, (float) 2));
- assertFalse(Floats.contains(ARRAY234, (float) 1));
- assertTrue(Floats.contains(new float[] {(float) -1}, (float) -1));
- assertTrue(Floats.contains(ARRAY234, (float) 2));
- assertTrue(Floats.contains(ARRAY234, (float) 3));
- assertTrue(Floats.contains(ARRAY234, (float) 4));
+ assertThat(Floats.contains(EMPTY, (float) 1)).isFalse();
+ assertThat(Floats.contains(ARRAY1, (float) 2)).isFalse();
+ assertThat(Floats.contains(ARRAY234, (float) 1)).isFalse();
+ assertThat(Floats.contains(new float[] {(float) -1}, (float) -1)).isTrue();
+ assertThat(Floats.contains(ARRAY234, (float) 2)).isTrue();
+ assertThat(Floats.contains(ARRAY234, (float) 3)).isTrue();
+ assertThat(Floats.contains(ARRAY234, (float) 4)).isTrue();
for (float value : NUMBERS) {
- assertTrue("" + value, Floats.contains(new float[] {5f, value}, value));
+ assertWithMessage("" + value).that(Floats.contains(new float[] {5f, value}, value)).isTrue();
}
- assertFalse(Floats.contains(new float[] {5f, NaN}, NaN));
+ assertThat(Floats.contains(new float[] {5f, NaN}, NaN)).isFalse();
}
public void testIndexOf() {
- assertEquals(-1, Floats.indexOf(EMPTY, (float) 1));
- assertEquals(-1, Floats.indexOf(ARRAY1, (float) 2));
- assertEquals(-1, Floats.indexOf(ARRAY234, (float) 1));
- assertEquals(0, Floats.indexOf(new float[] {(float) -1}, (float) -1));
- assertEquals(0, Floats.indexOf(ARRAY234, (float) 2));
- assertEquals(1, Floats.indexOf(ARRAY234, (float) 3));
- assertEquals(2, Floats.indexOf(ARRAY234, (float) 4));
- assertEquals(
- 1, Floats.indexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3));
+ assertThat(Floats.indexOf(EMPTY, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY1, (float) 2)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY234, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.indexOf(new float[] {(float) -1}, (float) -1)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, (float) 2)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, (float) 3)).isEqualTo(1);
+ assertThat(Floats.indexOf(ARRAY234, (float) 4)).isEqualTo(2);
+ assertThat(Floats.indexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3))
+ .isEqualTo(1);
for (float value : NUMBERS) {
- assertEquals("" + value, 1, Floats.indexOf(new float[] {5f, value}, value));
+ assertWithMessage("" + value)
+ .that(Floats.indexOf(new float[] {5f, value}, value))
+ .isEqualTo(1);
}
- assertEquals(-1, Floats.indexOf(new float[] {5f, NaN}, NaN));
+ assertThat(Floats.indexOf(new float[] {5f, NaN}, NaN)).isEqualTo(-1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Floats.indexOf(EMPTY, EMPTY));
- assertEquals(0, Floats.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Floats.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Floats.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Floats.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Floats.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Floats.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Floats.indexOf(ARRAY234, new float[] {(float) 2, (float) 3}));
- assertEquals(1, Floats.indexOf(ARRAY234, new float[] {(float) 3, (float) 4}));
- assertEquals(1, Floats.indexOf(ARRAY234, new float[] {(float) 3}));
- assertEquals(2, Floats.indexOf(ARRAY234, new float[] {(float) 4}));
- assertEquals(
- 1,
- Floats.indexOf(
- new float[] {(float) 2, (float) 3, (float) 3, (float) 3, (float) 3},
- new float[] {(float) 3}));
- assertEquals(
- 2,
- Floats.indexOf(
- new float[] {
- (float) 2, (float) 3, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3
- },
- new float[] {(float) 2, (float) 3, (float) 4}));
- assertEquals(
- 1,
- Floats.indexOf(
- new float[] {
- (float) 2, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3, (float) 4
- },
- new float[] {(float) 2, (float) 3, (float) 4}));
- assertEquals(
- -1,
- Floats.indexOf(
- new float[] {(float) 4, (float) 3, (float) 2},
- new float[] {(float) 2, (float) 3, (float) 4}));
+ assertThat(Floats.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Floats.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 2, (float) 3})).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 3, (float) 4})).isEqualTo(1);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 3})).isEqualTo(1);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 4})).isEqualTo(2);
+ assertThat(
+ Floats.indexOf(
+ new float[] {(float) 2, (float) 3, (float) 3, (float) 3, (float) 3},
+ new float[] {(float) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Floats.indexOf(
+ new float[] {
+ (float) 2, (float) 3, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3
+ },
+ new float[] {(float) 2, (float) 3, (float) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Floats.indexOf(
+ new float[] {
+ (float) 2, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3, (float) 4
+ },
+ new float[] {(float) 2, (float) 3, (float) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Floats.indexOf(
+ new float[] {(float) 4, (float) 3, (float) 2},
+ new float[] {(float) 2, (float) 3, (float) 4}))
+ .isEqualTo(-1);
for (float value : NUMBERS) {
- assertEquals(
- "" + value,
- 1,
- Floats.indexOf(new float[] {5f, value, value, 5f}, new float[] {value, value}));
+ assertWithMessage("" + value)
+ .that(Floats.indexOf(new float[] {5f, value, value, 5f}, new float[] {value, value}))
+ .isEqualTo(1);
}
- assertEquals(-1, Floats.indexOf(new float[] {5f, NaN, NaN, 5f}, new float[] {NaN, NaN}));
+ assertThat(Floats.indexOf(new float[] {5f, NaN, NaN, 5f}, new float[] {NaN, NaN}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Floats.lastIndexOf(EMPTY, (float) 1));
- assertEquals(-1, Floats.lastIndexOf(ARRAY1, (float) 2));
- assertEquals(-1, Floats.lastIndexOf(ARRAY234, (float) 1));
- assertEquals(0, Floats.lastIndexOf(new float[] {(float) -1}, (float) -1));
- assertEquals(0, Floats.lastIndexOf(ARRAY234, (float) 2));
- assertEquals(1, Floats.lastIndexOf(ARRAY234, (float) 3));
- assertEquals(2, Floats.lastIndexOf(ARRAY234, (float) 4));
- assertEquals(
- 3, Floats.lastIndexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3));
+ assertThat(Floats.lastIndexOf(EMPTY, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.lastIndexOf(ARRAY1, (float) 2)).isEqualTo(-1);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.lastIndexOf(new float[] {(float) -1}, (float) -1)).isEqualTo(0);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 2)).isEqualTo(0);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 3)).isEqualTo(1);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 4)).isEqualTo(2);
+ assertThat(
+ Floats.lastIndexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3))
+ .isEqualTo(3);
for (float value : NUMBERS) {
- assertEquals("" + value, 0, Floats.lastIndexOf(new float[] {value, 5f}, value));
+ assertWithMessage("" + value)
+ .that(Floats.lastIndexOf(new float[] {value, 5f}, value))
+ .isEqualTo(0);
}
- assertEquals(-1, Floats.lastIndexOf(new float[] {NaN, 5f}, NaN));
+ assertThat(Floats.lastIndexOf(new float[] {NaN, 5f}, NaN)).isEqualTo(-1);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -196,18 +208,19 @@ public class FloatsTest extends TestCase {
}
public void testMax() {
- assertEquals(GREATEST, Floats.max(GREATEST));
- assertEquals(LEAST, Floats.max(LEAST));
- assertEquals(
- (float) 9,
- Floats.max((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9));
+ assertThat(Floats.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Floats.max(LEAST)).isEqualTo(LEAST);
+ assertThat(
+ Floats.max((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9))
+ .isEqualTo((float) 9);
- assertEquals(0f, Floats.max(-0f, 0f));
- assertEquals(0f, Floats.max(0f, -0f));
- assertEquals(GREATEST, Floats.max(NUMBERS));
- assertTrue(Float.isNaN(Floats.max(VALUES)));
+ assertThat(Floats.max(-0f, 0f)).isEqualTo(0f);
+ assertThat(Floats.max(0f, -0f)).isEqualTo(0f);
+ assertThat(Floats.max(NUMBERS)).isEqualTo(GREATEST);
+ assertThat(Float.isNaN(Floats.max(VALUES))).isTrue();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -218,25 +231,24 @@ public class FloatsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Floats.min(LEAST));
- assertEquals(GREATEST, Floats.min(GREATEST));
- assertEquals(
- (float) 0,
- Floats.min((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9));
+ assertThat(Floats.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Floats.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Floats.min((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9))
+ .isEqualTo((float) 0);
- assertEquals(-0f, Floats.min(-0f, 0f));
- assertEquals(-0f, Floats.min(0f, -0f));
- assertEquals(LEAST, Floats.min(NUMBERS));
- assertTrue(Float.isNaN(Floats.min(VALUES)));
+ assertThat(Floats.min(-0f, 0f)).isEqualTo(-0f);
+ assertThat(Floats.min(0f, -0f)).isEqualTo(-0f);
+ assertThat(Floats.min(NUMBERS)).isEqualTo(LEAST);
+ assertThat(Float.isNaN(Floats.min(VALUES))).isTrue();
}
public void testConstrainToRange() {
- float tolerance = 1e-10f;
- assertEquals((float) 1, Floats.constrainToRange((float) 1, (float) 0, (float) 5), tolerance);
- assertEquals((float) 1, Floats.constrainToRange((float) 1, (float) 1, (float) 5), tolerance);
- assertEquals((float) 3, Floats.constrainToRange((float) 1, (float) 3, (float) 5), tolerance);
- assertEquals((float) -1, Floats.constrainToRange((float) 0, (float) -5, (float) -1), tolerance);
- assertEquals((float) 2, Floats.constrainToRange((float) 5, (float) 2, (float) 2), tolerance);
+ assertThat(Floats.constrainToRange((float) 1, (float) 0, (float) 5)).isEqualTo((float) 1);
+ assertThat(Floats.constrainToRange((float) 1, (float) 1, (float) 5)).isEqualTo((float) 1);
+ assertThat(Floats.constrainToRange((float) 1, (float) 3, (float) 5)).isEqualTo((float) 3);
+ assertThat(Floats.constrainToRange((float) 0, (float) -5, (float) -1)).isEqualTo((float) -1);
+ assertThat(Floats.constrainToRange((float) 5, (float) 2, (float) 2)).isEqualTo((float) 2);
try {
Floats.constrainToRange((float) 1, (float) 3, (float) 2);
fail();
@@ -245,28 +257,26 @@ public class FloatsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Floats.concat()));
- assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Floats.concat(ARRAY1)));
- assertNotSame(ARRAY1, Floats.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Floats.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new float[] {(float) 1, (float) 1, (float) 1}, Floats.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new float[] {(float) 1, (float) 2, (float) 3, (float) 4},
- Floats.concat(ARRAY1, ARRAY234)));
+ assertThat(Floats.concat()).isEqualTo(EMPTY);
+ assertThat(Floats.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Floats.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Floats.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Floats.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Floats.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Floats.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new float[] {(float) 1, (float) 1, (float) 1});
+ assertThat(Floats.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new float[] {(float) 1, (float) 2, (float) 3, (float) 4});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Floats.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new float[] {(float) 1, (float) 0, (float) 0}, Floats.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Floats.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Floats.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Floats.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(
+ Arrays.equals(
+ new float[] {(float) 1, (float) 0, (float) 0}, Floats.ensureCapacity(ARRAY1, 2, 1)))
+ .isTrue();
}
public void testEnsureCapacity_fail() {
@@ -283,12 +293,13 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Float.toString returns different value in GWT.
public void testJoin() {
- assertEquals("", Floats.join(",", EMPTY));
- assertEquals("1.0", Floats.join(",", ARRAY1));
- assertEquals("1.0,2.0", Floats.join(",", (float) 1, (float) 2));
- assertEquals("1.02.03.0", Floats.join("", (float) 1, (float) 2, (float) 3));
+ assertThat(Floats.join(",", EMPTY)).isEmpty();
+ assertThat(Floats.join(",", ARRAY1)).isEqualTo("1.0");
+ assertThat(Floats.join(",", (float) 1, (float) 2)).isEqualTo("1.0,2.0");
+ assertThat(Floats.join("", (float) 1, (float) 2, (float) 3)).isEqualTo("1.02.03.0");
}
public void testLexicographicalComparator() {
@@ -308,10 +319,11 @@ public class FloatsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<float[]> comparator = Floats.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -325,14 +337,14 @@ public class FloatsTest extends TestCase {
private static void testReverse(float[] input, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
float[] input, int fromIndex, int toIndex, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -344,6 +356,103 @@ public class FloatsTest extends TestCase {
testReverse(new float[] {-1, 1, -2, 2}, 1, 3, new float[] {-1, -2, 1, 2});
}
+ private static void testRotate(float[] input, int distance, float[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Floats.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ float[] input, int distance, int fromIndex, int toIndex, float[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Floats.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new float[] {}, -1, new float[] {});
+ testRotate(new float[] {}, 0, new float[] {});
+ testRotate(new float[] {}, 1, new float[] {});
+
+ testRotate(new float[] {1}, -2, new float[] {1});
+ testRotate(new float[] {1}, -1, new float[] {1});
+ testRotate(new float[] {1}, 0, new float[] {1});
+ testRotate(new float[] {1}, 1, new float[] {1});
+ testRotate(new float[] {1}, 2, new float[] {1});
+
+ testRotate(new float[] {1, 2}, -3, new float[] {2, 1});
+ testRotate(new float[] {1, 2}, -1, new float[] {2, 1});
+ testRotate(new float[] {1, 2}, -2, new float[] {1, 2});
+ testRotate(new float[] {1, 2}, 0, new float[] {1, 2});
+ testRotate(new float[] {1, 2}, 1, new float[] {2, 1});
+ testRotate(new float[] {1, 2}, 2, new float[] {1, 2});
+ testRotate(new float[] {1, 2}, 3, new float[] {2, 1});
+
+ testRotate(new float[] {1, 2, 3}, -5, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, -4, new float[] {2, 3, 1});
+ testRotate(new float[] {1, 2, 3}, -3, new float[] {1, 2, 3});
+ testRotate(new float[] {1, 2, 3}, -2, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, -1, new float[] {2, 3, 1});
+ testRotate(new float[] {1, 2, 3}, 0, new float[] {1, 2, 3});
+ testRotate(new float[] {1, 2, 3}, 1, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, 2, new float[] {2, 3, 1});
+ testRotate(new float[] {1, 2, 3}, 3, new float[] {1, 2, 3});
+ testRotate(new float[] {1, 2, 3}, 4, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, 5, new float[] {2, 3, 1});
+
+ testRotate(new float[] {1, 2, 3, 4}, -9, new float[] {2, 3, 4, 1});
+ testRotate(new float[] {1, 2, 3, 4}, -5, new float[] {2, 3, 4, 1});
+ testRotate(new float[] {1, 2, 3, 4}, -1, new float[] {2, 3, 4, 1});
+ testRotate(new float[] {1, 2, 3, 4}, 0, new float[] {1, 2, 3, 4});
+ testRotate(new float[] {1, 2, 3, 4}, 1, new float[] {4, 1, 2, 3});
+ testRotate(new float[] {1, 2, 3, 4}, 5, new float[] {4, 1, 2, 3});
+ testRotate(new float[] {1, 2, 3, 4}, 9, new float[] {4, 1, 2, 3});
+
+ testRotate(new float[] {1, 2, 3, 4, 5}, -6, new float[] {2, 3, 4, 5, 1});
+ testRotate(new float[] {1, 2, 3, 4, 5}, -4, new float[] {5, 1, 2, 3, 4});
+ testRotate(new float[] {1, 2, 3, 4, 5}, -3, new float[] {4, 5, 1, 2, 3});
+ testRotate(new float[] {1, 2, 3, 4, 5}, -1, new float[] {2, 3, 4, 5, 1});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 0, new float[] {1, 2, 3, 4, 5});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 1, new float[] {5, 1, 2, 3, 4});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 3, new float[] {3, 4, 5, 1, 2});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 4, new float[] {2, 3, 4, 5, 1});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 6, new float[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new float[] {}, 0, 0, 0, new float[] {});
+
+ testRotate(new float[] {1}, 0, 0, 1, new float[] {1});
+ testRotate(new float[] {1}, 1, 0, 1, new float[] {1});
+ testRotate(new float[] {1}, 1, 1, 1, new float[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new float[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new float[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new float[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new float[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new float[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new float[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new float[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new float[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new float[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new float[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new float[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new float[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new float[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new float[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new float[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new float[] {}, new float[] {});
testSortDescending(new float[] {1}, new float[] {1});
@@ -351,15 +460,15 @@ public class FloatsTest extends TestCase {
testSortDescending(new float[] {1, 3, 1}, new float[] {3, 1, 1});
testSortDescending(new float[] {-1, 1, -2, 2}, new float[] {2, 1, -1, -2});
testSortDescending(
- new float[] {-1, 1, Float.NaN, -2, -0, 0, 2}, new float[] {Float.NaN, 2, 1, 0, -0, -1, -2});
+ new float[] {-1, 1, Float.NaN, -2, -0f, 0, 2},
+ new float[] {Float.NaN, 2, 1, 0, -0f, -1, -2});
}
private static void testSortDescending(float[] input, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.sortDescending(input);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Float.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -367,9 +476,8 @@ public class FloatsTest extends TestCase {
float[] input, int fromIndex, int toIndex, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.sortDescending(input, fromIndex, toIndex);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Float.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -384,6 +492,7 @@ public class FloatsTest extends TestCase {
new float[] {-1, 1, Float.NaN, -2, 2}, 1, 4, new float[] {-1, Float.NaN, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Floats.stringConverter());
@@ -392,17 +501,17 @@ public class FloatsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Float> none = Arrays.<Float>asList();
- assertTrue(Arrays.equals(EMPTY, Floats.toArray(none)));
+ assertThat(Floats.toArray(none)).isEqualTo(EMPTY);
List<Float> one = Arrays.asList((float) 1);
- assertTrue(Arrays.equals(ARRAY1, Floats.toArray(one)));
+ assertThat(Floats.toArray(one)).isEqualTo(ARRAY1);
float[] array = {(float) 0, (float) 1, (float) 3};
List<Float> three = Arrays.asList((float) 0, (float) 1, (float) 3);
- assertTrue(Arrays.equals(array, Floats.toArray(three)));
+ assertThat(Floats.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Floats.toArray(Floats.asList(array))));
+ assertThat(Floats.toArray(Floats.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -412,16 +521,16 @@ public class FloatsTest extends TestCase {
Collection<Float> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
float[] arr = Floats.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr.length).isEqualTo(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Float> list = Arrays.asList((float) 0, (float) 1, null);
+ List<@Nullable Float> list = Arrays.asList((float) 0, (float) 1, null);
try {
Floats.toArray(list);
fail();
@@ -439,19 +548,20 @@ public class FloatsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Floats.toArray(bytes)));
- assertTrue(Arrays.equals(array, Floats.toArray(shorts)));
- assertTrue(Arrays.equals(array, Floats.toArray(ints)));
- assertTrue(Arrays.equals(array, Floats.toArray(floats)));
- assertTrue(Arrays.equals(array, Floats.toArray(longs)));
- assertTrue(Arrays.equals(array, Floats.toArray(doubles)));
+ assertThat(Floats.toArray(bytes)).isEqualTo(array);
+ assertThat(Floats.toArray(shorts)).isEqualTo(array);
+ assertThat(Floats.toArray(ints)).isEqualTo(array);
+ assertThat(Floats.toArray(floats)).isEqualTo(array);
+ assertThat(Floats.toArray(longs)).isEqualTo(array);
+ assertThat(Floats.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
float[] array = {(float) 0, (float) 1};
List<Float> list = Floats.asList(array);
list.set(0, (float) 2);
- assertTrue(Arrays.equals(new float[] {(float) 2, (float) 1}, array));
+ assertThat(array).isEqualTo(new float[] {(float) 2, (float) 1});
array[1] = (float) 3;
assertThat(list).containsExactly((float) 2, (float) 3).inOrder();
}
@@ -463,29 +573,28 @@ public class FloatsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (float) 4);
- assertTrue(Arrays.equals(new float[] {(float) 0, (float) 1, (float) 2}, newArray));
+ assertThat(newArray).isEqualTo(new float[] {(float) 0, (float) 1, (float) 2});
newArray[1] = (float) 5;
- assertEquals((float) 1, (float) list.get(1));
+ assertThat((float) list.get(1)).isEqualTo((float) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
float[] array = {(float) 0, (float) 1, (float) 2, (float) 3};
List<Float> list = Floats.asList(array);
- assertTrue(
- Arrays.equals(new float[] {(float) 1, (float) 2}, Floats.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new float[] {}, Floats.toArray(list.subList(2, 2))));
+ assertThat(Floats.toArray(list.subList(1, 3))).isEqualTo(new float[] {(float) 1, (float) 2});
+ assertThat(Floats.toArray(list.subList(2, 2))).isEmpty();
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Floats.asList(EMPTY));
+ assertThat(Floats.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
/**
* A reference implementation for {@code tryParse} that just catches the exception from {@link
* Float#valueOf}.
*/
- private static Float referenceTryParse(String input) {
+ private static @Nullable Float referenceTryParse(String input) {
if (input.trim().length() < input.length()) {
return null;
}
@@ -496,16 +605,19 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
private static void checkTryParse(String input) {
- assertEquals(referenceTryParse(input), Floats.tryParse(input));
+ assertThat(Floats.tryParse(input)).isEqualTo(referenceTryParse(input));
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
private static void checkTryParse(float expected, String input) {
- assertEquals(Float.valueOf(expected), Floats.tryParse(input));
+ assertThat(Floats.tryParse(input)).isEqualTo(Float.valueOf(expected));
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseHex() {
for (String signChar : ImmutableList.of("", "+", "-")) {
@@ -527,6 +639,7 @@ public class FloatsTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseAllCodePoints() {
// Exercise non-ASCII digit test cases and the like.
@@ -537,6 +650,7 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseOfToStringIsOriginal() {
for (float f : NUMBERS) {
@@ -544,6 +658,7 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseOfToHexStringIsOriginal() {
for (float f : NUMBERS) {
@@ -551,6 +666,7 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseNaN() {
checkTryParse("NaN");
@@ -558,6 +674,7 @@ public class FloatsTest extends TestCase {
checkTryParse("-NaN");
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseInfinity() {
checkTryParse(Float.POSITIVE_INFINITY, "Infinity");
@@ -582,30 +699,33 @@ public class FloatsTest extends TestCase {
"InfinityF"
};
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseFailures() {
for (String badInput : BAD_TRY_PARSE_INPUTS) {
- assertEquals(referenceTryParse(badInput), Floats.tryParse(badInput));
- assertNull(Floats.tryParse(badInput));
+ assertThat(Floats.tryParse(badInput)).isEqualTo(referenceTryParse(badInput));
+ assertThat(Floats.tryParse(badInput)).isNull();
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Floats.class);
}
+ @J2ktIncompatible
@GwtIncompatible // Float.toString returns different value in GWT.
public void testStringConverter_convert() {
Converter<String, Float> converter = Floats.stringConverter();
- assertEquals((Float) 1.0f, converter.convert("1.0"));
- assertEquals((Float) 0.0f, converter.convert("0.0"));
- assertEquals((Float) (-1.0f), converter.convert("-1.0"));
- assertEquals((Float) 1.0f, converter.convert("1"));
- assertEquals((Float) 0.0f, converter.convert("0"));
- assertEquals((Float) (-1.0f), converter.convert("-1"));
- assertEquals((Float) 1e6f, converter.convert("1e6"));
- assertEquals((Float) 1e-6f, converter.convert("1e-6"));
+ assertThat(converter.convert("1.0")).isEqualTo((Float) 1.0f);
+ assertThat(converter.convert("0.0")).isEqualTo((Float) 0.0f);
+ assertThat(converter.convert("-1.0")).isEqualTo((Float) (-1.0f));
+ assertThat(converter.convert("1")).isEqualTo((Float) 1.0f);
+ assertThat(converter.convert("0")).isEqualTo((Float) 0.0f);
+ assertThat(converter.convert("-1")).isEqualTo((Float) (-1.0f));
+ assertThat(converter.convert("1e6")).isEqualTo((Float) 1e6f);
+ assertThat(converter.convert("1e-6")).isEqualTo((Float) 1e-6f);
}
public void testStringConverter_convertError() {
@@ -617,29 +737,32 @@ public class FloatsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Floats.stringConverter().convert(null));
- assertNull(Floats.stringConverter().reverse().convert(null));
+ assertThat(Floats.stringConverter().convert(null)).isNull();
+ assertThat(Floats.stringConverter().reverse().convert(null)).isNull();
}
+ @J2ktIncompatible
@GwtIncompatible // Float.toString returns different value in GWT.
public void testStringConverter_reverse() {
Converter<String, Float> converter = Floats.stringConverter();
- assertEquals("1.0", converter.reverse().convert(1.0f));
- assertEquals("0.0", converter.reverse().convert(0.0f));
- assertEquals("-1.0", converter.reverse().convert(-1.0f));
- assertEquals("1000000.0", converter.reverse().convert(1e6f));
- assertEquals("1.0E-6", converter.reverse().convert(1e-6f));
+ assertThat(converter.reverse().convert(1.0f)).isEqualTo("1.0");
+ assertThat(converter.reverse().convert(0.0f)).isEqualTo("0.0");
+ assertThat(converter.reverse().convert(-1.0f)).isEqualTo("-1.0");
+ assertThat(converter.reverse().convert(1e6f)).isEqualTo("1000000.0");
+ assertThat(converter.reverse().convert(1e-6f)).isEqualTo("1.0E-6");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicInstanceMethods(Floats.stringConverter());
}
+ @J2ktIncompatible
@GwtIncompatible
public void testTryParse_withNullNoGwt() {
- assertNull(Floats.tryParse("null"));
+ assertThat(Floats.tryParse("null")).isNull();
try {
Floats.tryParse(null);
fail("Expected NPE");
diff --git a/android/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java b/android/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
index 4d988365f..b0d0fab5c 100644
--- a/android/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.testing.ListTestSuiteBuilder;
@@ -40,8 +41,11 @@ import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
-/** @author Kevin Bourrillion */
+/**
+ * @author Kevin Bourrillion
+ */
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class ImmutableDoubleArrayTest extends TestCase {
// Test all creation paths very lazily: by assuming asList() works
@@ -399,6 +403,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
assertActuallyTrims(underSized);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
assertThat(reserialize(ImmutableDoubleArray.of())).isSameInstanceAs(ImmutableDoubleArray.of());
@@ -423,6 +428,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
assertThat(iia.trimmed()).isSameInstanceAs(iia);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Double>> builders =
@@ -454,6 +460,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
return suite;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static ImmutableDoubleArray makeArray(Double[] values) {
return ImmutableDoubleArray.copyOf(Arrays.asList(values));
@@ -462,6 +469,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
// Test generators. To let the GWT test suite generator access them, they need to be public named
// classes with a public default constructor (not that we run these suites under GWT yet).
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayAsListGenerator extends TestDoubleListGenerator {
@Override
@@ -470,6 +478,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayHeadSubListAsListGenerator
extends TestDoubleListGenerator {
@@ -481,6 +490,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayTailSubListAsListGenerator
extends TestDoubleListGenerator {
@@ -492,6 +502,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayMiddleSubListAsListGenerator
extends TestDoubleListGenerator {
@@ -504,11 +515,13 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static Double[] concat(Double[] a, Double[] b) {
return ObjectArrays.concat(a, b, Double.class);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public abstract static class TestDoubleListGenerator implements TestListGenerator<Double> {
@Override
@@ -544,6 +557,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static class SampleDoubles extends SampleElements<Double> {
public SampleDoubles() {
diff --git a/android/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java b/android/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java
index 86274d453..3831b47a4 100644
--- a/android/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.testing.ListTestSuiteBuilder;
@@ -386,6 +387,7 @@ public class ImmutableIntArrayTest extends TestCase {
assertActuallyTrims(underSized);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
assertThat(reserialize(ImmutableIntArray.of())).isSameInstanceAs(ImmutableIntArray.of());
@@ -410,6 +412,7 @@ public class ImmutableIntArrayTest extends TestCase {
assertThat(iia.trimmed()).isSameInstanceAs(iia);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Integer>> builders =
@@ -441,6 +444,7 @@ public class ImmutableIntArrayTest extends TestCase {
return suite;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static ImmutableIntArray makeArray(Integer[] values) {
return ImmutableIntArray.copyOf(Arrays.asList(values));
@@ -449,6 +453,7 @@ public class ImmutableIntArrayTest extends TestCase {
// Test generators. To let the GWT test suite generator access them, they need to be public named
// classes with a public default constructor (not that we run these suites under GWT yet).
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayAsListGenerator extends TestIntegerListGenerator {
@Override
@@ -457,6 +462,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayHeadSubListAsListGenerator
extends TestIntegerListGenerator {
@@ -468,6 +474,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayTailSubListAsListGenerator
extends TestIntegerListGenerator {
@@ -479,6 +486,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayMiddleSubListAsListGenerator
extends TestIntegerListGenerator {
@@ -491,11 +499,13 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static Integer[] concat(Integer[] a, Integer[] b) {
return ObjectArrays.concat(a, b, Integer.class);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public abstract static class TestIntegerListGenerator implements TestListGenerator<Integer> {
@Override
@@ -531,6 +541,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static class SampleIntegers extends SampleElements<Integer> {
public SampleIntegers() {
diff --git a/android/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java b/android/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java
index ff879ec11..cc0091190 100644
--- a/android/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.testing.ListTestSuiteBuilder;
@@ -388,6 +389,7 @@ public class ImmutableLongArrayTest extends TestCase {
assertActuallyTrims(underSized);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
assertThat(reserialize(ImmutableLongArray.of())).isSameInstanceAs(ImmutableLongArray.of());
@@ -412,6 +414,7 @@ public class ImmutableLongArrayTest extends TestCase {
assertThat(iia.trimmed()).isSameInstanceAs(iia);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Long>> builders =
@@ -443,6 +446,7 @@ public class ImmutableLongArrayTest extends TestCase {
return suite;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static ImmutableLongArray makeArray(Long[] values) {
return ImmutableLongArray.copyOf(Arrays.asList(values));
@@ -451,6 +455,7 @@ public class ImmutableLongArrayTest extends TestCase {
// Test generators. To let the GWT test suite generator access them, they need to be public named
// classes with a public default constructor (not that we run these suites under GWT yet).
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayAsListGenerator extends TestLongListGenerator {
@Override
@@ -459,6 +464,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayHeadSubListAsListGenerator
extends TestLongListGenerator {
@@ -470,6 +476,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayTailSubListAsListGenerator
extends TestLongListGenerator {
@@ -481,6 +488,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayMiddleSubListAsListGenerator
extends TestLongListGenerator {
@@ -493,11 +501,13 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static Long[] concat(Long[] a, Long[] b) {
return ObjectArrays.concat(a, b, Long.class);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public abstract static class TestLongListGenerator implements TestListGenerator<Long> {
@Override
@@ -533,6 +543,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static class SampleLongs extends SampleElements<Long> {
public SampleLongs() {
diff --git a/android/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java
index e02d1aa5a..46611f388 100644
--- a/android/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -49,6 +50,7 @@ public class IntArrayAsListTest extends TestCase {
return Ints.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Integer>> builders =
diff --git a/android/guava-tests/test/com/google/common/primitives/IntsTest.java b/android/guava-tests/test/com/google/common/primitives/IntsTest.java
index 72154224c..1a60b7f0e 100644
--- a/android/guava-tests/test/com/google/common/primitives/IntsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/IntsTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
@@ -29,6 +33,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Ints}.
@@ -36,6 +41,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class IntsTest extends TestCase {
private static final int[] EMPTY = {};
@@ -49,13 +55,13 @@ public class IntsTest extends TestCase {
public void testHashCode() {
for (int value : VALUES) {
- assertEquals(((Integer) value).hashCode(), Ints.hashCode(value));
+ assertThat(Ints.hashCode(value)).isEqualTo(((Integer) value).hashCode());
}
}
public void testCheckedCast() {
for (int value : VALUES) {
- assertEquals(value, Ints.checkedCast((long) value));
+ assertThat(Ints.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -65,12 +71,12 @@ public class IntsTest extends TestCase {
public void testSaturatedCast() {
for (int value : VALUES) {
- assertEquals(value, Ints.saturatedCast((long) value));
+ assertThat(Ints.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, Ints.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, Ints.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, Ints.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, Ints.saturatedCast(Long.MIN_VALUE));
+ assertThat(Ints.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(Ints.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(Ints.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(Ints.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -78,9 +84,9 @@ public class IntsTest extends TestCase {
Ints.checkedCast(value);
fail("Cast to int should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -88,73 +94,79 @@ public class IntsTest extends TestCase {
for (int x : VALUES) {
for (int y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Integer.valueOf(x).compareTo(y), Ints.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Ints.compare(x, y))
+ .isEqualTo(Integer.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Ints.contains(EMPTY, (int) 1));
- assertFalse(Ints.contains(ARRAY1, (int) 2));
- assertFalse(Ints.contains(ARRAY234, (int) 1));
- assertTrue(Ints.contains(new int[] {(int) -1}, (int) -1));
- assertTrue(Ints.contains(ARRAY234, (int) 2));
- assertTrue(Ints.contains(ARRAY234, (int) 3));
- assertTrue(Ints.contains(ARRAY234, (int) 4));
+ assertThat(Ints.contains(EMPTY, (int) 1)).isFalse();
+ assertThat(Ints.contains(ARRAY1, (int) 2)).isFalse();
+ assertThat(Ints.contains(ARRAY234, (int) 1)).isFalse();
+ assertThat(Ints.contains(new int[] {(int) -1}, (int) -1)).isTrue();
+ assertThat(Ints.contains(ARRAY234, (int) 2)).isTrue();
+ assertThat(Ints.contains(ARRAY234, (int) 3)).isTrue();
+ assertThat(Ints.contains(ARRAY234, (int) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Ints.indexOf(EMPTY, (int) 1));
- assertEquals(-1, Ints.indexOf(ARRAY1, (int) 2));
- assertEquals(-1, Ints.indexOf(ARRAY234, (int) 1));
- assertEquals(0, Ints.indexOf(new int[] {(int) -1}, (int) -1));
- assertEquals(0, Ints.indexOf(ARRAY234, (int) 2));
- assertEquals(1, Ints.indexOf(ARRAY234, (int) 3));
- assertEquals(2, Ints.indexOf(ARRAY234, (int) 4));
- assertEquals(1, Ints.indexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3));
+ assertThat(Ints.indexOf(EMPTY, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY1, (int) 2)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY234, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.indexOf(new int[] {(int) -1}, (int) -1)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, (int) 2)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, (int) 3)).isEqualTo(1);
+ assertThat(Ints.indexOf(ARRAY234, (int) 4)).isEqualTo(2);
+ assertThat(Ints.indexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3)).isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Ints.indexOf(EMPTY, EMPTY));
- assertEquals(0, Ints.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Ints.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Ints.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Ints.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Ints.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Ints.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Ints.indexOf(ARRAY234, new int[] {(int) 2, (int) 3}));
- assertEquals(1, Ints.indexOf(ARRAY234, new int[] {(int) 3, (int) 4}));
- assertEquals(1, Ints.indexOf(ARRAY234, new int[] {(int) 3}));
- assertEquals(2, Ints.indexOf(ARRAY234, new int[] {(int) 4}));
- assertEquals(
- 1,
- Ints.indexOf(new int[] {(int) 2, (int) 3, (int) 3, (int) 3, (int) 3}, new int[] {(int) 3}));
- assertEquals(
- 2,
- Ints.indexOf(
- new int[] {(int) 2, (int) 3, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3},
- new int[] {(int) 2, (int) 3, (int) 4}));
- assertEquals(
- 1,
- Ints.indexOf(
- new int[] {(int) 2, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3, (int) 4},
- new int[] {(int) 2, (int) 3, (int) 4}));
- assertEquals(
- -1,
- Ints.indexOf(new int[] {(int) 4, (int) 3, (int) 2}, new int[] {(int) 2, (int) 3, (int) 4}));
+ assertThat(Ints.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Ints.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 2, (int) 3})).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 3, (int) 4})).isEqualTo(1);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 3})).isEqualTo(1);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 4})).isEqualTo(2);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 2, (int) 3, (int) 3, (int) 3, (int) 3}, new int[] {(int) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 2, (int) 3, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3},
+ new int[] {(int) 2, (int) 3, (int) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 2, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3, (int) 4},
+ new int[] {(int) 2, (int) 3, (int) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 4, (int) 3, (int) 2}, new int[] {(int) 2, (int) 3, (int) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Ints.lastIndexOf(EMPTY, (int) 1));
- assertEquals(-1, Ints.lastIndexOf(ARRAY1, (int) 2));
- assertEquals(-1, Ints.lastIndexOf(ARRAY234, (int) 1));
- assertEquals(0, Ints.lastIndexOf(new int[] {(int) -1}, (int) -1));
- assertEquals(0, Ints.lastIndexOf(ARRAY234, (int) 2));
- assertEquals(1, Ints.lastIndexOf(ARRAY234, (int) 3));
- assertEquals(2, Ints.lastIndexOf(ARRAY234, (int) 4));
- assertEquals(3, Ints.lastIndexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3));
- }
-
+ assertThat(Ints.lastIndexOf(EMPTY, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.lastIndexOf(ARRAY1, (int) 2)).isEqualTo(-1);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.lastIndexOf(new int[] {(int) -1}, (int) -1)).isEqualTo(0);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 2)).isEqualTo(0);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 3)).isEqualTo(1);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 4)).isEqualTo(2);
+ assertThat(Ints.lastIndexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3))
+ .isEqualTo(3);
+ }
+
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -165,11 +177,13 @@ public class IntsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Ints.max(LEAST));
- assertEquals(GREATEST, Ints.max(GREATEST));
- assertEquals((int) 9, Ints.max((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9));
+ assertThat(Ints.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Ints.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Ints.max((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9))
+ .isEqualTo((int) 9);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -180,17 +194,18 @@ public class IntsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Ints.min(LEAST));
- assertEquals(GREATEST, Ints.min(GREATEST));
- assertEquals((int) 0, Ints.min((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9));
+ assertThat(Ints.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Ints.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Ints.min((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9))
+ .isEqualTo((int) 0);
}
public void testConstrainToRange() {
- assertEquals((int) 1, Ints.constrainToRange((int) 1, (int) 0, (int) 5));
- assertEquals((int) 1, Ints.constrainToRange((int) 1, (int) 1, (int) 5));
- assertEquals((int) 3, Ints.constrainToRange((int) 1, (int) 3, (int) 5));
- assertEquals((int) -1, Ints.constrainToRange((int) 0, (int) -5, (int) -1));
- assertEquals((int) 2, Ints.constrainToRange((int) 5, (int) 2, (int) 2));
+ assertThat(Ints.constrainToRange((int) 1, (int) 0, (int) 5)).isEqualTo((int) 1);
+ assertThat(Ints.constrainToRange((int) 1, (int) 1, (int) 5)).isEqualTo((int) 1);
+ assertThat(Ints.constrainToRange((int) 1, (int) 3, (int) 5)).isEqualTo((int) 3);
+ assertThat(Ints.constrainToRange((int) 0, (int) -5, (int) -1)).isEqualTo((int) -1);
+ assertThat(Ints.constrainToRange((int) 5, (int) 2, (int) 2)).isEqualTo((int) 2);
try {
Ints.constrainToRange((int) 1, (int) 3, (int) 2);
fail();
@@ -199,32 +214,28 @@ public class IntsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Ints.concat()));
- assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Ints.concat(ARRAY1)));
- assertNotSame(ARRAY1, Ints.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Ints.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(new int[] {(int) 1, (int) 1, (int) 1}, Ints.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new int[] {(int) 1, (int) 2, (int) 3, (int) 4}, Ints.concat(ARRAY1, ARRAY234)));
+ assertThat(Ints.concat()).isEqualTo(EMPTY);
+ assertThat(Ints.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Ints.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Ints.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Ints.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Ints.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Ints.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new int[] {(int) 1, (int) 1, (int) 1});
+ assertThat(Ints.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new int[] {(int) 1, (int) 2, (int) 3, (int) 4});
}
public void testToByteArray() {
- assertTrue(Arrays.equals(new byte[] {0x12, 0x13, 0x14, 0x15}, Ints.toByteArray(0x12131415)));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC},
- Ints.toByteArray(0xFFEEDDCC)));
+ assertThat(Ints.toByteArray(0x12131415)).isEqualTo(new byte[] {0x12, 0x13, 0x14, 0x15});
+ assertThat(Ints.toByteArray(0xFFEEDDCC))
+ .isEqualTo(new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC});
}
public void testFromByteArray() {
- assertEquals(0x12131415, Ints.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x33}));
- assertEquals(
- 0xFFEEDDCC,
- Ints.fromByteArray(new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC}));
+ assertThat(Ints.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x33})).isEqualTo(0x12131415);
+ assertThat(Ints.fromByteArray(new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC}))
+ .isEqualTo(0xFFEEDDCC);
}
public void testFromByteArrayFails() {
@@ -236,8 +247,10 @@ public class IntsTest extends TestCase {
}
public void testFromBytes() {
- assertEquals(0x12131415, Ints.fromBytes((byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15));
- assertEquals(0xFFEEDDCC, Ints.fromBytes((byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC));
+ assertThat(Ints.fromBytes((byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15))
+ .isEqualTo(0x12131415);
+ assertThat(Ints.fromBytes((byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC))
+ .isEqualTo(0xFFEEDDCC);
}
public void testByteArrayRoundTrips() {
@@ -247,19 +260,18 @@ public class IntsTest extends TestCase {
// total overkill, but, it takes 0.1 sec so why not...
for (int i = 0; i < 10000; i++) {
int num = r.nextInt();
- assertEquals(num, Ints.fromByteArray(Ints.toByteArray(num)));
+ assertThat(Ints.fromByteArray(Ints.toByteArray(num))).isEqualTo(num);
r.nextBytes(b);
- assertTrue(Arrays.equals(b, Ints.toByteArray(Ints.fromByteArray(b))));
+ assertThat(Ints.toByteArray(Ints.fromByteArray(b))).isEqualTo(b);
}
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Ints.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(new int[] {(int) 1, (int) 0, (int) 0}, Ints.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Ints.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Ints.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Ints.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Ints.ensureCapacity(ARRAY1, 2, 1)).isEqualTo(new int[] {(int) 1, (int) 0, (int) 0});
}
public void testEnsureCapacity_fail() {
@@ -277,10 +289,10 @@ public class IntsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Ints.join(",", EMPTY));
- assertEquals("1", Ints.join(",", ARRAY1));
- assertEquals("1,2", Ints.join(",", (int) 1, (int) 2));
- assertEquals("123", Ints.join("", (int) 1, (int) 2, (int) 3));
+ assertThat(Ints.join(",", EMPTY)).isEmpty();
+ assertThat(Ints.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(Ints.join(",", (int) 1, (int) 2)).isEqualTo("1,2");
+ assertThat(Ints.join("", (int) 1, (int) 2, (int) 3)).isEqualTo("123");
}
public void testLexicographicalComparator() {
@@ -300,10 +312,11 @@ public class IntsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<int[]> comparator = Ints.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -317,13 +330,13 @@ public class IntsTest extends TestCase {
private static void testReverse(int[] input, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(int[] input, int fromIndex, int toIndex, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -335,6 +348,103 @@ public class IntsTest extends TestCase {
testReverse(new int[] {-1, 1, -2, 2}, 1, 3, new int[] {-1, -2, 1, 2});
}
+ private static void testRotate(int[] input, int distance, int[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Ints.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ int[] input, int distance, int fromIndex, int toIndex, int[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Ints.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new int[] {}, -1, new int[] {});
+ testRotate(new int[] {}, 0, new int[] {});
+ testRotate(new int[] {}, 1, new int[] {});
+
+ testRotate(new int[] {1}, -2, new int[] {1});
+ testRotate(new int[] {1}, -1, new int[] {1});
+ testRotate(new int[] {1}, 0, new int[] {1});
+ testRotate(new int[] {1}, 1, new int[] {1});
+ testRotate(new int[] {1}, 2, new int[] {1});
+
+ testRotate(new int[] {1, 2}, -3, new int[] {2, 1});
+ testRotate(new int[] {1, 2}, -1, new int[] {2, 1});
+ testRotate(new int[] {1, 2}, -2, new int[] {1, 2});
+ testRotate(new int[] {1, 2}, 0, new int[] {1, 2});
+ testRotate(new int[] {1, 2}, 1, new int[] {2, 1});
+ testRotate(new int[] {1, 2}, 2, new int[] {1, 2});
+ testRotate(new int[] {1, 2}, 3, new int[] {2, 1});
+
+ testRotate(new int[] {1, 2, 3}, -5, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, -4, new int[] {2, 3, 1});
+ testRotate(new int[] {1, 2, 3}, -3, new int[] {1, 2, 3});
+ testRotate(new int[] {1, 2, 3}, -2, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, -1, new int[] {2, 3, 1});
+ testRotate(new int[] {1, 2, 3}, 0, new int[] {1, 2, 3});
+ testRotate(new int[] {1, 2, 3}, 1, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, 2, new int[] {2, 3, 1});
+ testRotate(new int[] {1, 2, 3}, 3, new int[] {1, 2, 3});
+ testRotate(new int[] {1, 2, 3}, 4, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, 5, new int[] {2, 3, 1});
+
+ testRotate(new int[] {1, 2, 3, 4}, -9, new int[] {2, 3, 4, 1});
+ testRotate(new int[] {1, 2, 3, 4}, -5, new int[] {2, 3, 4, 1});
+ testRotate(new int[] {1, 2, 3, 4}, -1, new int[] {2, 3, 4, 1});
+ testRotate(new int[] {1, 2, 3, 4}, 0, new int[] {1, 2, 3, 4});
+ testRotate(new int[] {1, 2, 3, 4}, 1, new int[] {4, 1, 2, 3});
+ testRotate(new int[] {1, 2, 3, 4}, 5, new int[] {4, 1, 2, 3});
+ testRotate(new int[] {1, 2, 3, 4}, 9, new int[] {4, 1, 2, 3});
+
+ testRotate(new int[] {1, 2, 3, 4, 5}, -6, new int[] {2, 3, 4, 5, 1});
+ testRotate(new int[] {1, 2, 3, 4, 5}, -4, new int[] {5, 1, 2, 3, 4});
+ testRotate(new int[] {1, 2, 3, 4, 5}, -3, new int[] {4, 5, 1, 2, 3});
+ testRotate(new int[] {1, 2, 3, 4, 5}, -1, new int[] {2, 3, 4, 5, 1});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 0, new int[] {1, 2, 3, 4, 5});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 1, new int[] {5, 1, 2, 3, 4});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 3, new int[] {3, 4, 5, 1, 2});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 4, new int[] {2, 3, 4, 5, 1});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 6, new int[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new int[] {}, 0, 0, 0, new int[] {});
+
+ testRotate(new int[] {1}, 0, 0, 1, new int[] {1});
+ testRotate(new int[] {1}, 1, 0, 1, new int[] {1});
+ testRotate(new int[] {1}, 1, 1, 1, new int[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new int[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new int[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new int[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new int[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new int[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new int[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new int[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new int[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new int[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new int[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new int[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new int[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new int[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new int[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new int[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new int[] {}, new int[] {});
testSortDescending(new int[] {1}, new int[] {1});
@@ -346,14 +456,14 @@ public class IntsTest extends TestCase {
private static void testSortDescending(int[] input, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
int[] input, int fromIndex, int toIndex, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -365,6 +475,7 @@ public class IntsTest extends TestCase {
testSortDescending(new int[] {-1, -2, 1, 2}, 1, 3, new int[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Ints.stringConverter());
@@ -373,17 +484,17 @@ public class IntsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Integer> none = Arrays.<Integer>asList();
- assertTrue(Arrays.equals(EMPTY, Ints.toArray(none)));
+ assertThat(Ints.toArray(none)).isEqualTo(EMPTY);
List<Integer> one = Arrays.asList((int) 1);
- assertTrue(Arrays.equals(ARRAY1, Ints.toArray(one)));
+ assertThat(Ints.toArray(one)).isEqualTo(ARRAY1);
int[] array = {(int) 0, (int) 1, (int) 0xdeadbeef};
List<Integer> three = Arrays.asList((int) 0, (int) 1, (int) 0xdeadbeef);
- assertTrue(Arrays.equals(array, Ints.toArray(three)));
+ assertThat(Ints.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Ints.toArray(Ints.asList(array))));
+ assertThat(Ints.toArray(Ints.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -393,16 +504,16 @@ public class IntsTest extends TestCase {
Collection<Integer> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
int[] arr = Ints.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Integer> list = Arrays.asList((int) 0, (int) 1, null);
+ List<@Nullable Integer> list = Arrays.asList((int) 0, (int) 1, null);
try {
Ints.toArray(list);
fail();
@@ -420,21 +531,22 @@ public class IntsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Ints.toArray(bytes)));
- assertTrue(Arrays.equals(array, Ints.toArray(shorts)));
- assertTrue(Arrays.equals(array, Ints.toArray(ints)));
- assertTrue(Arrays.equals(array, Ints.toArray(floats)));
- assertTrue(Arrays.equals(array, Ints.toArray(longs)));
- assertTrue(Arrays.equals(array, Ints.toArray(doubles)));
+ assertThat(Ints.toArray(bytes)).isEqualTo(array);
+ assertThat(Ints.toArray(shorts)).isEqualTo(array);
+ assertThat(Ints.toArray(ints)).isEqualTo(array);
+ assertThat(Ints.toArray(floats)).isEqualTo(array);
+ assertThat(Ints.toArray(longs)).isEqualTo(array);
+ assertThat(Ints.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
int[] array = {(int) 0, (int) 1};
List<Integer> list = Ints.asList(array);
list.set(0, (int) 2);
- assertTrue(Arrays.equals(new int[] {(int) 2, (int) 1}, array));
+ assertThat(array).isEqualTo(new int[] {(int) 2, (int) 1});
array[1] = (int) 3;
- assertEquals(Arrays.asList((int) 2, (int) 3), list);
+ assertThat(list).containsExactly((int) 2, (int) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -444,23 +556,24 @@ public class IntsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (int) 4);
- assertTrue(Arrays.equals(new int[] {(int) 0, (int) 1, (int) 2}, newArray));
+ assertThat(newArray).isEqualTo(new int[] {(int) 0, (int) 1, (int) 2});
newArray[1] = (int) 5;
- assertEquals((int) 1, (int) list.get(1));
+ assertThat((int) list.get(1)).isEqualTo((int) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
int[] array = {(int) 0, (int) 1, (int) 2, (int) 3};
List<Integer> list = Ints.asList(array);
- assertTrue(Arrays.equals(new int[] {(int) 1, (int) 2}, Ints.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new int[] {}, Ints.toArray(list.subList(2, 2))));
+ assertThat(Ints.toArray(list.subList(1, 3))).isEqualTo(new int[] {(int) 1, (int) 2});
+ assertThat(Ints.toArray(list.subList(2, 2))).isEqualTo(new int[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Ints.asList(EMPTY));
+ assertThat(Ints.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Ints.class);
@@ -468,14 +581,14 @@ public class IntsTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Integer> converter = Ints.stringConverter();
- assertEquals((Integer) 1, converter.convert("1"));
- assertEquals((Integer) 0, converter.convert("0"));
- assertEquals((Integer) (-1), converter.convert("-1"));
- assertEquals((Integer) 255, converter.convert("0xff"));
- assertEquals((Integer) 255, converter.convert("0xFF"));
- assertEquals((Integer) (-255), converter.convert("-0xFF"));
- assertEquals((Integer) 255, converter.convert("#0000FF"));
- assertEquals((Integer) 438, converter.convert("0666"));
+ assertThat(converter.convert("1")).isEqualTo((Integer) 1);
+ assertThat(converter.convert("0")).isEqualTo((Integer) 0);
+ assertThat(converter.convert("-1")).isEqualTo((Integer) (-1));
+ assertThat(converter.convert("0xff")).isEqualTo((Integer) 255);
+ assertThat(converter.convert("0xFF")).isEqualTo((Integer) 255);
+ assertThat(converter.convert("-0xFF")).isEqualTo((Integer) (-255));
+ assertThat(converter.convert("#0000FF")).isEqualTo((Integer) 255);
+ assertThat(converter.convert("0666")).isEqualTo((Integer) 438);
}
public void testStringConverter_convertError() {
@@ -487,21 +600,22 @@ public class IntsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Ints.stringConverter().convert(null));
- assertNull(Ints.stringConverter().reverse().convert(null));
+ assertThat(Ints.stringConverter().convert(null)).isNull();
+ assertThat(Ints.stringConverter().reverse().convert(null)).isNull();
}
public void testStringConverter_reverse() {
Converter<String, Integer> converter = Ints.stringConverter();
- assertEquals("1", converter.reverse().convert(1));
- assertEquals("0", converter.reverse().convert(0));
- assertEquals("-1", converter.reverse().convert(-1));
- assertEquals("255", converter.reverse().convert(0xff));
- assertEquals("255", converter.reverse().convert(0xFF));
- assertEquals("-255", converter.reverse().convert(-0xFF));
- assertEquals("438", converter.reverse().convert(0666));
+ assertThat(converter.reverse().convert(1)).isEqualTo("1");
+ assertThat(converter.reverse().convert(0)).isEqualTo("0");
+ assertThat(converter.reverse().convert(-1)).isEqualTo("-1");
+ assertThat(converter.reverse().convert(0xff)).isEqualTo("255");
+ assertThat(converter.reverse().convert(0xFF)).isEqualTo("255");
+ assertThat(converter.reverse().convert(-0xFF)).isEqualTo("-255");
+ assertThat(converter.reverse().convert(0666)).isEqualTo("438");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -517,17 +631,25 @@ public class IntsTest extends TestCase {
tryParseAndAssertEquals(-8900, "-8900");
tryParseAndAssertEquals(GREATEST, Integer.toString(GREATEST));
tryParseAndAssertEquals(LEAST, Integer.toString(LEAST));
- assertNull(Ints.tryParse(""));
- assertNull(Ints.tryParse("-"));
- assertNull(Ints.tryParse("+1"));
- assertNull(Ints.tryParse("9999999999999999"));
- assertNull("Max integer + 1", Ints.tryParse(Long.toString(((long) GREATEST) + 1)));
- assertNull("Max integer * 10", Ints.tryParse(Long.toString(((long) GREATEST) * 10)));
- assertNull("Min integer - 1", Ints.tryParse(Long.toString(((long) LEAST) - 1)));
- assertNull("Min integer * 10", Ints.tryParse(Long.toString(((long) LEAST) * 10)));
- assertNull("Max long", Ints.tryParse(Long.toString(Long.MAX_VALUE)));
- assertNull("Min long", Ints.tryParse(Long.toString(Long.MIN_VALUE)));
- assertNull(Ints.tryParse("\u0662\u06f3"));
+ assertThat(Ints.tryParse("")).isNull();
+ assertThat(Ints.tryParse("-")).isNull();
+ assertThat(Ints.tryParse("+1")).isNull();
+ assertThat(Ints.tryParse("9999999999999999")).isNull();
+ assertWithMessage("Max integer + 1")
+ .that(Ints.tryParse(Long.toString(((long) GREATEST) + 1)))
+ .isNull();
+ assertWithMessage("Max integer * 10")
+ .that(Ints.tryParse(Long.toString(((long) GREATEST) * 10)))
+ .isNull();
+ assertWithMessage("Min integer - 1")
+ .that(Ints.tryParse(Long.toString(((long) LEAST) - 1)))
+ .isNull();
+ assertWithMessage("Min integer * 10")
+ .that(Ints.tryParse(Long.toString(((long) LEAST) * 10)))
+ .isNull();
+ assertWithMessage("Max long").that(Ints.tryParse(Long.toString(Long.MAX_VALUE))).isNull();
+ assertWithMessage("Min long").that(Ints.tryParse(Long.toString(Long.MIN_VALUE))).isNull();
+ assertThat(Ints.tryParse("\u0662\u06f3")).isNull();
}
/**
@@ -535,7 +657,7 @@ public class IntsTest extends TestCase {
* expected.
*/
private static void tryParseAndAssertEquals(Integer expected, String value) {
- assertEquals(expected, Ints.tryParse(value));
+ assertThat(Ints.tryParse(value)).isEqualTo(expected);
}
public void testTryParse_radix() {
@@ -545,21 +667,26 @@ public class IntsTest extends TestCase {
radixEncodeParseAndAssertEquals(-8000, radix);
radixEncodeParseAndAssertEquals(GREATEST, radix);
radixEncodeParseAndAssertEquals(LEAST, radix);
- assertNull("Radix: " + radix, Ints.tryParse("9999999999999999", radix));
- assertNull(
- "Radix: " + radix, Ints.tryParse(Long.toString((long) GREATEST + 1, radix), radix));
- assertNull("Radix: " + radix, Ints.tryParse(Long.toString((long) LEAST - 1, radix), radix));
+ assertWithMessage("Radix: " + radix).that(Ints.tryParse("9999999999999999", radix)).isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(Ints.tryParse(Long.toString((long) GREATEST + 1, radix), radix))
+ .isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(Ints.tryParse(Long.toString((long) LEAST - 1, radix), radix))
+ .isNull();
}
- assertNull("Hex string and dec parm", Ints.tryParse("FFFF", 10));
- assertEquals("Mixed hex case", 65535, (int) Ints.tryParse("ffFF", 16));
+ assertWithMessage("Hex string and dec parm").that(Ints.tryParse("FFFF", 10)).isNull();
+ assertWithMessage("Mixed hex case").that((int) Ints.tryParse("ffFF", 16)).isEqualTo(65535);
}
/**
- * Encodes the an integer as a string with given radix, then uses {@link Ints#tryParse(String,
- * int)} to parse the result. Asserts the result is the same as what we started with.
+ * Encodes an integer as a string with given radix, then uses {@link Ints#tryParse(String, int)}
+ * to parse the result. Asserts the result is the same as what we started with.
*/
private static void radixEncodeParseAndAssertEquals(Integer value, int radix) {
- assertEquals("Radix: " + radix, value, Ints.tryParse(Integer.toString(value, radix), radix));
+ assertWithMessage("Radix: " + radix)
+ .that(Ints.tryParse(Integer.toString(value, radix), radix))
+ .isEqualTo(value);
}
public void testTryParse_radixTooBig() {
@@ -579,7 +706,7 @@ public class IntsTest extends TestCase {
}
public void testTryParse_withNullGwt() {
- assertNull(Ints.tryParse("null"));
+ assertThat(Ints.tryParse("null")).isNull();
try {
Ints.tryParse(null);
fail("Expected NPE");
diff --git a/android/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java
index 1c51e7ea0..4a6325153 100644
--- a/android/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class LongArrayAsListTest extends TestCase {
return Longs.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Long>> builders =
diff --git a/android/guava-tests/test/com/google/common/primitives/LongsTest.java b/android/guava-tests/test/com/google/common/primitives/LongsTest.java
index 236d46165..83363c411 100644
--- a/android/guava-tests/test/com/google/common/primitives/LongsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/LongsTest.java
@@ -16,11 +16,14 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Long.MAX_VALUE;
import static java.lang.Long.MIN_VALUE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
@@ -33,12 +36,14 @@ import java.util.Comparator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Longs}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class LongsTest extends TestCase {
@@ -48,10 +53,13 @@ public class LongsTest extends TestCase {
private static final long[] VALUES = {MIN_VALUE, (long) -1, (long) 0, (long) 1, MAX_VALUE};
+ @J2ktIncompatible
@GwtIncompatible // Long.hashCode returns different values in GWT.
public void testHashCode() {
for (long value : VALUES) {
- assertEquals("hashCode for " + value, ((Long) value).hashCode(), Longs.hashCode(value));
+ assertWithMessage("hashCode for " + value)
+ .that(Longs.hashCode(value))
+ .isEqualTo(((Long) value).hashCode());
}
}
@@ -59,74 +67,79 @@ public class LongsTest extends TestCase {
for (long x : VALUES) {
for (long y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Long.valueOf(x).compareTo(y), Longs.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Longs.compare(x, y))
+ .isEqualTo(Long.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Longs.contains(EMPTY, (long) 1));
- assertFalse(Longs.contains(ARRAY1, (long) 2));
- assertFalse(Longs.contains(ARRAY234, (long) 1));
- assertTrue(Longs.contains(new long[] {(long) -1}, (long) -1));
- assertTrue(Longs.contains(ARRAY234, (long) 2));
- assertTrue(Longs.contains(ARRAY234, (long) 3));
- assertTrue(Longs.contains(ARRAY234, (long) 4));
+ assertThat(Longs.contains(EMPTY, (long) 1)).isFalse();
+ assertThat(Longs.contains(ARRAY1, (long) 2)).isFalse();
+ assertThat(Longs.contains(ARRAY234, (long) 1)).isFalse();
+ assertThat(Longs.contains(new long[] {(long) -1}, (long) -1)).isTrue();
+ assertThat(Longs.contains(ARRAY234, (long) 2)).isTrue();
+ assertThat(Longs.contains(ARRAY234, (long) 3)).isTrue();
+ assertThat(Longs.contains(ARRAY234, (long) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Longs.indexOf(EMPTY, (long) 1));
- assertEquals(-1, Longs.indexOf(ARRAY1, (long) 2));
- assertEquals(-1, Longs.indexOf(ARRAY234, (long) 1));
- assertEquals(0, Longs.indexOf(new long[] {(long) -1}, (long) -1));
- assertEquals(0, Longs.indexOf(ARRAY234, (long) 2));
- assertEquals(1, Longs.indexOf(ARRAY234, (long) 3));
- assertEquals(2, Longs.indexOf(ARRAY234, (long) 4));
- assertEquals(1, Longs.indexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3));
+ assertThat(Longs.indexOf(EMPTY, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY1, (long) 2)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY234, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.indexOf(new long[] {(long) -1}, (long) -1)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, (long) 2)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, (long) 3)).isEqualTo(1);
+ assertThat(Longs.indexOf(ARRAY234, (long) 4)).isEqualTo(2);
+ assertThat(Longs.indexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Longs.indexOf(EMPTY, EMPTY));
- assertEquals(0, Longs.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Longs.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Longs.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Longs.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Longs.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Longs.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Longs.indexOf(ARRAY234, new long[] {(long) 2, (long) 3}));
- assertEquals(1, Longs.indexOf(ARRAY234, new long[] {(long) 3, (long) 4}));
- assertEquals(1, Longs.indexOf(ARRAY234, new long[] {(long) 3}));
- assertEquals(2, Longs.indexOf(ARRAY234, new long[] {(long) 4}));
- assertEquals(
- 1,
- Longs.indexOf(
- new long[] {(long) 2, (long) 3, (long) 3, (long) 3, (long) 3}, new long[] {(long) 3}));
- assertEquals(
- 2,
- Longs.indexOf(
- new long[] {(long) 2, (long) 3, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3},
- new long[] {(long) 2, (long) 3, (long) 4}));
- assertEquals(
- 1,
- Longs.indexOf(
- new long[] {(long) 2, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3, (long) 4},
- new long[] {(long) 2, (long) 3, (long) 4}));
- assertEquals(
- -1,
- Longs.indexOf(
- new long[] {(long) 4, (long) 3, (long) 2}, new long[] {(long) 2, (long) 3, (long) 4}));
+ assertThat(Longs.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Longs.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 2, (long) 3})).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 3, (long) 4})).isEqualTo(1);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 3})).isEqualTo(1);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 4})).isEqualTo(2);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 2, (long) 3, (long) 3, (long) 3, (long) 3},
+ new long[] {(long) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 2, (long) 3, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3},
+ new long[] {(long) 2, (long) 3, (long) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 2, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3, (long) 4},
+ new long[] {(long) 2, (long) 3, (long) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 4, (long) 3, (long) 2},
+ new long[] {(long) 2, (long) 3, (long) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Longs.lastIndexOf(EMPTY, (long) 1));
- assertEquals(-1, Longs.lastIndexOf(ARRAY1, (long) 2));
- assertEquals(-1, Longs.lastIndexOf(ARRAY234, (long) 1));
- assertEquals(0, Longs.lastIndexOf(new long[] {(long) -1}, (long) -1));
- assertEquals(0, Longs.lastIndexOf(ARRAY234, (long) 2));
- assertEquals(1, Longs.lastIndexOf(ARRAY234, (long) 3));
- assertEquals(2, Longs.lastIndexOf(ARRAY234, (long) 4));
- assertEquals(
- 3, Longs.lastIndexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3));
+ assertThat(Longs.lastIndexOf(EMPTY, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.lastIndexOf(ARRAY1, (long) 2)).isEqualTo(-1);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.lastIndexOf(new long[] {(long) -1}, (long) -1)).isEqualTo(0);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 2)).isEqualTo(0);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 3)).isEqualTo(1);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 4)).isEqualTo(2);
+ assertThat(Longs.lastIndexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3))
+ .isEqualTo(3);
}
public void testMax_noArgs() {
@@ -138,10 +151,10 @@ public class LongsTest extends TestCase {
}
public void testMax() {
- assertEquals(MIN_VALUE, Longs.max(MIN_VALUE));
- assertEquals(MAX_VALUE, Longs.max(MAX_VALUE));
- assertEquals(
- (long) 9, Longs.max((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9));
+ assertThat(Longs.max(MIN_VALUE)).isEqualTo(MIN_VALUE);
+ assertThat(Longs.max(MAX_VALUE)).isEqualTo(MAX_VALUE);
+ assertThat(Longs.max((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9))
+ .isEqualTo((long) 9);
}
public void testMin_noArgs() {
@@ -153,18 +166,18 @@ public class LongsTest extends TestCase {
}
public void testMin() {
- assertEquals(MIN_VALUE, Longs.min(MIN_VALUE));
- assertEquals(MAX_VALUE, Longs.min(MAX_VALUE));
- assertEquals(
- (long) 0, Longs.min((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9));
+ assertThat(Longs.min(MIN_VALUE)).isEqualTo(MIN_VALUE);
+ assertThat(Longs.min(MAX_VALUE)).isEqualTo(MAX_VALUE);
+ assertThat(Longs.min((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9))
+ .isEqualTo((long) 0);
}
public void testConstrainToRange() {
- assertEquals((long) 1, Longs.constrainToRange((long) 1, (long) 0, (long) 5));
- assertEquals((long) 1, Longs.constrainToRange((long) 1, (long) 1, (long) 5));
- assertEquals((long) 3, Longs.constrainToRange((long) 1, (long) 3, (long) 5));
- assertEquals((long) -1, Longs.constrainToRange((long) 0, (long) -5, (long) -1));
- assertEquals((long) 2, Longs.constrainToRange((long) 5, (long) 2, (long) 2));
+ assertThat(Longs.constrainToRange((long) 1, (long) 0, (long) 5)).isEqualTo((long) 1);
+ assertThat(Longs.constrainToRange((long) 1, (long) 1, (long) 5)).isEqualTo((long) 1);
+ assertThat(Longs.constrainToRange((long) 1, (long) 3, (long) 5)).isEqualTo((long) 3);
+ assertThat(Longs.constrainToRange((long) 0, (long) -5, (long) -1)).isEqualTo((long) -1);
+ assertThat(Longs.constrainToRange((long) 5, (long) 2, (long) 2)).isEqualTo((long) 2);
try {
Longs.constrainToRange((long) 1, (long) 3, (long) 2);
fail();
@@ -173,24 +186,54 @@ public class LongsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Longs.concat()));
- assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Longs.concat(ARRAY1)));
- assertNotSame(ARRAY1, Longs.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Longs.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new long[] {(long) 1, (long) 1, (long) 1}, Longs.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new long[] {(long) 1, (long) 2, (long) 3, (long) 4}, Longs.concat(ARRAY1, ARRAY234)));
+ assertThat(Longs.concat()).isEqualTo(EMPTY);
+ assertThat(Longs.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Longs.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Longs.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Longs.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Longs.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Longs.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new long[] {(long) 1, (long) 1, (long) 1});
+ assertThat(Longs.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new long[] {(long) 1, (long) 2, (long) 3, (long) 4});
+ }
+
+ @GwtIncompatible // different overflow behavior; could probably be made to work by using ~~
+ public void testConcat_overflow_negative() {
+ int dim1 = 1 << 16;
+ int dim2 = 1 << 15;
+ assertThat(dim1 * dim2).isLessThan(0);
+ testConcat_overflow(dim1, dim2);
+ }
+
+ @GwtIncompatible // different overflow behavior; could probably be made to work by using ~~
+ public void testConcat_overflow_nonNegative() {
+ int dim1 = 1 << 16;
+ int dim2 = 1 << 16;
+ assertThat(dim1 * dim2).isAtLeast(0);
+ testConcat_overflow(dim1, dim2);
+ }
+
+ private static void testConcat_overflow(int arraysDim1, int arraysDim2) {
+ assertThat((long) arraysDim1 * arraysDim2).isNotEqualTo((long) (arraysDim1 * arraysDim2));
+
+ long[][] arrays = new long[arraysDim1][];
+ // it's shared to avoid using too much memory in tests
+ long[] sharedArray = new long[arraysDim2];
+ Arrays.fill(arrays, sharedArray);
+
+ try {
+ Longs.concat(arrays);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
}
private static void assertByteArrayEquals(byte[] expected, byte[] actual) {
- assertTrue(
- "Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual),
- Arrays.equals(expected, actual));
+ assertWithMessage(
+ "Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual))
+ .that(Arrays.equals(expected, actual))
+ .isTrue();
}
public void testToByteArray() {
@@ -206,16 +249,16 @@ public class LongsTest extends TestCase {
}
public void testFromByteArray() {
- assertEquals(
- 0x1213141516171819L,
- Longs.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33}));
- assertEquals(
- 0xFFEEDDCCBBAA9988L,
- Longs.fromByteArray(
- new byte[] {
- (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
- (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88
- }));
+ assertThat(
+ Longs.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33}))
+ .isEqualTo(0x1213141516171819L);
+ assertThat(
+ Longs.fromByteArray(
+ new byte[] {
+ (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
+ (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88
+ }))
+ .isEqualTo(0xFFEEDDCCBBAA9988L);
}
public void testFromByteArrayFails() {
@@ -227,28 +270,28 @@ public class LongsTest extends TestCase {
}
public void testFromBytes() {
- assertEquals(
- 0x1213141516171819L,
- Longs.fromBytes(
- (byte) 0x12,
- (byte) 0x13,
- (byte) 0x14,
- (byte) 0x15,
- (byte) 0x16,
- (byte) 0x17,
- (byte) 0x18,
- (byte) 0x19));
- assertEquals(
- 0xFFEEDDCCBBAA9988L,
- Longs.fromBytes(
- (byte) 0xFF,
- (byte) 0xEE,
- (byte) 0xDD,
- (byte) 0xCC,
- (byte) 0xBB,
- (byte) 0xAA,
- (byte) 0x99,
- (byte) 0x88));
+ assertThat(
+ Longs.fromBytes(
+ (byte) 0x12,
+ (byte) 0x13,
+ (byte) 0x14,
+ (byte) 0x15,
+ (byte) 0x16,
+ (byte) 0x17,
+ (byte) 0x18,
+ (byte) 0x19))
+ .isEqualTo(0x1213141516171819L);
+ assertThat(
+ Longs.fromBytes(
+ (byte) 0xFF,
+ (byte) 0xEE,
+ (byte) 0xDD,
+ (byte) 0xCC,
+ (byte) 0xBB,
+ (byte) 0xAA,
+ (byte) 0x99,
+ (byte) 0x88))
+ .isEqualTo(0xFFEEDDCCBBAA9988L);
}
public void testByteArrayRoundTrips() {
@@ -257,21 +300,20 @@ public class LongsTest extends TestCase {
for (int i = 0; i < 1000; i++) {
long num = r.nextLong();
- assertEquals(num, Longs.fromByteArray(Longs.toByteArray(num)));
+ assertThat(Longs.fromByteArray(Longs.toByteArray(num))).isEqualTo(num);
r.nextBytes(b);
long value = Longs.fromByteArray(b);
- assertTrue("" + value, Arrays.equals(b, Longs.toByteArray(value)));
+ assertWithMessage("" + value).that(Arrays.equals(b, Longs.toByteArray(value))).isTrue();
}
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Longs.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new long[] {(long) 1, (long) 0, (long) 0}, Longs.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Longs.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Longs.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Longs.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Longs.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new long[] {(long) 1, (long) 0, (long) 0});
}
public void testEnsureCapacity_fail() {
@@ -289,10 +331,10 @@ public class LongsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Longs.join(",", EMPTY));
- assertEquals("1", Longs.join(",", ARRAY1));
- assertEquals("1,2", Longs.join(",", (long) 1, (long) 2));
- assertEquals("123", Longs.join("", (long) 1, (long) 2, (long) 3));
+ assertThat(Longs.join(",", EMPTY)).isEmpty();
+ assertThat(Longs.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(Longs.join(",", (long) 1, (long) 2)).isEqualTo("1,2");
+ assertThat(Longs.join("", (long) 1, (long) 2, (long) 3)).isEqualTo("123");
}
public void testLexicographicalComparator() {
@@ -312,10 +354,11 @@ public class LongsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<long[]> comparator = Longs.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -329,13 +372,13 @@ public class LongsTest extends TestCase {
private static void testReverse(long[] input, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(long[] input, int fromIndex, int toIndex, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -347,6 +390,103 @@ public class LongsTest extends TestCase {
testReverse(new long[] {-1, 1, -2, 2}, 1, 3, new long[] {-1, -2, 1, 2});
}
+ private static void testRotate(long[] input, int distance, long[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Longs.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ long[] input, int distance, int fromIndex, int toIndex, long[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Longs.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new long[] {}, -1, new long[] {});
+ testRotate(new long[] {}, 0, new long[] {});
+ testRotate(new long[] {}, 1, new long[] {});
+
+ testRotate(new long[] {1}, -2, new long[] {1});
+ testRotate(new long[] {1}, -1, new long[] {1});
+ testRotate(new long[] {1}, 0, new long[] {1});
+ testRotate(new long[] {1}, 1, new long[] {1});
+ testRotate(new long[] {1}, 2, new long[] {1});
+
+ testRotate(new long[] {1, 2}, -3, new long[] {2, 1});
+ testRotate(new long[] {1, 2}, -1, new long[] {2, 1});
+ testRotate(new long[] {1, 2}, -2, new long[] {1, 2});
+ testRotate(new long[] {1, 2}, 0, new long[] {1, 2});
+ testRotate(new long[] {1, 2}, 1, new long[] {2, 1});
+ testRotate(new long[] {1, 2}, 2, new long[] {1, 2});
+ testRotate(new long[] {1, 2}, 3, new long[] {2, 1});
+
+ testRotate(new long[] {1, 2, 3}, -5, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, -4, new long[] {2, 3, 1});
+ testRotate(new long[] {1, 2, 3}, -3, new long[] {1, 2, 3});
+ testRotate(new long[] {1, 2, 3}, -2, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, -1, new long[] {2, 3, 1});
+ testRotate(new long[] {1, 2, 3}, 0, new long[] {1, 2, 3});
+ testRotate(new long[] {1, 2, 3}, 1, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, 2, new long[] {2, 3, 1});
+ testRotate(new long[] {1, 2, 3}, 3, new long[] {1, 2, 3});
+ testRotate(new long[] {1, 2, 3}, 4, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, 5, new long[] {2, 3, 1});
+
+ testRotate(new long[] {1, 2, 3, 4}, -9, new long[] {2, 3, 4, 1});
+ testRotate(new long[] {1, 2, 3, 4}, -5, new long[] {2, 3, 4, 1});
+ testRotate(new long[] {1, 2, 3, 4}, -1, new long[] {2, 3, 4, 1});
+ testRotate(new long[] {1, 2, 3, 4}, 0, new long[] {1, 2, 3, 4});
+ testRotate(new long[] {1, 2, 3, 4}, 1, new long[] {4, 1, 2, 3});
+ testRotate(new long[] {1, 2, 3, 4}, 5, new long[] {4, 1, 2, 3});
+ testRotate(new long[] {1, 2, 3, 4}, 9, new long[] {4, 1, 2, 3});
+
+ testRotate(new long[] {1, 2, 3, 4, 5}, -6, new long[] {2, 3, 4, 5, 1});
+ testRotate(new long[] {1, 2, 3, 4, 5}, -4, new long[] {5, 1, 2, 3, 4});
+ testRotate(new long[] {1, 2, 3, 4, 5}, -3, new long[] {4, 5, 1, 2, 3});
+ testRotate(new long[] {1, 2, 3, 4, 5}, -1, new long[] {2, 3, 4, 5, 1});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 0, new long[] {1, 2, 3, 4, 5});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 1, new long[] {5, 1, 2, 3, 4});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 3, new long[] {3, 4, 5, 1, 2});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 4, new long[] {2, 3, 4, 5, 1});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 6, new long[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new long[] {}, 0, 0, 0, new long[] {});
+
+ testRotate(new long[] {1}, 0, 0, 1, new long[] {1});
+ testRotate(new long[] {1}, 1, 0, 1, new long[] {1});
+ testRotate(new long[] {1}, 1, 1, 1, new long[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new long[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new long[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new long[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new long[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new long[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new long[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new long[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new long[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new long[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new long[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new long[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new long[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new long[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new long[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new long[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new long[] {}, new long[] {});
testSortDescending(new long[] {1}, new long[] {1});
@@ -358,14 +498,14 @@ public class LongsTest extends TestCase {
private static void testSortDescending(long[] input, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
long[] input, int fromIndex, int toIndex, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -377,6 +517,7 @@ public class LongsTest extends TestCase {
testSortDescending(new long[] {-1, -2, 1, 2}, 1, 3, new long[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Longs.stringConverter());
@@ -385,17 +526,17 @@ public class LongsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Long> none = Arrays.<Long>asList();
- assertTrue(Arrays.equals(EMPTY, Longs.toArray(none)));
+ assertThat(Longs.toArray(none)).isEqualTo(EMPTY);
List<Long> one = Arrays.asList((long) 1);
- assertTrue(Arrays.equals(ARRAY1, Longs.toArray(one)));
+ assertThat(Longs.toArray(one)).isEqualTo(ARRAY1);
long[] array = {(long) 0, (long) 1, 0x0FF1C1AL};
List<Long> three = Arrays.asList((long) 0, (long) 1, 0x0FF1C1AL);
- assertTrue(Arrays.equals(array, Longs.toArray(three)));
+ assertThat(Longs.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Longs.toArray(Longs.asList(array))));
+ assertThat(Longs.toArray(Longs.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -405,16 +546,16 @@ public class LongsTest extends TestCase {
Collection<Long> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
long[] arr = Longs.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Long> list = Arrays.asList((long) 0, (long) 1, null);
+ List<@Nullable Long> list = Arrays.asList((long) 0, (long) 1, null);
try {
Longs.toArray(list);
fail();
@@ -432,21 +573,22 @@ public class LongsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Longs.toArray(bytes)));
- assertTrue(Arrays.equals(array, Longs.toArray(shorts)));
- assertTrue(Arrays.equals(array, Longs.toArray(ints)));
- assertTrue(Arrays.equals(array, Longs.toArray(floats)));
- assertTrue(Arrays.equals(array, Longs.toArray(longs)));
- assertTrue(Arrays.equals(array, Longs.toArray(doubles)));
+ assertThat(Longs.toArray(bytes)).isEqualTo(array);
+ assertThat(Longs.toArray(shorts)).isEqualTo(array);
+ assertThat(Longs.toArray(ints)).isEqualTo(array);
+ assertThat(Longs.toArray(floats)).isEqualTo(array);
+ assertThat(Longs.toArray(longs)).isEqualTo(array);
+ assertThat(Longs.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
long[] array = {(long) 0, (long) 1};
List<Long> list = Longs.asList(array);
list.set(0, (long) 2);
- assertTrue(Arrays.equals(new long[] {(long) 2, (long) 1}, array));
+ assertThat(array).isEqualTo(new long[] {(long) 2, (long) 1});
array[1] = (long) 3;
- assertEquals(Arrays.asList((long) 2, (long) 3), list);
+ assertThat(list).containsExactly((long) 2, (long) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -456,23 +598,24 @@ public class LongsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (long) 4);
- assertTrue(Arrays.equals(new long[] {(long) 0, (long) 1, (long) 2}, newArray));
+ assertThat(newArray).isEqualTo(new long[] {(long) 0, (long) 1, (long) 2});
newArray[1] = (long) 5;
- assertEquals((long) 1, (long) list.get(1));
+ assertThat((long) list.get(1)).isEqualTo((long) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
long[] array = {(long) 0, (long) 1, (long) 2, (long) 3};
List<Long> list = Longs.asList(array);
- assertTrue(Arrays.equals(new long[] {(long) 1, (long) 2}, Longs.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new long[] {}, Longs.toArray(list.subList(2, 2))));
+ assertThat(Longs.toArray(list.subList(1, 3))).isEqualTo(new long[] {(long) 1, (long) 2});
+ assertThat(Longs.toArray(list.subList(2, 2))).isEqualTo(new long[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Longs.asList(EMPTY));
+ assertThat(Longs.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Longs.class);
@@ -480,14 +623,14 @@ public class LongsTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Long> converter = Longs.stringConverter();
- assertEquals((Long) 1L, converter.convert("1"));
- assertEquals((Long) 0L, converter.convert("0"));
- assertEquals((Long) (-1L), converter.convert("-1"));
- assertEquals((Long) 255L, converter.convert("0xff"));
- assertEquals((Long) 255L, converter.convert("0xFF"));
- assertEquals((Long) (-255L), converter.convert("-0xFF"));
- assertEquals((Long) 255L, converter.convert("#0000FF"));
- assertEquals((Long) 438L, converter.convert("0666"));
+ assertThat(converter.convert("1")).isEqualTo((Long) 1L);
+ assertThat(converter.convert("0")).isEqualTo((Long) 0L);
+ assertThat(converter.convert("-1")).isEqualTo((Long) (-1L));
+ assertThat(converter.convert("0xff")).isEqualTo((Long) 255L);
+ assertThat(converter.convert("0xFF")).isEqualTo((Long) 255L);
+ assertThat(converter.convert("-0xFF")).isEqualTo((Long) (-255L));
+ assertThat(converter.convert("#0000FF")).isEqualTo((Long) 255L);
+ assertThat(converter.convert("0666")).isEqualTo((Long) 438L);
}
public void testStringConverter_convertError() {
@@ -499,21 +642,22 @@ public class LongsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Longs.stringConverter().convert(null));
- assertNull(Longs.stringConverter().reverse().convert(null));
+ assertThat(Longs.stringConverter().convert(null)).isNull();
+ assertThat(Longs.stringConverter().reverse().convert(null)).isNull();
}
public void testStringConverter_reverse() {
Converter<String, Long> converter = Longs.stringConverter();
- assertEquals("1", converter.reverse().convert(1L));
- assertEquals("0", converter.reverse().convert(0L));
- assertEquals("-1", converter.reverse().convert(-1L));
- assertEquals("255", converter.reverse().convert(0xffL));
- assertEquals("255", converter.reverse().convert(0xFFL));
- assertEquals("-255", converter.reverse().convert(-0xFFL));
- assertEquals("438", converter.reverse().convert(0666L));
+ assertThat(converter.reverse().convert(1L)).isEqualTo("1");
+ assertThat(converter.reverse().convert(0L)).isEqualTo("0");
+ assertThat(converter.reverse().convert(-1L)).isEqualTo("-1");
+ assertThat(converter.reverse().convert(0xffL)).isEqualTo("255");
+ assertThat(converter.reverse().convert(0xFFL)).isEqualTo("255");
+ assertThat(converter.reverse().convert(-0xFFL)).isEqualTo("-255");
+ assertThat(converter.reverse().convert(0666L)).isEqualTo("438");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -529,23 +673,23 @@ public class LongsTest extends TestCase {
tryParseAndAssertEquals(-8900L, "-8900");
tryParseAndAssertEquals(MAX_VALUE, Long.toString(MAX_VALUE));
tryParseAndAssertEquals(MIN_VALUE, Long.toString(MIN_VALUE));
- assertNull(Longs.tryParse(""));
- assertNull(Longs.tryParse("-"));
- assertNull(Longs.tryParse("+1"));
- assertNull(Longs.tryParse("999999999999999999999999"));
- assertNull(
- "Max long + 1",
- Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString()));
- assertNull(
- "Max long * 10",
- Longs.tryParse(BigInteger.valueOf(MAX_VALUE).multiply(BigInteger.TEN).toString()));
- assertNull(
- "Min long - 1",
- Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString()));
- assertNull(
- "Min long * 10",
- Longs.tryParse(BigInteger.valueOf(MIN_VALUE).multiply(BigInteger.TEN).toString()));
- assertNull(Longs.tryParse("\u0662\u06f3"));
+ assertThat(Longs.tryParse("")).isNull();
+ assertThat(Longs.tryParse("-")).isNull();
+ assertThat(Longs.tryParse("+1")).isNull();
+ assertThat(Longs.tryParse("999999999999999999999999")).isNull();
+ assertWithMessage("Max long + 1")
+ .that(Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString()))
+ .isNull();
+ assertWithMessage("Max long * 10")
+ .that(Longs.tryParse(BigInteger.valueOf(MAX_VALUE).multiply(BigInteger.TEN).toString()))
+ .isNull();
+ assertWithMessage("Min long - 1")
+ .that(Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString()))
+ .isNull();
+ assertWithMessage("Min long * 10")
+ .that(Longs.tryParse(BigInteger.valueOf(MIN_VALUE).multiply(BigInteger.TEN).toString()))
+ .isNull();
+ assertThat(Longs.tryParse("\u0662\u06f3")).isNull();
}
/**
@@ -553,7 +697,7 @@ public class LongsTest extends TestCase {
* expected.
*/
private static void tryParseAndAssertEquals(Long expected, String value) {
- assertEquals(expected, Longs.tryParse(value));
+ assertThat(Longs.tryParse(value)).isEqualTo(expected);
}
public void testTryParse_radix() {
@@ -563,16 +707,22 @@ public class LongsTest extends TestCase {
radixEncodeParseAndAssertEquals((long) -8000, radix);
radixEncodeParseAndAssertEquals(MAX_VALUE, radix);
radixEncodeParseAndAssertEquals(MIN_VALUE, radix);
- assertNull("Radix: " + radix, Longs.tryParse("999999999999999999999999", radix));
- assertNull(
- "Radix: " + radix,
- Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString(), radix));
- assertNull(
- "Radix: " + radix,
- Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString(), radix));
+ assertWithMessage("Radix: " + radix)
+ .that(Longs.tryParse("999999999999999999999999", radix))
+ .isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString(), radix))
+ .isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(
+ Longs.tryParse(
+ BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString(), radix))
+ .isNull();
}
- assertNull("Hex string and dec parm", Longs.tryParse("FFFF", 10));
- assertEquals("Mixed hex case", 65535, Longs.tryParse("ffFF", 16).longValue());
+ assertWithMessage("Hex string and dec parm").that(Longs.tryParse("FFFF", 10)).isNull();
+ assertWithMessage("Mixed hex case")
+ .that(Longs.tryParse("ffFF", 16).longValue())
+ .isEqualTo(65535);
}
/**
@@ -580,7 +730,9 @@ public class LongsTest extends TestCase {
* parse the result. Asserts the result is the same as what we started with.
*/
private static void radixEncodeParseAndAssertEquals(Long value, int radix) {
- assertEquals("Radix: " + radix, value, Longs.tryParse(Long.toString(value, radix), radix));
+ assertWithMessage("Radix: " + radix)
+ .that(Longs.tryParse(Long.toString(value, radix), radix))
+ .isEqualTo(value);
}
public void testTryParse_radixTooBig() {
@@ -600,7 +752,7 @@ public class LongsTest extends TestCase {
}
public void testTryParse_withNullGwt() {
- assertNull(Longs.tryParse("null"));
+ assertThat(Longs.tryParse("null")).isNull();
try {
Longs.tryParse(null);
fail("Expected NPE");
diff --git a/android/guava-tests/test/com/google/common/primitives/PrimitivesTest.java b/android/guava-tests/test/com/google/common/primitives/PrimitivesTest.java
index 1e0974365..05cdc953a 100644
--- a/android/guava-tests/test/com/google/common/primitives/PrimitivesTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/PrimitivesTest.java
@@ -16,7 +16,11 @@
package com.google.common.primitives;
-import com.google.common.collect.ImmutableSet;
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import java.util.Set;
import junit.framework.TestCase;
@@ -26,28 +30,29 @@ import junit.framework.TestCase;
*
* @author Kevin Bourrillion
*/
+@GwtCompatible(emulated = true)
public class PrimitivesTest extends TestCase {
public void testIsWrapperType() {
- assertTrue(Primitives.isWrapperType(Void.class));
- assertFalse(Primitives.isWrapperType(void.class));
+ assertThat(Primitives.isWrapperType(Void.class)).isTrue();
+ assertThat(Primitives.isWrapperType(void.class)).isFalse();
}
public void testWrap() {
- assertSame(Integer.class, Primitives.wrap(int.class));
- assertSame(Integer.class, Primitives.wrap(Integer.class));
- assertSame(String.class, Primitives.wrap(String.class));
+ assertThat(Primitives.wrap(int.class)).isSameInstanceAs(Integer.class);
+ assertThat(Primitives.wrap(Integer.class)).isSameInstanceAs(Integer.class);
+ assertThat(Primitives.wrap(String.class)).isSameInstanceAs(String.class);
}
public void testUnwrap() {
- assertSame(int.class, Primitives.unwrap(Integer.class));
- assertSame(int.class, Primitives.unwrap(int.class));
- assertSame(String.class, Primitives.unwrap(String.class));
+ assertThat(Primitives.unwrap(Integer.class)).isSameInstanceAs(int.class);
+ assertThat(Primitives.unwrap(int.class)).isSameInstanceAs(int.class);
+ assertThat(Primitives.unwrap(String.class)).isSameInstanceAs(String.class);
}
public void testAllPrimitiveTypes() {
Set<Class<?>> primitives = Primitives.allPrimitiveTypes();
- assertEquals(
- ImmutableSet.<Object>of(
+ assertThat(primitives)
+ .containsExactly(
boolean.class,
byte.class,
char.class,
@@ -56,8 +61,7 @@ public class PrimitivesTest extends TestCase {
int.class,
long.class,
short.class,
- void.class),
- primitives);
+ void.class);
try {
primitives.remove(boolean.class);
@@ -68,8 +72,8 @@ public class PrimitivesTest extends TestCase {
public void testAllWrapperTypes() {
Set<Class<?>> wrappers = Primitives.allWrapperTypes();
- assertEquals(
- ImmutableSet.<Object>of(
+ assertThat(wrappers)
+ .containsExactly(
Boolean.class,
Byte.class,
Character.class,
@@ -78,8 +82,7 @@ public class PrimitivesTest extends TestCase {
Integer.class,
Long.class,
Short.class,
- Void.class),
- wrappers);
+ Void.class);
try {
wrappers.remove(Boolean.class);
@@ -88,6 +91,8 @@ public class PrimitivesTest extends TestCase {
}
}
+ @GwtIncompatible
+ @J2ktIncompatible
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicStaticMethods(Primitives.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java b/android/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java
index 9a1fada72..a79211a31 100644
--- a/android/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class ShortArrayAsListTest extends TestCase {
return Shorts.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Short>> builders =
diff --git a/android/guava-tests/test/com/google/common/primitives/ShortsTest.java b/android/guava-tests/test/com/google/common/primitives/ShortsTest.java
index 0816c6973..26eb04779 100644
--- a/android/guava-tests/test/com/google/common/primitives/ShortsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/ShortsTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
@@ -29,12 +33,14 @@ import java.util.Comparator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Shorts}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class ShortsTest extends TestCase {
@@ -49,13 +55,13 @@ public class ShortsTest extends TestCase {
public void testHashCode() {
for (short value : VALUES) {
- assertEquals(((Short) value).hashCode(), Shorts.hashCode(value));
+ assertThat(Shorts.hashCode(value)).isEqualTo(((Short) value).hashCode());
}
}
public void testCheckedCast() {
for (short value : VALUES) {
- assertEquals(value, Shorts.checkedCast((long) value));
+ assertThat(Shorts.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -65,12 +71,12 @@ public class ShortsTest extends TestCase {
public void testSaturatedCast() {
for (short value : VALUES) {
- assertEquals(value, Shorts.saturatedCast((long) value));
+ assertThat(Shorts.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, Shorts.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, Shorts.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, Shorts.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, Shorts.saturatedCast(Long.MIN_VALUE));
+ assertThat(Shorts.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(Shorts.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(Shorts.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(Shorts.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -78,9 +84,9 @@ public class ShortsTest extends TestCase {
Shorts.checkedCast(value);
fail("Cast to short should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -91,90 +97,94 @@ public class ShortsTest extends TestCase {
int expected = Short.valueOf(x).compareTo(y);
int actual = Shorts.compare(x, y);
if (expected == 0) {
- assertEquals(x + ", " + y, expected, actual);
+ assertWithMessage(x + ", " + y).that(actual).isEqualTo(expected);
} else if (expected < 0) {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual < 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual < 0)
+ .isTrue();
} else {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual > 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual > 0)
+ .isTrue();
}
}
}
}
public void testContains() {
- assertFalse(Shorts.contains(EMPTY, (short) 1));
- assertFalse(Shorts.contains(ARRAY1, (short) 2));
- assertFalse(Shorts.contains(ARRAY234, (short) 1));
- assertTrue(Shorts.contains(new short[] {(short) -1}, (short) -1));
- assertTrue(Shorts.contains(ARRAY234, (short) 2));
- assertTrue(Shorts.contains(ARRAY234, (short) 3));
- assertTrue(Shorts.contains(ARRAY234, (short) 4));
+ assertThat(Shorts.contains(EMPTY, (short) 1)).isFalse();
+ assertThat(Shorts.contains(ARRAY1, (short) 2)).isFalse();
+ assertThat(Shorts.contains(ARRAY234, (short) 1)).isFalse();
+ assertThat(Shorts.contains(new short[] {(short) -1}, (short) -1)).isTrue();
+ assertThat(Shorts.contains(ARRAY234, (short) 2)).isTrue();
+ assertThat(Shorts.contains(ARRAY234, (short) 3)).isTrue();
+ assertThat(Shorts.contains(ARRAY234, (short) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Shorts.indexOf(EMPTY, (short) 1));
- assertEquals(-1, Shorts.indexOf(ARRAY1, (short) 2));
- assertEquals(-1, Shorts.indexOf(ARRAY234, (short) 1));
- assertEquals(0, Shorts.indexOf(new short[] {(short) -1}, (short) -1));
- assertEquals(0, Shorts.indexOf(ARRAY234, (short) 2));
- assertEquals(1, Shorts.indexOf(ARRAY234, (short) 3));
- assertEquals(2, Shorts.indexOf(ARRAY234, (short) 4));
- assertEquals(
- 1, Shorts.indexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3));
+ assertThat(Shorts.indexOf(EMPTY, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY1, (short) 2)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(new short[] {(short) -1}, (short) -1)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 2)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 3)).isEqualTo(1);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 4)).isEqualTo(2);
+ assertThat(Shorts.indexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Shorts.indexOf(EMPTY, EMPTY));
- assertEquals(0, Shorts.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Shorts.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Shorts.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Shorts.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Shorts.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Shorts.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Shorts.indexOf(ARRAY234, new short[] {(short) 2, (short) 3}));
- assertEquals(1, Shorts.indexOf(ARRAY234, new short[] {(short) 3, (short) 4}));
- assertEquals(1, Shorts.indexOf(ARRAY234, new short[] {(short) 3}));
- assertEquals(2, Shorts.indexOf(ARRAY234, new short[] {(short) 4}));
- assertEquals(
- 1,
- Shorts.indexOf(
- new short[] {(short) 2, (short) 3, (short) 3, (short) 3, (short) 3},
- new short[] {(short) 3}));
- assertEquals(
- 2,
- Shorts.indexOf(
- new short[] {
- (short) 2, (short) 3, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3
- },
- new short[] {(short) 2, (short) 3, (short) 4}));
- assertEquals(
- 1,
- Shorts.indexOf(
- new short[] {
- (short) 2, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3, (short) 4
- },
- new short[] {(short) 2, (short) 3, (short) 4}));
- assertEquals(
- -1,
- Shorts.indexOf(
- new short[] {(short) 4, (short) 3, (short) 2},
- new short[] {(short) 2, (short) 3, (short) 4}));
+ assertThat(Shorts.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Shorts.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 2, (short) 3})).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 3, (short) 4})).isEqualTo(1);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 3})).isEqualTo(1);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 4})).isEqualTo(2);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {(short) 2, (short) 3, (short) 3, (short) 3, (short) 3},
+ new short[] {(short) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {
+ (short) 2, (short) 3, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3
+ },
+ new short[] {(short) 2, (short) 3, (short) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {
+ (short) 2, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3, (short) 4
+ },
+ new short[] {(short) 2, (short) 3, (short) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {(short) 4, (short) 3, (short) 2},
+ new short[] {(short) 2, (short) 3, (short) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Shorts.lastIndexOf(EMPTY, (short) 1));
- assertEquals(-1, Shorts.lastIndexOf(ARRAY1, (short) 2));
- assertEquals(-1, Shorts.lastIndexOf(ARRAY234, (short) 1));
- assertEquals(0, Shorts.lastIndexOf(new short[] {(short) -1}, (short) -1));
- assertEquals(0, Shorts.lastIndexOf(ARRAY234, (short) 2));
- assertEquals(1, Shorts.lastIndexOf(ARRAY234, (short) 3));
- assertEquals(2, Shorts.lastIndexOf(ARRAY234, (short) 4));
- assertEquals(
- 3, Shorts.lastIndexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3));
- }
-
+ assertThat(Shorts.lastIndexOf(EMPTY, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.lastIndexOf(ARRAY1, (short) 2)).isEqualTo(-1);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.lastIndexOf(new short[] {(short) -1}, (short) -1)).isEqualTo(0);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 2)).isEqualTo(0);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 3)).isEqualTo(1);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 4)).isEqualTo(2);
+ assertThat(
+ Shorts.lastIndexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3))
+ .isEqualTo(3);
+ }
+
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -185,13 +195,14 @@ public class ShortsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Shorts.max(LEAST));
- assertEquals(GREATEST, Shorts.max(GREATEST));
- assertEquals(
- (short) 9,
- Shorts.max((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9));
+ assertThat(Shorts.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Shorts.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Shorts.max((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9))
+ .isEqualTo((short) 9);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -202,19 +213,19 @@ public class ShortsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Shorts.min(LEAST));
- assertEquals(GREATEST, Shorts.min(GREATEST));
- assertEquals(
- (short) 0,
- Shorts.min((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9));
+ assertThat(Shorts.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Shorts.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Shorts.min((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9))
+ .isEqualTo((short) 0);
}
public void testConstrainToRange() {
- assertEquals((short) 1, Shorts.constrainToRange((short) 1, (short) 0, (short) 5));
- assertEquals((short) 1, Shorts.constrainToRange((short) 1, (short) 1, (short) 5));
- assertEquals((short) 3, Shorts.constrainToRange((short) 1, (short) 3, (short) 5));
- assertEquals((short) -1, Shorts.constrainToRange((short) 0, (short) -5, (short) -1));
- assertEquals((short) 2, Shorts.constrainToRange((short) 5, (short) 2, (short) 2));
+ assertThat(Shorts.constrainToRange((short) 1, (short) 0, (short) 5)).isEqualTo((short) 1);
+ assertThat(Shorts.constrainToRange((short) 1, (short) 1, (short) 5)).isEqualTo((short) 1);
+ assertThat(Shorts.constrainToRange((short) 1, (short) 3, (short) 5)).isEqualTo((short) 3);
+ assertThat(Shorts.constrainToRange((short) 0, (short) -5, (short) -1)).isEqualTo((short) -1);
+ assertThat(Shorts.constrainToRange((short) 5, (short) 2, (short) 2)).isEqualTo((short) 2);
try {
Shorts.constrainToRange((short) 1, (short) 3, (short) 2);
fail();
@@ -223,34 +234,34 @@ public class ShortsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Shorts.concat()));
- assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Shorts.concat(ARRAY1)));
- assertNotSame(ARRAY1, Shorts.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Shorts.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new short[] {(short) 1, (short) 1, (short) 1}, Shorts.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new short[] {(short) 1, (short) 2, (short) 3, (short) 4},
- Shorts.concat(ARRAY1, ARRAY234)));
- }
-
+ assertThat(Shorts.concat()).isEqualTo(EMPTY);
+ assertThat(Shorts.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Shorts.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Shorts.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Shorts.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Shorts.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Shorts.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new short[] {(short) 1, (short) 1, (short) 1});
+ assertThat(Shorts.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new short[] {(short) 1, (short) 2, (short) 3, (short) 4});
+ }
+
+ @J2ktIncompatible
@GwtIncompatible // Shorts.toByteArray
public void testToByteArray() {
- assertTrue(Arrays.equals(new byte[] {0x23, 0x45}, Shorts.toByteArray((short) 0x2345)));
- assertTrue(
- Arrays.equals(new byte[] {(byte) 0xFE, (byte) 0xDC}, Shorts.toByteArray((short) 0xFEDC)));
+ assertThat(Shorts.toByteArray((short) 0x2345)).isEqualTo(new byte[] {0x23, 0x45});
+ assertThat(Shorts.toByteArray((short) 0xFEDC)).isEqualTo(new byte[] {(byte) 0xFE, (byte) 0xDC});
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromByteArray
public void testFromByteArray() {
- assertEquals((short) 0x2345, Shorts.fromByteArray(new byte[] {0x23, 0x45}));
- assertEquals((short) 0xFEDC, Shorts.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC}));
+ assertThat(Shorts.fromByteArray(new byte[] {0x23, 0x45})).isEqualTo((short) 0x2345);
+ assertThat(Shorts.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC}))
+ .isEqualTo((short) 0xFEDC);
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromByteArray
public void testFromByteArrayFails() {
try {
@@ -260,12 +271,14 @@ public class ShortsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromBytes
public void testFromBytes() {
- assertEquals((short) 0x2345, Shorts.fromBytes((byte) 0x23, (byte) 0x45));
- assertEquals((short) 0xFEDC, Shorts.fromBytes((byte) 0xFE, (byte) 0xDC));
+ assertThat(Shorts.fromBytes((byte) 0x23, (byte) 0x45)).isEqualTo((short) 0x2345);
+ assertThat(Shorts.fromBytes((byte) 0xFE, (byte) 0xDC)).isEqualTo((short) 0xFEDC);
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromByteArray, Shorts.toByteArray
public void testByteArrayRoundTrips() {
Random r = new Random(5);
@@ -274,20 +287,19 @@ public class ShortsTest extends TestCase {
// total overkill, but, it takes 0.1 sec so why not...
for (int i = 0; i < 10000; i++) {
short num = (short) r.nextInt();
- assertEquals(num, Shorts.fromByteArray(Shorts.toByteArray(num)));
+ assertThat(Shorts.fromByteArray(Shorts.toByteArray(num))).isEqualTo(num);
r.nextBytes(b);
- assertTrue(Arrays.equals(b, Shorts.toByteArray(Shorts.fromByteArray(b))));
+ assertThat(Shorts.toByteArray(Shorts.fromByteArray(b))).isEqualTo(b);
}
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Shorts.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new short[] {(short) 1, (short) 0, (short) 0}, Shorts.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Shorts.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Shorts.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Shorts.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Shorts.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new short[] {(short) 1, (short) 0, (short) 0});
}
public void testEnsureCapacity_fail() {
@@ -305,12 +317,13 @@ public class ShortsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Shorts.join(",", EMPTY));
- assertEquals("1", Shorts.join(",", ARRAY1));
- assertEquals("1,2", Shorts.join(",", (short) 1, (short) 2));
- assertEquals("123", Shorts.join("", (short) 1, (short) 2, (short) 3));
+ assertThat(Shorts.join(",", EMPTY)).isEmpty();
+ assertThat(Shorts.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(Shorts.join(",", (short) 1, (short) 2)).isEqualTo("1,2");
+ assertThat(Shorts.join("", (short) 1, (short) 2, (short) 3)).isEqualTo("123");
}
+ @J2ktIncompatible // TODO(b/285297472): Enable
public void testLexicographicalComparator() {
List<short[]> ordered =
Arrays.asList(
@@ -328,10 +341,11 @@ public class ShortsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<short[]> comparator = Shorts.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -345,14 +359,14 @@ public class ShortsTest extends TestCase {
private static void testReverse(short[] input, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
short[] input, int fromIndex, int toIndex, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -364,6 +378,103 @@ public class ShortsTest extends TestCase {
testReverse(new short[] {-1, 1, -2, 2}, 1, 3, new short[] {-1, -2, 1, 2});
}
+ private static void testRotate(short[] input, int distance, short[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Shorts.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ short[] input, int distance, int fromIndex, int toIndex, short[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Shorts.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new short[] {}, -1, new short[] {});
+ testRotate(new short[] {}, 0, new short[] {});
+ testRotate(new short[] {}, 1, new short[] {});
+
+ testRotate(new short[] {1}, -2, new short[] {1});
+ testRotate(new short[] {1}, -1, new short[] {1});
+ testRotate(new short[] {1}, 0, new short[] {1});
+ testRotate(new short[] {1}, 1, new short[] {1});
+ testRotate(new short[] {1}, 2, new short[] {1});
+
+ testRotate(new short[] {1, 2}, -3, new short[] {2, 1});
+ testRotate(new short[] {1, 2}, -1, new short[] {2, 1});
+ testRotate(new short[] {1, 2}, -2, new short[] {1, 2});
+ testRotate(new short[] {1, 2}, 0, new short[] {1, 2});
+ testRotate(new short[] {1, 2}, 1, new short[] {2, 1});
+ testRotate(new short[] {1, 2}, 2, new short[] {1, 2});
+ testRotate(new short[] {1, 2}, 3, new short[] {2, 1});
+
+ testRotate(new short[] {1, 2, 3}, -5, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, -4, new short[] {2, 3, 1});
+ testRotate(new short[] {1, 2, 3}, -3, new short[] {1, 2, 3});
+ testRotate(new short[] {1, 2, 3}, -2, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, -1, new short[] {2, 3, 1});
+ testRotate(new short[] {1, 2, 3}, 0, new short[] {1, 2, 3});
+ testRotate(new short[] {1, 2, 3}, 1, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, 2, new short[] {2, 3, 1});
+ testRotate(new short[] {1, 2, 3}, 3, new short[] {1, 2, 3});
+ testRotate(new short[] {1, 2, 3}, 4, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, 5, new short[] {2, 3, 1});
+
+ testRotate(new short[] {1, 2, 3, 4}, -9, new short[] {2, 3, 4, 1});
+ testRotate(new short[] {1, 2, 3, 4}, -5, new short[] {2, 3, 4, 1});
+ testRotate(new short[] {1, 2, 3, 4}, -1, new short[] {2, 3, 4, 1});
+ testRotate(new short[] {1, 2, 3, 4}, 0, new short[] {1, 2, 3, 4});
+ testRotate(new short[] {1, 2, 3, 4}, 1, new short[] {4, 1, 2, 3});
+ testRotate(new short[] {1, 2, 3, 4}, 5, new short[] {4, 1, 2, 3});
+ testRotate(new short[] {1, 2, 3, 4}, 9, new short[] {4, 1, 2, 3});
+
+ testRotate(new short[] {1, 2, 3, 4, 5}, -6, new short[] {2, 3, 4, 5, 1});
+ testRotate(new short[] {1, 2, 3, 4, 5}, -4, new short[] {5, 1, 2, 3, 4});
+ testRotate(new short[] {1, 2, 3, 4, 5}, -3, new short[] {4, 5, 1, 2, 3});
+ testRotate(new short[] {1, 2, 3, 4, 5}, -1, new short[] {2, 3, 4, 5, 1});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 0, new short[] {1, 2, 3, 4, 5});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 1, new short[] {5, 1, 2, 3, 4});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 3, new short[] {3, 4, 5, 1, 2});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 4, new short[] {2, 3, 4, 5, 1});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 6, new short[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new short[] {}, 0, 0, 0, new short[] {});
+
+ testRotate(new short[] {1}, 0, 0, 1, new short[] {1});
+ testRotate(new short[] {1}, 1, 0, 1, new short[] {1});
+ testRotate(new short[] {1}, 1, 1, 1, new short[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new short[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new short[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new short[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new short[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new short[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new short[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new short[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new short[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new short[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new short[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new short[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new short[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new short[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new short[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new short[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new short[] {}, new short[] {});
testSortDescending(new short[] {1}, new short[] {1});
@@ -375,14 +486,14 @@ public class ShortsTest extends TestCase {
private static void testSortDescending(short[] input, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
short[] input, int fromIndex, int toIndex, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -394,6 +505,7 @@ public class ShortsTest extends TestCase {
testSortDescending(new short[] {-1, -2, 1, 2}, 1, 3, new short[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Shorts.stringConverter());
@@ -402,17 +514,17 @@ public class ShortsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Short> none = Arrays.<Short>asList();
- assertTrue(Arrays.equals(EMPTY, Shorts.toArray(none)));
+ assertThat(Shorts.toArray(none)).isEqualTo(EMPTY);
List<Short> one = Arrays.asList((short) 1);
- assertTrue(Arrays.equals(ARRAY1, Shorts.toArray(one)));
+ assertThat(Shorts.toArray(one)).isEqualTo(ARRAY1);
short[] array = {(short) 0, (short) 1, (short) 3};
List<Short> three = Arrays.asList((short) 0, (short) 1, (short) 3);
- assertTrue(Arrays.equals(array, Shorts.toArray(three)));
+ assertThat(Shorts.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Shorts.toArray(Shorts.asList(array))));
+ assertThat(Shorts.toArray(Shorts.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -422,16 +534,16 @@ public class ShortsTest extends TestCase {
Collection<Short> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
short[] arr = Shorts.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Short> list = Arrays.asList((short) 0, (short) 1, null);
+ List<@Nullable Short> list = Arrays.asList((short) 0, (short) 1, null);
try {
Shorts.toArray(list);
fail();
@@ -449,21 +561,22 @@ public class ShortsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Shorts.toArray(bytes)));
- assertTrue(Arrays.equals(array, Shorts.toArray(shorts)));
- assertTrue(Arrays.equals(array, Shorts.toArray(ints)));
- assertTrue(Arrays.equals(array, Shorts.toArray(floats)));
- assertTrue(Arrays.equals(array, Shorts.toArray(longs)));
- assertTrue(Arrays.equals(array, Shorts.toArray(doubles)));
+ assertThat(Shorts.toArray(bytes)).isEqualTo(array);
+ assertThat(Shorts.toArray(shorts)).isEqualTo(array);
+ assertThat(Shorts.toArray(ints)).isEqualTo(array);
+ assertThat(Shorts.toArray(floats)).isEqualTo(array);
+ assertThat(Shorts.toArray(longs)).isEqualTo(array);
+ assertThat(Shorts.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
short[] array = {(short) 0, (short) 1};
List<Short> list = Shorts.asList(array);
list.set(0, (short) 2);
- assertTrue(Arrays.equals(new short[] {(short) 2, (short) 1}, array));
+ assertThat(array).isEqualTo(new short[] {(short) 2, (short) 1});
array[1] = (short) 3;
- assertEquals(Arrays.asList((short) 2, (short) 3), list);
+ assertThat(list).containsExactly((short) 2, (short) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -473,24 +586,24 @@ public class ShortsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (short) 4);
- assertTrue(Arrays.equals(new short[] {(short) 0, (short) 1, (short) 2}, newArray));
+ assertThat(newArray).isEqualTo(new short[] {(short) 0, (short) 1, (short) 2});
newArray[1] = (short) 5;
- assertEquals((short) 1, (short) list.get(1));
+ assertThat((short) list.get(1)).isEqualTo((short) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
short[] array = {(short) 0, (short) 1, (short) 2, (short) 3};
List<Short> list = Shorts.asList(array);
- assertTrue(
- Arrays.equals(new short[] {(short) 1, (short) 2}, Shorts.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new short[] {}, Shorts.toArray(list.subList(2, 2))));
+ assertThat(Shorts.toArray(list.subList(1, 3))).isEqualTo(new short[] {(short) 1, (short) 2});
+ assertThat(Shorts.toArray(list.subList(2, 2))).isEqualTo(new short[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Shorts.asList(EMPTY));
+ assertThat(Shorts.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Shorts.class);
@@ -498,14 +611,14 @@ public class ShortsTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Short> converter = Shorts.stringConverter();
- assertEquals((Short) (short) 1, converter.convert("1"));
- assertEquals((Short) (short) 0, converter.convert("0"));
- assertEquals((Short) (short) (-1), converter.convert("-1"));
- assertEquals((Short) (short) 255, converter.convert("0xff"));
- assertEquals((Short) (short) 255, converter.convert("0xFF"));
- assertEquals((Short) (short) (-255), converter.convert("-0xFF"));
- assertEquals((Short) (short) 255, converter.convert("#0000FF"));
- assertEquals((Short) (short) 438, converter.convert("0666"));
+ assertThat(converter.convert("1")).isEqualTo((Short) (short) 1);
+ assertThat(converter.convert("0")).isEqualTo((Short) (short) 0);
+ assertThat(converter.convert("-1")).isEqualTo((Short) (short) (-1));
+ assertThat(converter.convert("0xff")).isEqualTo((Short) (short) 255);
+ assertThat(converter.convert("0xFF")).isEqualTo((Short) (short) 255);
+ assertThat(converter.convert("-0xFF")).isEqualTo((Short) (short) (-255));
+ assertThat(converter.convert("#0000FF")).isEqualTo((Short) (short) 255);
+ assertThat(converter.convert("0666")).isEqualTo((Short) (short) 438);
}
public void testStringConverter_convertError() {
@@ -517,21 +630,22 @@ public class ShortsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Shorts.stringConverter().convert(null));
- assertNull(Shorts.stringConverter().reverse().convert(null));
+ assertThat(Shorts.stringConverter().convert(null)).isNull();
+ assertThat(Shorts.stringConverter().reverse().convert(null)).isNull();
}
public void testStringConverter_reverse() {
Converter<String, Short> converter = Shorts.stringConverter();
- assertEquals("1", converter.reverse().convert((short) 1));
- assertEquals("0", converter.reverse().convert((short) 0));
- assertEquals("-1", converter.reverse().convert((short) -1));
- assertEquals("255", converter.reverse().convert((short) 0xff));
- assertEquals("255", converter.reverse().convert((short) 0xFF));
- assertEquals("-255", converter.reverse().convert((short) -0xFF));
- assertEquals("438", converter.reverse().convert((short) 0666));
+ assertThat(converter.reverse().convert((short) 1)).isEqualTo("1");
+ assertThat(converter.reverse().convert((short) 0)).isEqualTo("0");
+ assertThat(converter.reverse().convert((short) -1)).isEqualTo("-1");
+ assertThat(converter.reverse().convert((short) 0xff)).isEqualTo("255");
+ assertThat(converter.reverse().convert((short) 0xFF)).isEqualTo("255");
+ assertThat(converter.reverse().convert((short) -0xFF)).isEqualTo("-255");
+ assertThat(converter.reverse().convert((short) 0666)).isEqualTo("438");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
diff --git a/android/guava-tests/test/com/google/common/primitives/SignedBytesTest.java b/android/guava-tests/test/com/google/common/primitives/SignedBytesTest.java
index 86c2ce612..a141d72bb 100644
--- a/android/guava-tests/test/com/google/common/primitives/SignedBytesTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/SignedBytesTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -31,6 +35,7 @@ import junit.framework.TestCase;
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class SignedBytesTest extends TestCase {
@@ -44,7 +49,7 @@ public class SignedBytesTest extends TestCase {
public void testCheckedCast() {
for (byte value : VALUES) {
- assertEquals(value, SignedBytes.checkedCast((long) value));
+ assertThat(SignedBytes.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -54,12 +59,12 @@ public class SignedBytesTest extends TestCase {
public void testSaturatedCast() {
for (byte value : VALUES) {
- assertEquals(value, SignedBytes.saturatedCast((long) value));
+ assertThat(SignedBytes.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, SignedBytes.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, SignedBytes.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, SignedBytes.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, SignedBytes.saturatedCast(Long.MIN_VALUE));
+ assertThat(SignedBytes.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(SignedBytes.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -67,9 +72,9 @@ public class SignedBytesTest extends TestCase {
SignedBytes.checkedCast(value);
fail("Cast to byte should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -80,13 +85,15 @@ public class SignedBytesTest extends TestCase {
int expected = Byte.valueOf(x).compareTo(y);
int actual = SignedBytes.compare(x, y);
if (expected == 0) {
- assertEquals(x + ", " + y, expected, actual);
+ assertWithMessage(x + ", " + y).that(actual).isEqualTo(expected);
} else if (expected < 0) {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual < 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual < 0)
+ .isTrue();
} else {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual > 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual > 0)
+ .isTrue();
}
}
}
@@ -101,10 +108,10 @@ public class SignedBytesTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, SignedBytes.max(LEAST));
- assertEquals(GREATEST, SignedBytes.max(GREATEST));
- assertEquals(
- (byte) 127, SignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
+ assertThat(SignedBytes.max(LEAST)).isEqualTo(LEAST);
+ assertThat(SignedBytes.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) 127);
}
public void testMin_noArgs() {
@@ -116,20 +123,21 @@ public class SignedBytesTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, SignedBytes.min(LEAST));
- assertEquals(GREATEST, SignedBytes.min(GREATEST));
- assertEquals(
- (byte) -128, SignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
+ assertThat(SignedBytes.min(LEAST)).isEqualTo(LEAST);
+ assertThat(SignedBytes.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) -128);
}
public void testJoin() {
- assertEquals("", SignedBytes.join(",", EMPTY));
- assertEquals("1", SignedBytes.join(",", ARRAY1));
- assertEquals("1,2", SignedBytes.join(",", (byte) 1, (byte) 2));
- assertEquals("123", SignedBytes.join("", (byte) 1, (byte) 2, (byte) 3));
- assertEquals("-128,-1", SignedBytes.join(",", (byte) -128, (byte) -1));
+ assertThat(SignedBytes.join(",", EMPTY)).isEmpty();
+ assertThat(SignedBytes.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(SignedBytes.join(",", (byte) 1, (byte) 2)).isEqualTo("1,2");
+ assertThat(SignedBytes.join("", (byte) 1, (byte) 2, (byte) 3)).isEqualTo("123");
+ assertThat(SignedBytes.join(",", (byte) -128, (byte) -1)).isEqualTo("-128,-1");
}
+ @J2ktIncompatible // b/285319375
public void testLexicographicalComparator() {
List<byte[]> ordered =
Arrays.asList(
@@ -147,10 +155,11 @@ public class SignedBytesTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<byte[]> comparator = SignedBytes.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testSortDescending() {
@@ -164,14 +173,14 @@ public class SignedBytesTest extends TestCase {
private static void testSortDescending(byte[] input, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
SignedBytes.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
byte[] input, int fromIndex, int toIndex, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
SignedBytes.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -183,6 +192,7 @@ public class SignedBytesTest extends TestCase {
testSortDescending(new byte[] {-1, -2, 1, 2}, 1, 3, new byte[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(SignedBytes.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java b/android/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java
index 352c8f439..840ae97c3 100644
--- a/android/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java
@@ -16,6 +16,9 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -39,17 +42,17 @@ public class UnsignedBytesTest extends TestCase {
private static final byte[] VALUES = {LEAST, 127, (byte) 128, (byte) 129, GREATEST};
public void testToInt() {
- assertEquals(0, UnsignedBytes.toInt((byte) 0));
- assertEquals(1, UnsignedBytes.toInt((byte) 1));
- assertEquals(127, UnsignedBytes.toInt((byte) 127));
- assertEquals(128, UnsignedBytes.toInt((byte) -128));
- assertEquals(129, UnsignedBytes.toInt((byte) -127));
- assertEquals(255, UnsignedBytes.toInt((byte) -1));
+ assertThat(UnsignedBytes.toInt((byte) 0)).isEqualTo(0);
+ assertThat(UnsignedBytes.toInt((byte) 1)).isEqualTo(1);
+ assertThat(UnsignedBytes.toInt((byte) 127)).isEqualTo(127);
+ assertThat(UnsignedBytes.toInt((byte) -128)).isEqualTo(128);
+ assertThat(UnsignedBytes.toInt((byte) -127)).isEqualTo(129);
+ assertThat(UnsignedBytes.toInt((byte) -1)).isEqualTo(255);
}
public void testCheckedCast() {
for (byte value : VALUES) {
- assertEquals(value, UnsignedBytes.checkedCast(UnsignedBytes.toInt(value)));
+ assertThat(UnsignedBytes.checkedCast(UnsignedBytes.toInt(value))).isEqualTo(value);
}
assertCastFails(256L);
assertCastFails(-1L);
@@ -59,12 +62,12 @@ public class UnsignedBytesTest extends TestCase {
public void testSaturatedCast() {
for (byte value : VALUES) {
- assertEquals(value, UnsignedBytes.saturatedCast(UnsignedBytes.toInt(value)));
+ assertThat(UnsignedBytes.saturatedCast(UnsignedBytes.toInt(value))).isEqualTo(value);
}
- assertEquals(GREATEST, UnsignedBytes.saturatedCast(256L));
- assertEquals(LEAST, UnsignedBytes.saturatedCast(-1L));
- assertEquals(GREATEST, UnsignedBytes.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, UnsignedBytes.saturatedCast(Long.MIN_VALUE));
+ assertThat(UnsignedBytes.saturatedCast(256L)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.saturatedCast(-1L)).isEqualTo(LEAST);
+ assertThat(UnsignedBytes.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -72,9 +75,9 @@ public class UnsignedBytesTest extends TestCase {
UnsignedBytes.checkedCast(value);
fail("Cast to byte should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -86,10 +89,9 @@ public class UnsignedBytesTest extends TestCase {
byte x = VALUES[i];
byte y = VALUES[j];
// note: spec requires only that the sign is the same
- assertEquals(
- x + ", " + y,
- Math.signum(UnsignedBytes.compare(x, y)),
- Math.signum(Ints.compare(i, j)));
+ assertWithMessage(x + ", " + y)
+ .that(Math.signum(Ints.compare(i, j)))
+ .isEqualTo(Math.signum(UnsignedBytes.compare(x, y)));
}
}
}
@@ -103,10 +105,10 @@ public class UnsignedBytesTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, UnsignedBytes.max(LEAST));
- assertEquals(GREATEST, UnsignedBytes.max(GREATEST));
- assertEquals(
- (byte) 255, UnsignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
+ assertThat(UnsignedBytes.max(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedBytes.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) 255);
}
public void testMin_noArgs() {
@@ -118,12 +120,12 @@ public class UnsignedBytesTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, UnsignedBytes.min(LEAST));
- assertEquals(GREATEST, UnsignedBytes.min(GREATEST));
- assertEquals(
- (byte) 0, UnsignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
- assertEquals(
- (byte) 0, UnsignedBytes.min((byte) -1, (byte) 127, (byte) 1, (byte) -128, (byte) 0));
+ assertThat(UnsignedBytes.min(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedBytes.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) 0);
+ assertThat(UnsignedBytes.min((byte) -1, (byte) 127, (byte) 1, (byte) -128, (byte) 0))
+ .isEqualTo((byte) 0);
}
private static void assertParseFails(String value) {
@@ -145,7 +147,7 @@ public class UnsignedBytesTest extends TestCase {
public void testParseUnsignedByte() {
// We can easily afford to test this exhaustively.
for (int i = 0; i <= 0xff; i++) {
- assertEquals((byte) i, UnsignedBytes.parseUnsignedByte(Integer.toString(i)));
+ assertThat(UnsignedBytes.parseUnsignedByte(Integer.toString(i))).isEqualTo((byte) i);
}
assertParseFails("1000");
assertParseFails("-1");
@@ -154,15 +156,16 @@ public class UnsignedBytesTest extends TestCase {
}
public void testMaxValue() {
- assertTrue(
- UnsignedBytes.compare(UnsignedBytes.MAX_VALUE, (byte) (UnsignedBytes.MAX_VALUE + 1)) > 0);
+ assertThat(UnsignedBytes.compare(UnsignedBytes.MAX_VALUE, (byte) (UnsignedBytes.MAX_VALUE + 1)))
+ .isGreaterThan(0);
}
public void testParseUnsignedByteWithRadix() throws NumberFormatException {
// We can easily afford to test this exhaustively.
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (int i = 0; i <= 0xff; i++) {
- assertEquals((byte) i, UnsignedBytes.parseUnsignedByte(Integer.toString(i, radix), radix));
+ assertThat(UnsignedBytes.parseUnsignedByte(Integer.toString(i, radix), radix))
+ .isEqualTo((byte) i);
}
assertParseFails(Integer.toString(1000, radix), radix);
assertParseFails(Integer.toString(-1, radix), radix);
@@ -197,7 +200,7 @@ public class UnsignedBytesTest extends TestCase {
public void testToString() {
// We can easily afford to test this exhaustively.
for (int i = 0; i <= 0xff; i++) {
- assertEquals(Integer.toString(i), UnsignedBytes.toString((byte) i));
+ assertThat(UnsignedBytes.toString((byte) i)).isEqualTo(Integer.toString(i));
}
}
@@ -205,17 +208,17 @@ public class UnsignedBytesTest extends TestCase {
// We can easily afford to test this exhaustively.
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (int i = 0; i <= 0xff; i++) {
- assertEquals(Integer.toString(i, radix), UnsignedBytes.toString((byte) i, radix));
+ assertThat(UnsignedBytes.toString((byte) i, radix)).isEqualTo(Integer.toString(i, radix));
}
}
}
public void testJoin() {
- assertEquals("", UnsignedBytes.join(",", new byte[] {}));
- assertEquals("1", UnsignedBytes.join(",", new byte[] {(byte) 1}));
- assertEquals("1,2", UnsignedBytes.join(",", (byte) 1, (byte) 2));
- assertEquals("123", UnsignedBytes.join("", (byte) 1, (byte) 2, (byte) 3));
- assertEquals("128,255", UnsignedBytes.join(",", (byte) 128, (byte) -1));
+ assertThat(UnsignedBytes.join(",", new byte[] {})).isEmpty();
+ assertThat(UnsignedBytes.join(",", new byte[] {(byte) 1})).isEqualTo("1");
+ assertThat(UnsignedBytes.join(",", (byte) 1, (byte) 2)).isEqualTo("1,2");
+ assertThat(UnsignedBytes.join("", (byte) 1, (byte) 2, (byte) 3)).isEqualTo("123");
+ assertThat(UnsignedBytes.join(",", (byte) 128, (byte) -1)).isEqualTo("128,255");
}
private static String unsafeComparatorClassName() {
@@ -251,12 +254,14 @@ public class UnsignedBytesTest extends TestCase {
public void testLexicographicalComparatorChoice() throws Exception {
Comparator<byte[]> defaultComparator = UnsignedBytes.lexicographicalComparator();
- assertNotNull(defaultComparator);
- assertSame(defaultComparator, UnsignedBytes.lexicographicalComparator());
+ assertThat(defaultComparator).isNotNull();
+ assertThat(UnsignedBytes.lexicographicalComparator()).isSameInstanceAs(defaultComparator);
if (unsafeComparatorAvailable()) {
- assertSame(defaultComparator.getClass(), Class.forName(unsafeComparatorClassName()));
+ assertThat(Class.forName(unsafeComparatorClassName()))
+ .isSameInstanceAs(defaultComparator.getClass());
} else {
- assertSame(defaultComparator, UnsignedBytes.lexicographicalComparatorJavaImpl());
+ assertThat(UnsignedBytes.lexicographicalComparatorJavaImpl())
+ .isSameInstanceAs(defaultComparator);
}
}
@@ -276,12 +281,12 @@ public class UnsignedBytesTest extends TestCase {
// The Unsafe implementation if it's available. Otherwise, the Java implementation.
Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
// The Java implementation.
Comparator<byte[]> javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl();
Helpers.testComparator(javaImpl, ordered);
- assertSame(javaImpl, SerializableTester.reserialize(javaImpl));
+ assertThat(SerializableTester.reserialize(javaImpl)).isSameInstanceAs(javaImpl);
}
@SuppressWarnings("unchecked")
@@ -295,12 +300,12 @@ public class UnsignedBytesTest extends TestCase {
byte[] left = new byte[1 + rnd.nextInt(32)];
rnd.nextBytes(left);
byte[] right = left.clone();
- assertTrue(comparator.compare(left, right) == 0);
+ assertThat(comparator.compare(left, right)).isEqualTo(0);
int i = rnd.nextInt(left.length);
left[i] ^= (byte) (1 + rnd.nextInt(255));
- assertTrue(comparator.compare(left, right) != 0);
- assertEquals(
- comparator.compare(left, right) > 0, UnsignedBytes.compare(left[i], right[i]) > 0);
+ assertThat(comparator.compare(left, right)).isNotEqualTo(0);
+ assertThat(UnsignedBytes.compare(left[i], right[i]) > 0)
+ .isEqualTo(comparator.compare(left, right) > 0);
}
}
}
@@ -315,13 +320,13 @@ public class UnsignedBytesTest extends TestCase {
static void testSort(byte[] input, byte[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sort(input);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
static void testSort(byte[] input, int from, int to, byte[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sort(input, from, to);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
public void testSortIndexed() {
@@ -344,14 +349,14 @@ public class UnsignedBytesTest extends TestCase {
private static void testSortDescending(byte[] input, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
byte[] input, int fromIndex, int toIndex, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
diff --git a/android/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java b/android/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java
index 04bf27d05..7034447a9 100644
--- a/android/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java
@@ -14,8 +14,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
@@ -58,16 +62,18 @@ public class UnsignedIntegerTest extends TestCase {
public void testFromIntBitsAndIntValueAreInverses() {
for (int value : TEST_INTS) {
- assertEquals(
- UnsignedInts.toString(value), value, UnsignedInteger.fromIntBits(value).intValue());
+ assertWithMessage(UnsignedInts.toString(value))
+ .that(UnsignedInteger.fromIntBits(value).intValue())
+ .isEqualTo(value);
}
}
public void testFromIntBitsLongValue() {
for (int value : TEST_INTS) {
long expected = value & 0xffffffffL;
- assertEquals(
- UnsignedInts.toString(value), expected, UnsignedInteger.fromIntBits(value).longValue());
+ assertWithMessage(UnsignedInts.toString(value))
+ .that(UnsignedInteger.fromIntBits(value).longValue())
+ .isEqualTo(expected);
}
}
@@ -77,10 +83,10 @@ public class UnsignedIntegerTest extends TestCase {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= min && value <= max;
try {
- assertEquals(value, UnsignedInteger.valueOf(value).longValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedInteger.valueOf(value).longValue()).isEqualTo(value);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
@@ -91,10 +97,10 @@ public class UnsignedIntegerTest extends TestCase {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= min && value <= max;
try {
- assertEquals(value, UnsignedInteger.valueOf(BigInteger.valueOf(value)).longValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedInteger.valueOf(BigInteger.valueOf(value)).longValue()).isEqualTo(value);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
@@ -102,16 +108,17 @@ public class UnsignedIntegerTest extends TestCase {
public void testToString() {
for (int value : TEST_INTS) {
UnsignedInteger unsignedValue = UnsignedInteger.fromIntBits(value);
- assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString());
+ assertThat(unsignedValue.toString()).isEqualTo(unsignedValue.bigIntegerValue().toString());
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testToStringRadix() {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (int l : TEST_INTS) {
UnsignedInteger value = UnsignedInteger.fromIntBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -121,7 +128,7 @@ public class UnsignedIntegerTest extends TestCase {
for (int radix : radices) {
for (int l : TEST_INTS) {
UnsignedInteger value = UnsignedInteger.fromIntBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -129,14 +136,16 @@ public class UnsignedIntegerTest extends TestCase {
public void testFloatValue() {
for (int value : TEST_INTS) {
UnsignedInteger unsignedValue = UnsignedInteger.fromIntBits(value);
- assertEquals(unsignedValue.bigIntegerValue().floatValue(), unsignedValue.floatValue());
+ assertThat(unsignedValue.floatValue())
+ .isEqualTo(unsignedValue.bigIntegerValue().floatValue());
}
}
public void testDoubleValue() {
for (int value : TEST_INTS) {
UnsignedInteger unsignedValue = UnsignedInteger.fromIntBits(value);
- assertEquals(unsignedValue.bigIntegerValue().doubleValue(), unsignedValue.doubleValue());
+ assertThat(unsignedValue.doubleValue())
+ .isEqualTo(unsignedValue.bigIntegerValue().doubleValue());
}
}
@@ -147,7 +156,7 @@ public class UnsignedIntegerTest extends TestCase {
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
int expected = aUnsigned.bigIntegerValue().add(bUnsigned.bigIntegerValue()).intValue();
UnsignedInteger unsignedSum = aUnsigned.plus(bUnsigned);
- assertEquals(expected, unsignedSum.intValue());
+ assertThat(unsignedSum.intValue()).isEqualTo(expected);
}
}
}
@@ -160,11 +169,12 @@ public class UnsignedIntegerTest extends TestCase {
int expected =
force32(aUnsigned.bigIntegerValue().subtract(bUnsigned.bigIntegerValue()).intValue());
UnsignedInteger unsignedSub = aUnsigned.minus(bUnsigned);
- assertEquals(expected, unsignedSub.intValue());
+ assertThat(unsignedSub.intValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // multiply
public void testTimes() {
for (int a : TEST_INTS) {
@@ -174,7 +184,9 @@ public class UnsignedIntegerTest extends TestCase {
int expected =
force32(aUnsigned.bigIntegerValue().multiply(bUnsigned.bigIntegerValue()).intValue());
UnsignedInteger unsignedMul = aUnsigned.times(bUnsigned);
- assertEquals(aUnsigned + " * " + bUnsigned, expected, unsignedMul.intValue());
+ assertWithMessage(aUnsigned + " * " + bUnsigned)
+ .that(unsignedMul.intValue())
+ .isEqualTo(expected);
}
}
}
@@ -187,7 +199,7 @@ public class UnsignedIntegerTest extends TestCase {
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
int expected = aUnsigned.bigIntegerValue().divide(bUnsigned.bigIntegerValue()).intValue();
UnsignedInteger unsignedDiv = aUnsigned.dividedBy(bUnsigned);
- assertEquals(expected, unsignedDiv.intValue());
+ assertThat(unsignedDiv.intValue()).isEqualTo(expected);
}
}
}
@@ -211,7 +223,7 @@ public class UnsignedIntegerTest extends TestCase {
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
int expected = aUnsigned.bigIntegerValue().mod(bUnsigned.bigIntegerValue()).intValue();
UnsignedInteger unsignedRem = aUnsigned.mod(bUnsigned);
- assertEquals(expected, unsignedRem.intValue());
+ assertThat(unsignedRem.intValue()).isEqualTo(expected);
}
}
}
@@ -232,13 +244,13 @@ public class UnsignedIntegerTest extends TestCase {
for (int b : TEST_INTS) {
UnsignedInteger aUnsigned = UnsignedInteger.fromIntBits(a);
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
- assertEquals(
- aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()),
- aUnsigned.compareTo(bUnsigned));
+ assertThat(aUnsigned.compareTo(bUnsigned))
+ .isEqualTo(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()));
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testEquals() {
EqualsTester equalsTester = new EqualsTester();
@@ -257,10 +269,11 @@ public class UnsignedIntegerTest extends TestCase {
for (int a : TEST_INTS) {
UnsignedInteger aUnsigned = UnsignedInteger.fromIntBits(a);
int intValue = aUnsigned.bigIntegerValue().intValue();
- assertEquals(intValue, aUnsigned.intValue());
+ assertThat(aUnsigned.intValue()).isEqualTo(intValue);
}
}
+ @J2ktIncompatible
@GwtIncompatible // serialization
public void testSerialization() {
for (int a : TEST_INTS) {
@@ -268,6 +281,7 @@ public class UnsignedIntegerTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedInteger.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java b/android/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java
index 0d0b38008..1b118863a 100644
--- a/android/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java
@@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import java.util.Arrays;
@@ -52,7 +53,7 @@ public class UnsignedIntsTest extends TestCase {
public void testCheckedCast() {
for (long value : UNSIGNED_INTS) {
- assertEquals(value, UnsignedInts.toLong(UnsignedInts.checkedCast(value)));
+ assertThat(UnsignedInts.toLong(UnsignedInts.checkedCast(value))).isEqualTo(value);
}
assertCastFails(1L << 32);
assertCastFails(-1L);
@@ -65,23 +66,23 @@ public class UnsignedIntsTest extends TestCase {
UnsignedInts.checkedCast(value);
fail("Cast to int should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertThat(ex.getMessage()).contains(String.valueOf(value));
+ assertThat(ex).hasMessageThat().contains(String.valueOf(value));
}
}
public void testSaturatedCast() {
for (long value : UNSIGNED_INTS) {
- assertEquals(value, UnsignedInts.toLong(UnsignedInts.saturatedCast(value)));
+ assertThat(UnsignedInts.toLong(UnsignedInts.saturatedCast(value))).isEqualTo(value);
}
- assertEquals(GREATEST, UnsignedInts.saturatedCast(1L << 32));
- assertEquals(LEAST, UnsignedInts.saturatedCast(-1L));
- assertEquals(GREATEST, UnsignedInts.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, UnsignedInts.saturatedCast(Long.MIN_VALUE));
+ assertThat(UnsignedInts.saturatedCast(1L << 32)).isEqualTo(GREATEST);
+ assertThat(UnsignedInts.saturatedCast(-1L)).isEqualTo(LEAST);
+ assertThat(UnsignedInts.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(UnsignedInts.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
public void testToLong() {
for (long a : UNSIGNED_INTS) {
- assertEquals(a, UnsignedInts.toLong((int) a));
+ assertThat(UnsignedInts.toLong((int) a)).isEqualTo(a);
}
}
@@ -90,7 +91,7 @@ public class UnsignedIntsTest extends TestCase {
for (long b : UNSIGNED_INTS) {
int cmpAsLongs = Longs.compare(a, b);
int cmpAsUInt = UnsignedInts.compare((int) a, (int) b);
- assertEquals(Integer.signum(cmpAsLongs), Integer.signum(cmpAsUInt));
+ assertThat(Integer.signum(cmpAsUInt)).isEqualTo(Integer.signum(cmpAsLongs));
}
}
}
@@ -104,18 +105,18 @@ public class UnsignedIntsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, UnsignedInts.max(LEAST));
- assertEquals(GREATEST, UnsignedInts.max(GREATEST));
- assertEquals(
- (int) 0xff1a618bL,
- UnsignedInts.max(
- (int) 8L,
- (int) 6L,
- (int) 7L,
- (int) 0x12345678L,
- (int) 0x5a4316b8L,
- (int) 0xff1a618bL,
- (int) 0L));
+ assertThat(UnsignedInts.max(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedInts.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedInts.max(
+ (int) 8L,
+ (int) 6L,
+ (int) 7L,
+ (int) 0x12345678L,
+ (int) 0x5a4316b8L,
+ (int) 0xff1a618bL,
+ (int) 0L))
+ .isEqualTo((int) 0xff1a618bL);
}
public void testMin_noArgs() {
@@ -127,18 +128,18 @@ public class UnsignedIntsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, UnsignedInts.min(LEAST));
- assertEquals(GREATEST, UnsignedInts.min(GREATEST));
- assertEquals(
- (int) 0L,
- UnsignedInts.min(
- (int) 8L,
- (int) 6L,
- (int) 7L,
- (int) 0x12345678L,
- (int) 0x5a4316b8L,
- (int) 0xff1a618bL,
- (int) 0L));
+ assertThat(UnsignedInts.min(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedInts.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedInts.min(
+ (int) 8L,
+ (int) 6L,
+ (int) 7L,
+ (int) 0x12345678L,
+ (int) 0x5a4316b8L,
+ (int) 0xff1a618bL,
+ (int) 0L))
+ .isEqualTo((int) 0L);
}
public void testLexicographicalComparator() {
@@ -168,13 +169,13 @@ public class UnsignedIntsTest extends TestCase {
static void testSort(int[] input, int[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sort(input);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
static void testSort(int[] input, int from, int to, int[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sort(input, from, to);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
public void testSortIndexed() {
@@ -196,14 +197,14 @@ public class UnsignedIntsTest extends TestCase {
private static void testSortDescending(int[] input, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
int[] input, int fromIndex, int toIndex, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -223,10 +224,10 @@ public class UnsignedIntsTest extends TestCase {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
try {
- assertEquals((int) (a / b), UnsignedInts.divide((int) a, (int) b));
- assertFalse(b == 0);
+ assertThat(UnsignedInts.divide((int) a, (int) b)).isEqualTo((int) (a / b));
+ assertThat(b).isNotEqualTo(0);
} catch (ArithmeticException e) {
- assertEquals(0, b);
+ assertThat(b).isEqualTo(0);
}
}
}
@@ -236,15 +237,16 @@ public class UnsignedIntsTest extends TestCase {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
try {
- assertEquals((int) (a % b), UnsignedInts.remainder((int) a, (int) b));
- assertFalse(b == 0);
+ assertThat(UnsignedInts.remainder((int) a, (int) b)).isEqualTo((int) (a % b));
+ assertThat(b).isNotEqualTo(0);
} catch (ArithmeticException e) {
- assertEquals(0, b);
+ assertThat(b).isEqualTo(0);
}
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // Too slow in GWT (~3min fully optimized)
public void testDivideRemainderEuclideanProperty() {
// Use a seed so that the test is deterministic:
@@ -253,17 +255,17 @@ public class UnsignedIntsTest extends TestCase {
int dividend = r.nextInt();
int divisor = r.nextInt();
// Test that the Euclidean property is preserved:
- assertTrue(
- dividend
+ assertThat(
+ dividend
- (divisor * UnsignedInts.divide(dividend, divisor)
- + UnsignedInts.remainder(dividend, divisor))
- == 0);
+ + UnsignedInts.remainder(dividend, divisor)))
+ .isEqualTo(0);
}
}
public void testParseInt() {
for (long a : UNSIGNED_INTS) {
- assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a)));
+ assertThat(UnsignedInts.parseUnsignedInt(Long.toString(a))).isEqualTo((int) a);
}
}
@@ -278,7 +280,8 @@ public class UnsignedIntsTest extends TestCase {
public void testParseIntWithRadix() {
for (long a : UNSIGNED_INTS) {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
- assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a, radix), radix));
+ assertThat(UnsignedInts.parseUnsignedInt(Long.toString(a, radix), radix))
+ .isEqualTo((int) a);
}
}
}
@@ -288,10 +291,10 @@ public class UnsignedIntsTest extends TestCase {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
// tests can successfully parse a number string with this radix.
String maxAsString = Long.toString((1L << 32) - 1, radix);
- assertEquals(-1, UnsignedInts.parseUnsignedInt(maxAsString, radix));
+ assertThat(UnsignedInts.parseUnsignedInt(maxAsString, radix)).isEqualTo(-1);
try {
- // tests that we get exception whre an overflow would occur.
+ // tests that we get exception where an overflow would occur.
long overflow = 1L << 32;
String overflowAsString = Long.toString(overflow, radix);
UnsignedInts.parseUnsignedInt(overflowAsString, radix);
@@ -301,6 +304,7 @@ public class UnsignedIntsTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/285538920): Exception mismatch
public void testParseIntThrowsExceptionForInvalidRadix() {
// Valid radix values are Character.MIN_RADIX to Character.MAX_RADIX,
// inclusive.
@@ -325,13 +329,13 @@ public class UnsignedIntsTest extends TestCase {
}
public void testDecodeInt() {
- assertEquals(0xffffffff, UnsignedInts.decode("0xffffffff"));
- assertEquals(01234567, UnsignedInts.decode("01234567")); // octal
- assertEquals(0x12345678, UnsignedInts.decode("#12345678"));
- assertEquals(76543210, UnsignedInts.decode("76543210"));
- assertEquals(0x13579135, UnsignedInts.decode("0x13579135"));
- assertEquals(0x13579135, UnsignedInts.decode("0X13579135"));
- assertEquals(0, UnsignedInts.decode("0"));
+ assertThat(UnsignedInts.decode("0xffffffff")).isEqualTo(0xffffffff);
+ assertThat(UnsignedInts.decode("01234567")).isEqualTo(01234567); // octal
+ assertThat(UnsignedInts.decode("#12345678")).isEqualTo(0x12345678);
+ assertThat(UnsignedInts.decode("76543210")).isEqualTo(76543210);
+ assertThat(UnsignedInts.decode("0x13579135")).isEqualTo(0x13579135);
+ assertThat(UnsignedInts.decode("0X13579135")).isEqualTo(0x13579135);
+ assertThat(UnsignedInts.decode("0")).isEqualTo(0);
}
public void testDecodeIntFails() {
@@ -365,24 +369,25 @@ public class UnsignedIntsTest extends TestCase {
int[] bases = {2, 5, 7, 8, 10, 16};
for (long a : UNSIGNED_INTS) {
for (int base : bases) {
- assertEquals(UnsignedInts.toString((int) a, base), Long.toString(a, base));
+ assertThat(Long.toString(a, base)).isEqualTo(UnsignedInts.toString((int) a, base));
}
}
}
public void testJoin() {
- assertEquals("", join());
- assertEquals("1", join(1));
- assertEquals("1,2", join(1, 2));
- assertEquals("4294967295,2147483648", join(-1, Integer.MIN_VALUE));
+ assertThat(join()).isEmpty();
+ assertThat(join(1)).isEqualTo("1");
+ assertThat(join(1, 2)).isEqualTo("1,2");
+ assertThat(join(-1, Integer.MIN_VALUE)).isEqualTo("4294967295,2147483648");
- assertEquals("123", UnsignedInts.join("", 1, 2, 3));
+ assertThat(UnsignedInts.join("", 1, 2, 3)).isEqualTo("123");
}
private static String join(int... values) {
return UnsignedInts.join(",", values);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedInts.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java b/android/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java
index cfa286257..335e6e3ef 100644
--- a/android/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java
@@ -14,8 +14,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
@@ -69,8 +73,9 @@ public class UnsignedLongTest extends TestCase {
public void testAsUnsignedAndLongValueAreInverses() {
for (long value : TEST_LONGS) {
- assertEquals(
- UnsignedLongs.toString(value), value, UnsignedLong.fromLongBits(value).longValue());
+ assertWithMessage(UnsignedLongs.toString(value))
+ .that(UnsignedLong.fromLongBits(value).longValue())
+ .isEqualTo(value);
}
}
@@ -80,10 +85,9 @@ public class UnsignedLongTest extends TestCase {
(value >= 0)
? BigInteger.valueOf(value)
: BigInteger.valueOf(value).add(BigInteger.ZERO.setBit(64));
- assertEquals(
- UnsignedLongs.toString(value),
- expected,
- UnsignedLong.fromLongBits(value).bigIntegerValue());
+ assertWithMessage(UnsignedLongs.toString(value))
+ .that(UnsignedLong.fromLongBits(value).bigIntegerValue())
+ .isEqualTo(expected);
}
}
@@ -91,24 +95,25 @@ public class UnsignedLongTest extends TestCase {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= 0;
try {
- assertEquals(value, UnsignedLong.valueOf(value).longValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedLong.valueOf(value).longValue()).isEqualTo(value);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testValueOfBigInteger() {
BigInteger min = BigInteger.ZERO;
BigInteger max = UnsignedLong.MAX_VALUE.bigIntegerValue();
for (BigInteger big : TEST_BIG_INTEGERS) {
boolean expectSuccess = big.compareTo(min) >= 0 && big.compareTo(max) <= 0;
try {
- assertEquals(big, UnsignedLong.valueOf(big).bigIntegerValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedLong.valueOf(big).bigIntegerValue()).isEqualTo(big);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
@@ -116,16 +121,17 @@ public class UnsignedLongTest extends TestCase {
public void testToString() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
- assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString());
+ assertThat(unsignedValue.toString()).isEqualTo(unsignedValue.bigIntegerValue().toString());
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testToStringRadix() {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (long l : TEST_LONGS) {
UnsignedLong value = UnsignedLong.fromLongBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -135,7 +141,7 @@ public class UnsignedLongTest extends TestCase {
for (int radix : radices) {
for (long l : TEST_LONGS) {
UnsignedLong value = UnsignedLong.fromLongBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -144,25 +150,24 @@ public class UnsignedLongTest extends TestCase {
public void testFloatValue() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
- assertEquals(
- "Float value of " + unsignedValue,
- unsignedValue.bigIntegerValue().floatValue(),
- unsignedValue.floatValue(),
- 0.0f);
+ assertWithMessage("Float value of " + unsignedValue)
+ .that(unsignedValue.floatValue())
+ .isWithin(0.0f)
+ .of(unsignedValue.bigIntegerValue().floatValue());
}
}
public void testDoubleValue() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
- assertEquals(
- "Double value of " + unsignedValue,
- unsignedValue.bigIntegerValue().doubleValue(),
- unsignedValue.doubleValue(),
- 0.0);
+ assertWithMessage("Double value of " + unsignedValue)
+ .that(unsignedValue.doubleValue())
+ .isWithin(0.0)
+ .of(unsignedValue.bigIntegerValue().doubleValue());
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testPlus() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -170,11 +175,12 @@ public class UnsignedLongTest extends TestCase {
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned.bigIntegerValue().add(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedSum = aUnsigned.plus(bUnsigned);
- assertEquals(expected, unsignedSum.longValue());
+ assertThat(unsignedSum.longValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testMinus() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -183,11 +189,12 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().subtract(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedSub = aUnsigned.minus(bUnsigned);
- assertEquals(expected, unsignedSub.longValue());
+ assertThat(unsignedSub.longValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testTimes() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -196,11 +203,12 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().multiply(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedMul = aUnsigned.times(bUnsigned);
- assertEquals(expected, unsignedMul.longValue());
+ assertThat(unsignedMul.longValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testDividedBy() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -210,7 +218,7 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().divide(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedDiv = aUnsigned.dividedBy(bUnsigned);
- assertEquals(expected, unsignedDiv.longValue());
+ assertThat(unsignedDiv.longValue()).isEqualTo(expected);
}
}
}
@@ -226,6 +234,7 @@ public class UnsignedLongTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/285538920): Wrong result for j2kt
public void testMod() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -235,7 +244,7 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().remainder(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedRem = aUnsigned.mod(bUnsigned);
- assertEquals(expected, unsignedRem.longValue());
+ assertThat(unsignedRem.longValue()).isEqualTo(expected);
}
}
}
@@ -256,13 +265,13 @@ public class UnsignedLongTest extends TestCase {
for (long b : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
- assertEquals(
- aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()),
- aUnsigned.compareTo(bUnsigned));
+ assertThat(aUnsigned.compareTo(bUnsigned))
+ .isEqualTo(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()));
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testEquals() {
EqualsTester equalsTester = new EqualsTester();
@@ -282,10 +291,11 @@ public class UnsignedLongTest extends TestCase {
for (long a : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
int intValue = aUnsigned.bigIntegerValue().intValue();
- assertEquals(intValue, aUnsigned.intValue());
+ assertThat(aUnsigned.intValue()).isEqualTo(intValue);
}
}
+ @J2ktIncompatible
@GwtIncompatible // serialization
public void testSerialization() {
for (long a : TEST_LONGS) {
@@ -293,6 +303,7 @@ public class UnsignedLongTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedLong.class);
diff --git a/android/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java b/android/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java
index a8b799577..faa8ec72a 100644
--- a/android/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java
+++ b/android/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java
@@ -14,10 +14,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
import static java.math.BigInteger.ONE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import java.math.BigInteger;
@@ -40,23 +42,23 @@ public class UnsignedLongsTest extends TestCase {
public void testCompare() {
// max value
- assertTrue(UnsignedLongs.compare(0, 0xffffffffffffffffL) < 0);
- assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0) > 0);
+ assertThat(UnsignedLongs.compare(0, 0xffffffffffffffffL)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0xffffffffffffffffL, 0)).isGreaterThan(0);
// both with high bit set
- assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xffffffffffffffffL) < 0);
- assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0xff1a618b7f65ea12L) > 0);
+ assertThat(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xffffffffffffffffL)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0xffffffffffffffffL, 0xff1a618b7f65ea12L)).isGreaterThan(0);
// one with high bit set
- assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0xff1a618b7f65ea12L) < 0);
- assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0x5a4316b8c153ac4dL) > 0);
+ assertThat(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0xff1a618b7f65ea12L)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0x5a4316b8c153ac4dL)).isGreaterThan(0);
// neither with high bit set
- assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0x6cf78a4b139a4e2aL) < 0);
- assertTrue(UnsignedLongs.compare(0x6cf78a4b139a4e2aL, 0x5a4316b8c153ac4dL) > 0);
+ assertThat(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0x6cf78a4b139a4e2aL)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0x6cf78a4b139a4e2aL, 0x5a4316b8c153ac4dL)).isGreaterThan(0);
// same value
- assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xff1a618b7f65ea12L) == 0);
+ assertThat(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xff1a618b7f65ea12L)).isEqualTo(0);
}
public void testMax_noArgs() {
@@ -68,12 +70,12 @@ public class UnsignedLongsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, UnsignedLongs.max(LEAST));
- assertEquals(GREATEST, UnsignedLongs.max(GREATEST));
- assertEquals(
- 0xff1a618b7f65ea12L,
- UnsignedLongs.max(
- 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L));
+ assertThat(UnsignedLongs.max(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedLongs.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedLongs.max(
+ 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L))
+ .isEqualTo(0xff1a618b7f65ea12L);
}
public void testMin_noArgs() {
@@ -85,12 +87,12 @@ public class UnsignedLongsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, UnsignedLongs.min(LEAST));
- assertEquals(GREATEST, UnsignedLongs.min(GREATEST));
- assertEquals(
- 0L,
- UnsignedLongs.min(
- 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L));
+ assertThat(UnsignedLongs.min(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedLongs.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedLongs.min(
+ 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L))
+ .isEqualTo(0L);
}
public void testLexicographicalComparator() {
@@ -120,13 +122,13 @@ public class UnsignedLongsTest extends TestCase {
static void testSort(long[] input, long[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sort(input);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
static void testSort(long[] input, int from, int to, long[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sort(input, from, to);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
public void testSortIndexed() {
@@ -149,14 +151,14 @@ public class UnsignedLongsTest extends TestCase {
private static void testSortDescending(long[] input, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
long[] input, int fromIndex, int toIndex, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -173,26 +175,27 @@ public class UnsignedLongsTest extends TestCase {
}
public void testDivide() {
- assertEquals(2, UnsignedLongs.divide(14, 5));
- assertEquals(0, UnsignedLongs.divide(0, 50));
- assertEquals(1, UnsignedLongs.divide(0xfffffffffffffffeL, 0xfffffffffffffffdL));
- assertEquals(0, UnsignedLongs.divide(0xfffffffffffffffdL, 0xfffffffffffffffeL));
- assertEquals(281479271743488L, UnsignedLongs.divide(0xfffffffffffffffeL, 65535));
- assertEquals(0x7fffffffffffffffL, UnsignedLongs.divide(0xfffffffffffffffeL, 2));
- assertEquals(3689348814741910322L, UnsignedLongs.divide(0xfffffffffffffffeL, 5));
+ assertThat(UnsignedLongs.divide(14, 5)).isEqualTo(2);
+ assertThat(UnsignedLongs.divide(0, 50)).isEqualTo(0);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 0xfffffffffffffffdL)).isEqualTo(1);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffdL, 0xfffffffffffffffeL)).isEqualTo(0);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 65535)).isEqualTo(281479271743488L);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 2)).isEqualTo(0x7fffffffffffffffL);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 5)).isEqualTo(3689348814741910322L);
}
public void testRemainder() {
- assertEquals(4, UnsignedLongs.remainder(14, 5));
- assertEquals(0, UnsignedLongs.remainder(0, 50));
- assertEquals(1, UnsignedLongs.remainder(0xfffffffffffffffeL, 0xfffffffffffffffdL));
- assertEquals(
- 0xfffffffffffffffdL, UnsignedLongs.remainder(0xfffffffffffffffdL, 0xfffffffffffffffeL));
- assertEquals(65534L, UnsignedLongs.remainder(0xfffffffffffffffeL, 65535));
- assertEquals(0, UnsignedLongs.remainder(0xfffffffffffffffeL, 2));
- assertEquals(4, UnsignedLongs.remainder(0xfffffffffffffffeL, 5));
+ assertThat(UnsignedLongs.remainder(14, 5)).isEqualTo(4);
+ assertThat(UnsignedLongs.remainder(0, 50)).isEqualTo(0);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 0xfffffffffffffffdL)).isEqualTo(1);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffdL, 0xfffffffffffffffeL))
+ .isEqualTo(0xfffffffffffffffdL);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 65535)).isEqualTo(65534L);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 2)).isEqualTo(0);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 5)).isEqualTo(4);
}
+ @J2ktIncompatible
@GwtIncompatible // Too slow in GWT (~3min fully optimized)
public void testDivideRemainderEuclideanProperty() {
// Use a seed so that the test is deterministic:
@@ -201,20 +204,25 @@ public class UnsignedLongsTest extends TestCase {
long dividend = r.nextLong();
long divisor = r.nextLong();
// Test that the Euclidean property is preserved:
- assertEquals(
- 0,
- dividend
- - (divisor * UnsignedLongs.divide(dividend, divisor)
- + UnsignedLongs.remainder(dividend, divisor)));
+ assertThat(
+ dividend
+ - (divisor * UnsignedLongs.divide(dividend, divisor)
+ + UnsignedLongs.remainder(dividend, divisor)))
+ .isEqualTo(0);
}
}
public void testParseLong() {
- assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("18446744073709551615"));
- assertEquals(0x7fffffffffffffffL, UnsignedLongs.parseUnsignedLong("9223372036854775807"));
- assertEquals(0xff1a618b7f65ea12L, UnsignedLongs.parseUnsignedLong("18382112080831834642"));
- assertEquals(0x5a4316b8c153ac4dL, UnsignedLongs.parseUnsignedLong("6504067269626408013"));
- assertEquals(0x6cf78a4b139a4e2aL, UnsignedLongs.parseUnsignedLong("7851896530399809066"));
+ assertThat(UnsignedLongs.parseUnsignedLong("18446744073709551615"))
+ .isEqualTo(0xffffffffffffffffL);
+ assertThat(UnsignedLongs.parseUnsignedLong("9223372036854775807"))
+ .isEqualTo(0x7fffffffffffffffL);
+ assertThat(UnsignedLongs.parseUnsignedLong("18382112080831834642"))
+ .isEqualTo(0xff1a618b7f65ea12L);
+ assertThat(UnsignedLongs.parseUnsignedLong("6504067269626408013"))
+ .isEqualTo(0x5a4316b8c153ac4dL);
+ assertThat(UnsignedLongs.parseUnsignedLong("7851896530399809066"))
+ .isEqualTo(0x6cf78a4b139a4e2aL);
}
public void testParseLongEmptyString() {
@@ -235,13 +243,13 @@ public class UnsignedLongsTest extends TestCase {
}
public void testDecodeLong() {
- assertEquals(0xffffffffffffffffL, UnsignedLongs.decode("0xffffffffffffffff"));
- assertEquals(01234567, UnsignedLongs.decode("01234567")); // octal
- assertEquals(0x1234567890abcdefL, UnsignedLongs.decode("#1234567890abcdef"));
- assertEquals(987654321012345678L, UnsignedLongs.decode("987654321012345678"));
- assertEquals(0x135791357913579L, UnsignedLongs.decode("0x135791357913579"));
- assertEquals(0x135791357913579L, UnsignedLongs.decode("0X135791357913579"));
- assertEquals(0L, UnsignedLongs.decode("0"));
+ assertThat(UnsignedLongs.decode("0xffffffffffffffff")).isEqualTo(0xffffffffffffffffL);
+ assertThat(UnsignedLongs.decode("01234567")).isEqualTo(01234567); // octal
+ assertThat(UnsignedLongs.decode("#1234567890abcdef")).isEqualTo(0x1234567890abcdefL);
+ assertThat(UnsignedLongs.decode("987654321012345678")).isEqualTo(987654321012345678L);
+ assertThat(UnsignedLongs.decode("0x135791357913579")).isEqualTo(0x135791357913579L);
+ assertThat(UnsignedLongs.decode("0X135791357913579")).isEqualTo(0x135791357913579L);
+ assertThat(UnsignedLongs.decode("0")).isEqualTo(0L);
}
public void testDecodeLongFails() {
@@ -272,8 +280,10 @@ public class UnsignedLongsTest extends TestCase {
}
public void testParseLongWithRadix() {
- assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("ffffffffffffffff", 16));
- assertEquals(0x1234567890abcdefL, UnsignedLongs.parseUnsignedLong("1234567890abcdef", 16));
+ assertThat(UnsignedLongs.parseUnsignedLong("ffffffffffffffff", 16))
+ .isEqualTo(0xffffffffffffffffL);
+ assertThat(UnsignedLongs.parseUnsignedLong("1234567890abcdef", 16))
+ .isEqualTo(0x1234567890abcdefL);
}
public void testParseLongWithRadixLimits() {
@@ -282,10 +292,10 @@ public class UnsignedLongsTest extends TestCase {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
// tests can successfully parse a number string with this radix.
String maxAsString = max.toString(radix);
- assertEquals(max.longValue(), UnsignedLongs.parseUnsignedLong(maxAsString, radix));
+ assertThat(UnsignedLongs.parseUnsignedLong(maxAsString, radix)).isEqualTo(max.longValue());
try {
- // tests that we get exception whre an overflow would occur.
+ // tests that we get exception where an overflow would occur.
BigInteger overflow = max.add(ONE);
String overflowAsString = overflow.toString(radix);
UnsignedLongs.parseUnsignedLong(overflowAsString, radix);
@@ -323,6 +333,7 @@ public class UnsignedLongsTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testToString() {
String[] tests = {
"0",
@@ -337,22 +348,23 @@ public class UnsignedLongsTest extends TestCase {
for (String x : tests) {
BigInteger xValue = new BigInteger(x, 16);
long xLong = xValue.longValue(); // signed
- assertEquals(xValue.toString(base), UnsignedLongs.toString(xLong, base));
+ assertThat(UnsignedLongs.toString(xLong, base)).isEqualTo(xValue.toString(base));
}
}
}
public void testJoin() {
- assertEquals("", UnsignedLongs.join(","));
- assertEquals("1", UnsignedLongs.join(",", 1));
- assertEquals("1,2", UnsignedLongs.join(",", 1, 2));
- assertEquals(
- "18446744073709551615,9223372036854775808", UnsignedLongs.join(",", -1, Long.MIN_VALUE));
- assertEquals("123", UnsignedLongs.join("", 1, 2, 3));
- assertEquals(
- "184467440737095516159223372036854775808", UnsignedLongs.join("", -1, Long.MIN_VALUE));
+ assertThat(UnsignedLongs.join(",")).isEmpty();
+ assertThat(UnsignedLongs.join(",", 1)).isEqualTo("1");
+ assertThat(UnsignedLongs.join(",", 1, 2)).isEqualTo("1,2");
+ assertThat(UnsignedLongs.join(",", -1, Long.MIN_VALUE))
+ .isEqualTo("18446744073709551615,9223372036854775808");
+ assertThat(UnsignedLongs.join("", 1, 2, 3)).isEqualTo("123");
+ assertThat(UnsignedLongs.join("", -1, Long.MIN_VALUE))
+ .isEqualTo("184467440737095516159223372036854775808");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedLongs.class);
diff --git a/android/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java b/android/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java
index 56b20bdfb..310878f98 100644
--- a/android/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java
@@ -26,6 +26,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link AbstractInvocationHandler}.
@@ -136,7 +137,7 @@ public class AbstractInvocationHandlerTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof DelegatingInvocationHandlerWithEquals) {
DelegatingInvocationHandlerWithEquals that = (DelegatingInvocationHandlerWithEquals) obj;
return delegate.equals(that.delegate);
diff --git a/android/guava-tests/test/com/google/common/reflect/ClassPathTest.java b/android/guava-tests/test/com/google/common/reflect/ClassPathTest.java
index d199d1f90..f5f8f3774 100644
--- a/android/guava-tests/test/com/google/common/reflect/ClassPathTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/ClassPathTest.java
@@ -17,6 +17,7 @@ package com.google.common.reflect;
import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.common.truth.Truth.assertThat;
@@ -178,6 +179,7 @@ public class ClassPathTest extends TestCase {
assertThat(ClassPath.from(classloader).getTopLevelClasses()).isNotEmpty();
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScan_classPathCycle() throws IOException {
File jarFile = File.createTempFile("with_circular_class_path", ".jar");
@@ -201,6 +203,7 @@ public class ClassPathTest extends TestCase {
.isEmpty();
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanFromFile_notJarFile() throws IOException {
ClassLoader classLoader = ClassPathTest.class.getClassLoader();
@@ -213,6 +216,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathEntry() throws MalformedURLException, URISyntaxException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
assertEquals(
new File("/usr/test/dep.jar").toURI(),
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "file:/usr/test/dep.jar")
@@ -283,6 +289,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathFromManifest_absoluteDirectory() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
@@ -290,6 +299,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathFromManifest_absoluteJar() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
@@ -297,6 +309,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathFromManifest_multiplePaths() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute.jar relative.jar relative/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
@@ -352,7 +367,11 @@ public class ClassPathTest extends TestCase {
// Test that ResourceInfo.urls() returns identical content to ClassLoader.getResources()
+ @AndroidIncompatible
public void testGetClassPathUrls() throws Exception {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
String oldPathSeparator = PATH_SEPARATOR.value();
String oldClassPath = JAVA_CLASS_PATH.value();
System.setProperty(PATH_SEPARATOR.key(), ":");
@@ -399,6 +418,7 @@ public class ClassPathTest extends TestCase {
.testAllPublicInstanceMethods(ClassPath.from(getClass().getClassLoader()));
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testLocationsFrom_idempotentScan() throws IOException {
ImmutableSet<ClassPath.LocationInfo> locations =
@@ -429,6 +449,7 @@ public class ClassPathTest extends TestCase {
.testEquals();
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanAllResources() throws IOException {
assertThat(scanResourceNames(ClassLoader.getSystemClassLoader()))
@@ -543,6 +564,10 @@ public class ClassPathTest extends TestCase {
}
private static URL makeJarUrlWithName(String name) throws IOException {
+ /*
+ * TODO: cpovirk - Use java.nio.file.Files.createTempDirectory instead of
+ * c.g.c.io.Files.createTempDir?
+ */
File fullPath = new File(Files.createTempDir(), name);
File jarFile = pickAnyJarFile();
Files.copy(jarFile, fullPath);
@@ -568,4 +593,8 @@ public class ClassPathTest extends TestCase {
}
return builder.build();
}
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/android/guava-tests/test/com/google/common/reflect/InvokableTest.java b/android/guava-tests/test/com/google/common/reflect/InvokableTest.java
index e545bdd1b..ab5ff738f 100644
--- a/android/guava-tests/test/com/google/common/reflect/InvokableTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/InvokableTest.java
@@ -32,8 +32,8 @@ import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.TypeVariable;
import java.util.Collections;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link Invokable}.
@@ -49,9 +49,9 @@ public class InvokableTest extends TestCase {
public void testApiCompatibleWithAccessibleObject() {
ImmutableSet<String> invokableMethods =
publicMethodSignatures(Invokable.class, ImmutableSet.<String>of());
- ImmutableSet<String> accesibleObjectMethods =
+ ImmutableSet<String> accessibleObjectMethods =
publicMethodSignatures(AccessibleObject.class, ImmutableSet.of("canAccess"));
- assertThat(invokableMethods).containsAtLeastElementsIn(accesibleObjectMethods);
+ assertThat(invokableMethods).containsAtLeastElementsIn(accessibleObjectMethods);
Class<?> genericDeclaration;
try {
genericDeclaration = Class.forName("java.lang.reflect.GenericDeclaration");
@@ -453,7 +453,7 @@ public class InvokableTest extends TestCase {
static class Foo {}
- public void testConstructor_isOverridablel() throws Exception {
+ public void testConstructor_isOverridable() throws Exception {
Invokable<?, ?> delegate = Invokable.from(Foo.class.getDeclaredConstructor());
assertFalse(delegate.isOverridable());
assertFalse(delegate.isVarArgs());
@@ -520,7 +520,7 @@ public class InvokableTest extends TestCase {
private class InnerWithAnnotatedConstructorParameter {
@SuppressWarnings("unused") // called by reflection
- InnerWithAnnotatedConstructorParameter(@CheckForNull String s) {}
+ InnerWithAnnotatedConstructorParameter(@Nullable String s) {}
}
public void testInnerClassWithAnnotatedConstructorParameter() {
@@ -684,7 +684,7 @@ public class InvokableTest extends TestCase {
public void testLocalClassWithAnnotatedConstructorParameter() throws Exception {
class LocalWithAnnotatedConstructorParameter {
@SuppressWarnings("unused") // called by reflection
- LocalWithAnnotatedConstructorParameter(@CheckForNull String s) {}
+ LocalWithAnnotatedConstructorParameter(@Nullable String s) {}
}
Constructor<?> constructor =
LocalWithAnnotatedConstructorParameter.class.getDeclaredConstructors()[0];
@@ -733,7 +733,7 @@ public class InvokableTest extends TestCase {
private final String prefix;
private final int times;
- Prepender(@NotBlank String prefix, int times) throws NullPointerException {
+ Prepender(@NotBlank @Nullable String prefix, int times) throws NullPointerException {
this.prefix = prefix;
this.times = times;
}
diff --git a/android/guava-tests/test/com/google/common/reflect/ParameterTest.java b/android/guava-tests/test/com/google/common/reflect/ParameterTest.java
index 6e0500a9c..86ea0104f 100644
--- a/android/guava-tests/test/com/google/common/reflect/ParameterTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/ParameterTest.java
@@ -29,6 +29,16 @@ import junit.framework.TestCase;
public class ParameterTest extends TestCase {
public void testNulls() {
+ try {
+ Class.forName("java.lang.reflect.AnnotatedType");
+ } catch (ClassNotFoundException runningInAndroidVm) {
+ /*
+ * Parameter declares a method that returns AnnotatedType, which isn't available on Android.
+ * This would cause NullPointerTester, which calls Class.getDeclaredMethods, to throw
+ * NoClassDefFoundError.
+ */
+ return;
+ }
for (Method method : ParameterTest.class.getDeclaredMethods()) {
for (Parameter param : Invokable.from(method).getParameters()) {
new NullPointerTester().testAllPublicInstanceMethods(param);
diff --git a/android/guava-tests/test/com/google/common/reflect/SubtypeTester.java b/android/guava-tests/test/com/google/common/reflect/SubtypeTester.java
index 3eec66843..7cd61c129 100644
--- a/android/guava-tests/test/com/google/common/reflect/SubtypeTester.java
+++ b/android/guava-tests/test/com/google/common/reflect/SubtypeTester.java
@@ -30,6 +30,7 @@ import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Comparator;
import javax.lang.model.element.Modifier;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester of subtyping relationships between two types.
@@ -78,7 +79,7 @@ abstract class SubtypeTester implements Cloneable {
boolean suppressGetSupertype() default false;
}
- private Method method = null;
+ private @Nullable Method method = null;
/** Call this in a {@link TestSubtype} public method asserting subtype relationship. */
final <T> T isSubtype(T sub) {
@@ -105,7 +106,7 @@ abstract class SubtypeTester implements Cloneable {
* Call this in a {@link TestSubtype} public method asserting that subtype relationship does not
* hold.
*/
- final <X> X notSubtype(@SuppressWarnings("unused") Object sub) {
+ final <X> @Nullable X notSubtype(@SuppressWarnings("unused") Object sub) {
Type returnType = method.getGenericReturnType();
Type paramType = getOnlyParameterType();
TestSubtype spec = method.getAnnotation(TestSubtype.class);
diff --git a/android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java b/android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
index 69e59ff18..b8f5edbe0 100644
--- a/android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
@@ -178,10 +178,12 @@ public class TypeTokenResolutionTest extends TestCase {
assertEquals(String.class, new Owner.Nested<String>() {}.getTypeArgument());
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testResolveInnerClass() {
assertEquals(String.class, new Owner<Integer>().new Inner<String>() {}.getTypeArgument());
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testResolveOwnerClass() {
assertEquals(Integer.class, new Owner<Integer>().new Inner<String>() {}.getOwnerType());
}
@@ -253,7 +255,7 @@ public class TypeTokenResolutionTest extends TestCase {
}
}
- public void testConextIsParameterizedType() throws Exception {
+ public void testContextIsParameterizedType() throws Exception {
class Context {
@SuppressWarnings("unused") // used by reflection
Map<String, Integer> returningMap() {
diff --git a/android/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java b/android/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
index 0dd2318e9..b25aab57c 100644
--- a/android/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
@@ -47,30 +47,35 @@ public class TypeTokenSubtypeTest extends TestCase {
}
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfInnerClass_nonStaticAnonymousClass() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfInnerClass_nonStaticAnonymousClass_typeParameterOfOwnerTypeNotMatch() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Indoor>().new Shop<Electronics>() {}.getClass();
assertFalse(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfInnerClass_nonStaticAnonymousClass_typeParameterOfInnerTypeNotMatch() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Outdoor>().new Shop<Grocery>() {}.getClass();
assertFalse(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public static void testSubtypeOfInnerClass_staticAnonymousClass() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public static void testSubtypeOfStaticAnonymousClass() {
Class<?> superclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(superclass).isSubtypeOf(superclass));
@@ -79,6 +84,7 @@ public class TypeTokenSubtypeTest extends TestCase {
.isSubtypeOf(superclass));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfNonStaticAnonymousClass() {
Class<?> superclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(superclass).isSubtypeOf(superclass));
@@ -231,7 +237,7 @@ public class TypeTokenSubtypeTest extends TestCase {
@TestSubtype(suppressGetSupertype = true, suppressGetSubtype = true)
public List<RecursiveTypeBoundBugExample<?>> ifYouUseTheTypeVariableOnTheClassAndItIsRecursive(
List<RecursiveTypeBoundBugExample<? extends RecursiveTypeBoundBugExample<T>>> arg) {
- return notSubtype(arg); // isSubtype() currently incorectly considers it a subtype.
+ return notSubtype(arg); // isSubtype() currently incorrectly considers it a subtype.
}
}
diff --git a/android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java b/android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
index 171ef49fd..5d66b840b 100644
--- a/android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
+++ b/android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
@@ -402,7 +402,7 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends ArrayList<String> & CharSequence>
+ public <T extends ArrayList<String> & Serializable>
void testGetGenericSuperclass_typeVariable_boundIsClass() {
assertEquals(
new TypeToken<ArrayList<String>>() {},
@@ -410,7 +410,7 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends Enum<T> & CharSequence>
+ public <T extends Enum<T> & Serializable>
void testGetGenericSuperclass_typeVariable_boundIsFBoundedClass() {
assertEquals(
new TypeToken<Enum<T>>() {},
@@ -418,13 +418,13 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends List<String> & CharSequence>
+ public <T extends List<String> & Serializable>
void testGetGenericSuperclass_typeVariable_boundIsInterface() {
assertNull(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericSuperclass());
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends ArrayList<String> & CharSequence, T1 extends T>
+ public <T extends ArrayList<String> & Serializable, T1 extends T>
void testGetGenericSuperclass_typeVariable_boundIsTypeVariableAndClass() {
assertEquals(
TypeToken.of(new TypeCapture<T>() {}.capture()),
@@ -432,7 +432,7 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends List<String> & CharSequence, T1 extends T>
+ public <T extends List<String> & Serializable, T1 extends T>
void testGetGenericSuperclass_typeVariable_boundIsTypeVariableAndInterface() {
assertNull(TypeToken.of(new TypeCapture<T1>() {}.capture()).getGenericSuperclass());
assertEquals(TypeToken.of(Object.class), new TypeToken<T1[]>() {}.getGenericSuperclass());
@@ -1101,7 +1101,7 @@ public class TypeTokenTest extends TestCase {
}
public void testGetSupertype_chained() {
- @SuppressWarnings("unchecked") // StringListIterable extensd ListIterable<String>
+ @SuppressWarnings("unchecked") // StringListIterable extends ListIterable<String>
TypeToken<ListIterable<String>> listIterableType =
(TypeToken<ListIterable<String>>)
TypeToken.of(StringListIterable.class).getSupertype(ListIterable.class);
@@ -1747,6 +1747,7 @@ public class TypeTokenTest extends TestCase {
}
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public <T> void testRejectTypeVariable_withOwnerType() {
// Neither has subclass
assertHasTypeVariable(new From<Integer>().new To<String>().type());
@@ -1793,7 +1794,7 @@ public class TypeTokenTest extends TestCase {
abstract <T2 extends CharSequence & Iterable<T2>> void acceptT2(T2 t2);
- static void verifyConsitentRawType() {
+ static void verifyConsistentRawType() {
for (Method method : RawTypeConsistencyTester.class.getDeclaredMethods()) {
assertEquals(
method.getReturnType(), TypeToken.of(method.getGenericReturnType()).getRawType());
@@ -1807,7 +1808,7 @@ public class TypeTokenTest extends TestCase {
}
public void testRawTypes() {
- RawTypeConsistencyTester.verifyConsitentRawType();
+ RawTypeConsistencyTester.verifyConsistentRawType();
assertEquals(Object.class, TypeToken.of(Types.subtypeOf(Object.class)).getRawType());
assertEquals(
CharSequence.class, TypeToken.of(Types.subtypeOf(CharSequence.class)).getRawType());
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
index 991cada29..8e94f174f 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
@@ -34,6 +34,7 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base class for tests for emulated {@link AbstractFuture} that allow subclasses to swap in a
@@ -443,7 +444,8 @@ abstract class AbstractAbstractFutureTest extends TestCase {
verifyTimedGetOnPendingFuture(future);
}
- private static void assertSuccessful(AbstractFuture<Integer> future, Integer expectedResult)
+ private static void assertSuccessful(
+ AbstractFuture<Integer> future, @Nullable Integer expectedResult)
throws InterruptedException, TimeoutException, ExecutionException {
assertDone(future);
assertThat(future.isCancelled()).isFalse();
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureBenchmarks.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureBenchmarks.java
index ed5e6a96d..d90c5bbe8 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureBenchmarks.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureBenchmarks.java
@@ -25,7 +25,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Utilities for the AbstractFutureBenchmarks */
final class AbstractFutureBenchmarks {
@@ -218,7 +218,7 @@ final class AbstractFutureBenchmarks {
* @return true if the state was successfully changed.
*/
@CanIgnoreReturnValue
- protected boolean set(@CheckForNull V value) {
+ protected boolean set(@Nullable V value) {
boolean result = sync.set(value);
if (result) {
executionList.execute();
@@ -360,7 +360,7 @@ final class AbstractFutureBenchmarks {
}
/** Transition to the COMPLETED state and set the value. */
- boolean set(@CheckForNull V v) {
+ boolean set(@Nullable V v) {
return complete(v, null, COMPLETED);
}
@@ -384,7 +384,7 @@ final class AbstractFutureBenchmarks {
* @param t the exception to set as the result of the computation.
* @param finalState the state to transition to.
*/
- private boolean complete(@CheckForNull V v, @CheckForNull Throwable t, int finalState) {
+ private boolean complete(@Nullable V v, @Nullable Throwable t, int finalState) {
boolean doCompletion = compareAndSetState(RUNNING, COMPLETING);
if (doCompletion) {
// If this thread successfully transitioned to COMPLETING, set the value
@@ -406,7 +406,7 @@ final class AbstractFutureBenchmarks {
}
static final CancellationException cancellationExceptionWithCause(
- @CheckForNull String message, @CheckForNull Throwable cause) {
+ @Nullable String message, @Nullable Throwable cause) {
CancellationException exception = new CancellationException(message);
exception.initCause(cause);
return exception;
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
index dc020fb20..89d92c8c4 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
@@ -16,6 +16,8 @@
package com.google.common.util.concurrent;
+import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
@@ -23,6 +25,7 @@ import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
+import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
import java.util.ArrayList;
import java.util.Arrays;
@@ -46,6 +49,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link AbstractFuture}.
@@ -293,6 +297,13 @@ public class AbstractFutureTest extends TestCase {
@SuppressWarnings({"DeprecatedThreadMethods", "ThreadPriorityCheck"})
@AndroidIncompatible // Thread.suspend
public void testToString_delayedTimeout() throws Exception {
+ Integer javaVersion = Ints.tryParse(JAVA_SPECIFICATION_VERSION.value());
+ // Parsing to an integer might fail because Java 8 returns "1.8" instead of "8."
+ // We can continue if it's 1.8, and we can continue if it's an integer in [9, 20).
+ if (javaVersion != null && javaVersion >= 20) {
+ // TODO(b/261217224): Make this test work under newer JDKs.
+ return;
+ }
TimedWaiterThread thread =
new TimedWaiterThread(new AbstractFuture<Object>() {}, 2, TimeUnit.SECONDS);
thread.start();
@@ -426,6 +437,9 @@ public class AbstractFutureTest extends TestCase {
*/
public void testFutureBash() {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Running very slowly on Windows CI.
+ }
final CyclicBarrier barrier =
new CyclicBarrier(
6 // for the setter threads
@@ -435,10 +449,10 @@ public class AbstractFutureTest extends TestCase {
final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicInteger numSuccessfulSetCalls = new AtomicInteger();
- Callable<Void> completeSuccessfullyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> completeSuccessfullyRunnable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().set("set")) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -446,12 +460,12 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> completeExceptionallyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> completeExceptionallyRunnable =
+ new Callable<@Nullable Void>() {
Exception failureCause = new Exception("setException");
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setException(failureCause)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -459,10 +473,10 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> cancelRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> cancelRunnable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().cancel(true)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -470,12 +484,12 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> setFutureCompleteSuccessfullyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCompleteSuccessfullyRunnable =
+ new Callable<@Nullable Void>() {
ListenableFuture<String> future = Futures.immediateFuture("setFuture");
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -483,13 +497,13 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> setFutureCompleteExceptionallyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCompleteExceptionallyRunnable =
+ new Callable<@Nullable Void>() {
ListenableFuture<String> future =
Futures.immediateFailedFuture(new Exception("setFuture"));
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -497,12 +511,12 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> setFutureCancelRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCancelRunnable =
+ new Callable<@Nullable Void>() {
ListenableFuture<String> future = Futures.immediateCancelledFuture();
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -559,15 +573,15 @@ public class AbstractFutureTest extends TestCase {
allTasks.add(setFutureCancelRunnable);
for (int k = 0; k < 50; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
- // get usecase and another task that adds it as a listener to the future to exercise both
+ // get use case and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener =
k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
allTasks.add(Executors.callable(listener));
allTasks.add(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
currentFuture.get().addListener(listener, executor);
return null;
}
@@ -607,6 +621,9 @@ public class AbstractFutureTest extends TestCase {
// setFuture and cancel() interact in more complicated ways than the other setters.
public void testSetFutureCancelBash() {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Running very slowly on Windows CI.
+ }
final int size = 50;
final CyclicBarrier barrier =
new CyclicBarrier(
@@ -683,7 +700,7 @@ public class AbstractFutureTest extends TestCase {
allTasks.add(setFutureCompleteSuccessfullyRunnable);
for (int k = 0; k < size; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
- // get usecase and another task that adds it as a listener to the future to exercise both
+ // get use case and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener =
k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
@@ -751,21 +768,21 @@ public class AbstractFutureTest extends TestCase {
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicBoolean setFutureSuccess = new AtomicBoolean();
final AtomicBoolean cancellationSuccess = new AtomicBoolean();
- Callable<Void> cancelRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> cancelRunnable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
cancellationSuccess.set(currentFuture.get().cancel(true));
awaitUnchecked(barrier);
return null;
}
};
- Callable<Void> setFutureCompleteSuccessfullyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCompleteSuccessfullyRunnable =
+ new Callable<@Nullable Void>() {
final ListenableFuture<String> future = Futures.immediateFuture("hello");
@Override
- public Void call() {
+ public @Nullable Void call() {
setFutureSuccess.set(currentFuture.get().setFuture(future));
awaitUnchecked(barrier);
return null;
@@ -1200,13 +1217,10 @@ public class AbstractFutureTest extends TestCase {
throws InterruptedException {
try {
String got = future.get();
- fail("Expected exception but got " + got);
+ throw new AssertionError("Expected exception but got " + got);
} catch (ExecutionException e) {
return e;
}
-
- // unreachable, but compiler doesn't know that fail() always throws
- return null;
}
private static final class WaiterThread extends Thread {
@@ -1318,4 +1332,8 @@ public class AbstractFutureTest extends TestCase {
interruptTaskWasCalled = true;
}
}
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
index 2df5a4f3a..0444c31be 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
@@ -33,65 +33,6 @@ import junit.framework.TestCase;
* @author Ben Yu
*/
public class AbstractIdleServiceTest extends TestCase {
-
- // Functional tests using real thread. We only verify publicly visible state.
- // Interaction assertions are done by the single-threaded unit tests.
- public static class FunctionalTest extends TestCase {
-
- private static class DefaultService extends AbstractIdleService {
- @Override
- protected void startUp() throws Exception {}
-
- @Override
- protected void shutDown() throws Exception {}
- }
-
- public void testServiceStartStop() throws Exception {
- AbstractIdleService service = new DefaultService();
- service.startAsync().awaitRunning();
- assertEquals(Service.State.RUNNING, service.state());
- service.stopAsync().awaitTerminated();
- assertEquals(Service.State.TERMINATED, service.state());
- }
-
- public void testStart_failed() throws Exception {
- final Exception exception = new Exception("deliberate");
- AbstractIdleService service =
- new DefaultService() {
- @Override
- protected void startUp() throws Exception {
- throw exception;
- }
- };
- try {
- service.startAsync().awaitRunning();
- fail();
- } catch (RuntimeException e) {
- assertThat(e).hasCauseThat().isSameInstanceAs(exception);
- }
- assertEquals(Service.State.FAILED, service.state());
- }
-
- public void testStop_failed() throws Exception {
- final Exception exception = new Exception("deliberate");
- AbstractIdleService service =
- new DefaultService() {
- @Override
- protected void shutDown() throws Exception {
- throw exception;
- }
- };
- service.startAsync().awaitRunning();
- try {
- service.stopAsync().awaitTerminated();
- fail();
- } catch (RuntimeException e) {
- assertThat(e).hasCauseThat().isSameInstanceAs(exception);
- }
- assertEquals(Service.State.FAILED, service.state());
- }
- }
-
public void testStart() {
TestService service = new TestService();
assertEquals(0, service.startUpCalled);
@@ -236,4 +177,60 @@ public class AbstractIdleServiceTest extends TestCase {
return directExecutor();
}
}
+
+ // Functional tests using real thread. We only verify publicly visible state.
+ // Interaction assertions are done by the single-threaded unit tests.
+
+ private static class DefaultService extends AbstractIdleService {
+ @Override
+ protected void startUp() throws Exception {}
+
+ @Override
+ protected void shutDown() throws Exception {}
+ }
+
+ public void testFunctionalServiceStartStop() {
+ AbstractIdleService service = new DefaultService();
+ service.startAsync().awaitRunning();
+ assertEquals(Service.State.RUNNING, service.state());
+ service.stopAsync().awaitTerminated();
+ assertEquals(Service.State.TERMINATED, service.state());
+ }
+
+ public void testFunctionalStart_failed() {
+ final Exception exception = new Exception("deliberate");
+ AbstractIdleService service =
+ new DefaultService() {
+ @Override
+ protected void startUp() throws Exception {
+ throw exception;
+ }
+ };
+ try {
+ service.startAsync().awaitRunning();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasCauseThat().isSameInstanceAs(exception);
+ }
+ assertEquals(Service.State.FAILED, service.state());
+ }
+
+ public void testFunctionalStop_failed() {
+ final Exception exception = new Exception("deliberate");
+ AbstractIdleService service =
+ new DefaultService() {
+ @Override
+ protected void shutDown() throws Exception {
+ throw exception;
+ }
+ };
+ service.startAsync().awaitRunning();
+ try {
+ service.stopAsync().awaitTerminated();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasCauseThat().isSameInstanceAs(exception);
+ }
+ assertEquals(Service.State.FAILED, service.state());
+ }
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
index a05a83869..f7266b274 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
@@ -43,6 +43,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractScheduledService}.
@@ -52,7 +53,7 @@ import junit.framework.TestCase;
public class AbstractScheduledServiceTest extends TestCase {
volatile Scheduler configuration = newFixedDelaySchedule(0, 10, MILLISECONDS);
- volatile ScheduledFuture<?> future = null;
+ volatile @Nullable ScheduledFuture<?> future = null;
volatile boolean atFixedRateCalled = false;
volatile boolean withFixedDelayCalled = false;
@@ -313,9 +314,9 @@ public class AbstractScheduledServiceTest extends TestCase {
AtomicInteger numberOfTimesRunCalled = new AtomicInteger(0);
AtomicInteger numberOfTimesExecutorCalled = new AtomicInteger(0);
AtomicInteger numberOfTimesSchedulerCalled = new AtomicInteger(0);
- volatile Exception runException = null;
- volatile Exception startUpException = null;
- volatile Exception shutDownException = null;
+ volatile @Nullable Exception runException = null;
+ volatile @Nullable Exception startUpException = null;
+ volatile @Nullable Exception shutDownException = null;
@Override
protected void runOneIteration() throws Exception {
@@ -364,317 +365,317 @@ public class AbstractScheduledServiceTest extends TestCase {
}
}
- public static class SchedulerTest extends TestCase {
- // These constants are arbitrary and just used to make sure that the correct method is called
- // with the correct parameters.
- private static final int INITIAL_DELAY = 10;
- private static final int DELAY = 20;
- private static final TimeUnit UNIT = MILLISECONDS;
+ // Tests for Scheduler:
- // Unique runnable object used for comparison.
- final Runnable testRunnable =
- new Runnable() {
- @Override
- public void run() {}
- };
- boolean called = false;
-
- private void assertSingleCallWithCorrectParameters(
- Runnable command, long initialDelay, long delay, TimeUnit unit) {
- assertFalse(called); // only called once.
- called = true;
- assertEquals(INITIAL_DELAY, initialDelay);
- assertEquals(DELAY, delay);
- assertEquals(UNIT, unit);
- assertEquals(testRunnable, command);
- }
+ // These constants are arbitrary and just used to make sure that the correct method is called
+ // with the correct parameters.
+ private static final int INITIAL_DELAY = 10;
+ private static final int DELAY = 20;
+ private static final TimeUnit UNIT = MILLISECONDS;
- public void testFixedRateSchedule() {
- Scheduler schedule = Scheduler.newFixedRateSchedule(INITIAL_DELAY, DELAY, UNIT);
- Cancellable unused =
- schedule.schedule(
- null,
- new ScheduledThreadPoolExecutor(1) {
- @Override
- public ScheduledFuture<?> scheduleAtFixedRate(
- Runnable command, long initialDelay, long period, TimeUnit unit) {
- assertSingleCallWithCorrectParameters(command, initialDelay, period, unit);
- return new ThrowingScheduledFuture<>();
- }
- },
- testRunnable);
- assertTrue(called);
- }
-
- public void testFixedDelaySchedule() {
- Scheduler schedule = newFixedDelaySchedule(INITIAL_DELAY, DELAY, UNIT);
- Cancellable unused =
- schedule.schedule(
- null,
- new ScheduledThreadPoolExecutor(10) {
- @Override
- public ScheduledFuture<?> scheduleWithFixedDelay(
- Runnable command, long initialDelay, long delay, TimeUnit unit) {
- assertSingleCallWithCorrectParameters(command, initialDelay, delay, unit);
- return new ThrowingScheduledFuture<>();
- }
- },
- testRunnable);
- assertTrue(called);
- }
+ // Unique runnable object used for comparison.
+ final Runnable testRunnable =
+ new Runnable() {
+ @Override
+ public void run() {}
+ };
+ boolean called = false;
+
+ private void assertSingleCallWithCorrectParameters(
+ Runnable command, long initialDelay, long delay, TimeUnit unit) {
+ assertFalse(called); // only called once.
+ called = true;
+ assertEquals(INITIAL_DELAY, initialDelay);
+ assertEquals(DELAY, delay);
+ assertEquals(UNIT, unit);
+ assertEquals(testRunnable, command);
+ }
- private static final class ThrowingScheduledFuture<V> extends ForwardingFuture<V>
- implements ScheduledFuture<V> {
- @Override
- protected Future<V> delegate() {
- throw new UnsupportedOperationException("test should not care about this");
- }
+ public void testFixedRateSchedule() {
+ Scheduler schedule = Scheduler.newFixedRateSchedule(INITIAL_DELAY, DELAY, UNIT);
+ Cancellable unused =
+ schedule.schedule(
+ null,
+ new ScheduledThreadPoolExecutor(1) {
+ @Override
+ public ScheduledFuture<?> scheduleAtFixedRate(
+ Runnable command, long initialDelay, long period, TimeUnit unit) {
+ assertSingleCallWithCorrectParameters(command, initialDelay, period, unit);
+ return new ThrowingScheduledFuture<>();
+ }
+ },
+ testRunnable);
+ assertTrue(called);
+ }
- @Override
- public long getDelay(TimeUnit unit) {
- throw new UnsupportedOperationException("test should not care about this");
- }
+ public void testFixedDelaySchedule() {
+ Scheduler schedule = newFixedDelaySchedule(INITIAL_DELAY, DELAY, UNIT);
+ Cancellable unused =
+ schedule.schedule(
+ null,
+ new ScheduledThreadPoolExecutor(10) {
+ @Override
+ public ScheduledFuture<?> scheduleWithFixedDelay(
+ Runnable command, long initialDelay, long delay, TimeUnit unit) {
+ assertSingleCallWithCorrectParameters(command, initialDelay, delay, unit);
+ return new ThrowingScheduledFuture<>();
+ }
+ },
+ testRunnable);
+ assertTrue(called);
+ }
- @Override
- public int compareTo(Delayed other) {
- throw new UnsupportedOperationException("test should not care about this");
- }
+ private static final class ThrowingScheduledFuture<V> extends ForwardingFuture<V>
+ implements ScheduledFuture<V> {
+ @Override
+ protected Future<V> delegate() {
+ throw new UnsupportedOperationException("test should not care about this");
}
- public void testFixedDelayScheduleFarFuturePotentiallyOverflowingScheduleIsNeverReached()
- throws Exception {
- TestAbstractScheduledCustomService service =
- new TestAbstractScheduledCustomService() {
- @Override
- protected Scheduler scheduler() {
- return newFixedDelaySchedule(Long.MAX_VALUE, Long.MAX_VALUE, SECONDS);
- }
- };
- service.startAsync().awaitRunning();
- try {
- service.firstBarrier.await(5, SECONDS);
- fail();
- } catch (TimeoutException expected) {
- }
- assertEquals(0, service.numIterations.get());
- service.stopAsync();
- service.awaitTerminated();
+ @Override
+ public long getDelay(TimeUnit unit) {
+ throw new UnsupportedOperationException("test should not care about this");
}
- public void testCustomSchedulerFarFuturePotentiallyOverflowingScheduleIsNeverReached()
- throws Exception {
- TestAbstractScheduledCustomService service =
- new TestAbstractScheduledCustomService() {
- @Override
- protected Scheduler scheduler() {
- return new AbstractScheduledService.CustomScheduler() {
- @Override
- protected Schedule getNextSchedule() throws Exception {
- return new Schedule(Long.MAX_VALUE, SECONDS);
- }
- };
- }
- };
- service.startAsync().awaitRunning();
- try {
- service.firstBarrier.await(5, SECONDS);
- fail();
- } catch (TimeoutException expected) {
- }
- assertEquals(0, service.numIterations.get());
- service.stopAsync();
- service.awaitTerminated();
+ @Override
+ public int compareTo(Delayed other) {
+ throw new UnsupportedOperationException("test should not care about this");
}
+ }
- private static class TestCustomScheduler extends AbstractScheduledService.CustomScheduler {
- public AtomicInteger scheduleCounter = new AtomicInteger(0);
-
- @Override
- protected Schedule getNextSchedule() throws Exception {
- scheduleCounter.incrementAndGet();
- return new Schedule(0, SECONDS);
- }
+ public void testFixedDelayScheduleFarFuturePotentiallyOverflowingScheduleIsNeverReached()
+ throws Exception {
+ TestAbstractScheduledCustomService service =
+ new TestAbstractScheduledCustomService() {
+ @Override
+ protected Scheduler scheduler() {
+ return newFixedDelaySchedule(Long.MAX_VALUE, Long.MAX_VALUE, SECONDS);
+ }
+ };
+ service.startAsync().awaitRunning();
+ try {
+ service.firstBarrier.await(5, SECONDS);
+ fail();
+ } catch (TimeoutException expected) {
}
+ assertEquals(0, service.numIterations.get());
+ service.stopAsync();
+ service.awaitTerminated();
+ }
- public void testCustomSchedule_startStop() throws Exception {
- final CyclicBarrier firstBarrier = new CyclicBarrier(2);
- final CyclicBarrier secondBarrier = new CyclicBarrier(2);
- final AtomicBoolean shouldWait = new AtomicBoolean(true);
- Runnable task =
- new Runnable() {
- @Override
- public void run() {
- try {
- if (shouldWait.get()) {
- firstBarrier.await();
- secondBarrier.await();
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
+ public void testCustomSchedulerFarFuturePotentiallyOverflowingScheduleIsNeverReached()
+ throws Exception {
+ TestAbstractScheduledCustomService service =
+ new TestAbstractScheduledCustomService() {
+ @Override
+ protected Scheduler scheduler() {
+ return new AbstractScheduledService.CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ return new Schedule(Long.MAX_VALUE, SECONDS);
}
- }
- };
- TestCustomScheduler scheduler = new TestCustomScheduler();
- Cancellable future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
- firstBarrier.await();
- assertEquals(1, scheduler.scheduleCounter.get());
- secondBarrier.await();
- firstBarrier.await();
- assertEquals(2, scheduler.scheduleCounter.get());
- shouldWait.set(false);
- secondBarrier.await();
- future.cancel(false);
+ };
+ }
+ };
+ service.startAsync().awaitRunning();
+ try {
+ service.firstBarrier.await(5, SECONDS);
+ fail();
+ } catch (TimeoutException expected) {
}
+ assertEquals(0, service.numIterations.get());
+ service.stopAsync();
+ service.awaitTerminated();
+ }
- public void testCustomSchedulerServiceStop() throws Exception {
- TestAbstractScheduledCustomService service = new TestAbstractScheduledCustomService();
- service.startAsync().awaitRunning();
- service.firstBarrier.await();
- assertEquals(1, service.numIterations.get());
- service.stopAsync();
- service.secondBarrier.await();
- service.awaitTerminated();
- // Sleep for a while just to ensure that our task wasn't called again.
- Thread.sleep(UNIT.toMillis(3 * DELAY));
- assertEquals(1, service.numIterations.get());
- }
+ private static class TestCustomScheduler extends AbstractScheduledService.CustomScheduler {
+ public AtomicInteger scheduleCounter = new AtomicInteger(0);
- public void testCustomScheduler_deadlock() throws InterruptedException, BrokenBarrierException {
- final CyclicBarrier inGetNextSchedule = new CyclicBarrier(2);
- // This will flakily deadlock, so run it multiple times to increase the flake likelihood
- for (int i = 0; i < 1000; i++) {
- Service service =
- new AbstractScheduledService() {
- @Override
- protected void runOneIteration() {}
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ scheduleCounter.incrementAndGet();
+ return new Schedule(0, SECONDS);
+ }
+ }
- @Override
- protected Scheduler scheduler() {
- return new CustomScheduler() {
- @Override
- protected Schedule getNextSchedule() throws Exception {
- if (state() != State.STARTING) {
- inGetNextSchedule.await();
- Thread.yield();
- throw new RuntimeException("boom");
- }
- return new Schedule(0, NANOSECONDS);
- }
- };
+ public void testCustomSchedule_startStop() throws Exception {
+ final CyclicBarrier firstBarrier = new CyclicBarrier(2);
+ final CyclicBarrier secondBarrier = new CyclicBarrier(2);
+ final AtomicBoolean shouldWait = new AtomicBoolean(true);
+ Runnable task =
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if (shouldWait.get()) {
+ firstBarrier.await();
+ secondBarrier.await();
}
- };
- service.startAsync().awaitRunning();
- inGetNextSchedule.await();
- service.stopAsync();
- }
- }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ TestCustomScheduler scheduler = new TestCustomScheduler();
+ Cancellable future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
+ firstBarrier.await();
+ assertEquals(1, scheduler.scheduleCounter.get());
+ secondBarrier.await();
+ firstBarrier.await();
+ assertEquals(2, scheduler.scheduleCounter.get());
+ shouldWait.set(false);
+ secondBarrier.await();
+ future.cancel(false);
+ }
+
+ public void testCustomSchedulerServiceStop() throws Exception {
+ TestAbstractScheduledCustomService service = new TestAbstractScheduledCustomService();
+ service.startAsync().awaitRunning();
+ service.firstBarrier.await();
+ assertEquals(1, service.numIterations.get());
+ service.stopAsync();
+ service.secondBarrier.await();
+ service.awaitTerminated();
+ // Sleep for a while just to ensure that our task wasn't called again.
+ Thread.sleep(UNIT.toMillis(3 * DELAY));
+ assertEquals(1, service.numIterations.get());
+ }
+
+ public void testCustomScheduler_deadlock() throws InterruptedException, BrokenBarrierException {
+ final CyclicBarrier inGetNextSchedule = new CyclicBarrier(2);
+ // This will flakily deadlock, so run it multiple times to increase the flake likelihood
+ for (int i = 0; i < 1000; i++) {
+ Service service =
+ new AbstractScheduledService() {
+ @Override
+ protected void runOneIteration() {}
- public void testBig() throws Exception {
- TestAbstractScheduledCustomService service =
- new TestAbstractScheduledCustomService() {
@Override
protected Scheduler scheduler() {
- return new AbstractScheduledService.CustomScheduler() {
+ return new CustomScheduler() {
@Override
protected Schedule getNextSchedule() throws Exception {
- // Explicitly yield to increase the probability of a pathological scheduling.
- Thread.yield();
- return new Schedule(0, SECONDS);
+ if (state() != State.STARTING) {
+ inGetNextSchedule.await();
+ Thread.yield();
+ throw new RuntimeException("boom");
+ }
+ return new Schedule(0, NANOSECONDS);
}
};
}
};
- service.useBarriers = false;
service.startAsync().awaitRunning();
- Thread.sleep(50);
- service.useBarriers = true;
- service.firstBarrier.await();
- int numIterations = service.numIterations.get();
+ inGetNextSchedule.await();
service.stopAsync();
- service.secondBarrier.await();
- service.awaitTerminated();
- assertEquals(numIterations, service.numIterations.get());
}
+ }
- private static class TestAbstractScheduledCustomService extends AbstractScheduledService {
- final AtomicInteger numIterations = new AtomicInteger(0);
- volatile boolean useBarriers = true;
- final CyclicBarrier firstBarrier = new CyclicBarrier(2);
- final CyclicBarrier secondBarrier = new CyclicBarrier(2);
-
- @Override
- protected void runOneIteration() throws Exception {
- numIterations.incrementAndGet();
- if (useBarriers) {
- firstBarrier.await();
- secondBarrier.await();
- }
- }
-
- @Override
- protected ScheduledExecutorService executor() {
- // use a bunch of threads so that weird overlapping schedules are more likely to happen.
- return Executors.newScheduledThreadPool(10);
- }
-
- @Override
- protected Scheduler scheduler() {
- return new CustomScheduler() {
+ public void testBig() throws Exception {
+ TestAbstractScheduledCustomService service =
+ new TestAbstractScheduledCustomService() {
@Override
- protected Schedule getNextSchedule() throws Exception {
- return new Schedule(DELAY, UNIT);
+ protected Scheduler scheduler() {
+ return new AbstractScheduledService.CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ // Explicitly yield to increase the probability of a pathological scheduling.
+ Thread.yield();
+ return new Schedule(0, SECONDS);
+ }
+ };
}
};
+ service.useBarriers = false;
+ service.startAsync().awaitRunning();
+ Thread.sleep(50);
+ service.useBarriers = true;
+ service.firstBarrier.await();
+ int numIterations = service.numIterations.get();
+ service.stopAsync();
+ service.secondBarrier.await();
+ service.awaitTerminated();
+ assertEquals(numIterations, service.numIterations.get());
+ }
+
+ private static class TestAbstractScheduledCustomService extends AbstractScheduledService {
+ final AtomicInteger numIterations = new AtomicInteger(0);
+ volatile boolean useBarriers = true;
+ final CyclicBarrier firstBarrier = new CyclicBarrier(2);
+ final CyclicBarrier secondBarrier = new CyclicBarrier(2);
+
+ @Override
+ protected void runOneIteration() throws Exception {
+ numIterations.incrementAndGet();
+ if (useBarriers) {
+ firstBarrier.await();
+ secondBarrier.await();
}
}
- public void testCustomSchedulerFailure() throws Exception {
- TestFailingCustomScheduledService service = new TestFailingCustomScheduledService();
- service.startAsync().awaitRunning();
- for (int i = 1; i < 4; i++) {
- service.firstBarrier.await();
- assertEquals(i, service.numIterations.get());
- service.secondBarrier.await();
- }
- Thread.sleep(1000);
- try {
- service.stopAsync().awaitTerminated(100, SECONDS);
- fail();
- } catch (IllegalStateException e) {
- assertEquals(State.FAILED, service.state());
- }
+ @Override
+ protected ScheduledExecutorService executor() {
+ // use a bunch of threads so that weird overlapping schedules are more likely to happen.
+ return Executors.newScheduledThreadPool(10);
}
- private static class TestFailingCustomScheduledService extends AbstractScheduledService {
- final AtomicInteger numIterations = new AtomicInteger(0);
- final CyclicBarrier firstBarrier = new CyclicBarrier(2);
- final CyclicBarrier secondBarrier = new CyclicBarrier(2);
+ @Override
+ protected Scheduler scheduler() {
+ return new CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ return new Schedule(DELAY, UNIT);
+ }
+ };
+ }
+ }
- @Override
- protected void runOneIteration() throws Exception {
- numIterations.incrementAndGet();
- firstBarrier.await();
- secondBarrier.await();
- }
+ public void testCustomSchedulerFailure() throws Exception {
+ TestFailingCustomScheduledService service = new TestFailingCustomScheduledService();
+ service.startAsync().awaitRunning();
+ for (int i = 1; i < 4; i++) {
+ service.firstBarrier.await();
+ assertEquals(i, service.numIterations.get());
+ service.secondBarrier.await();
+ }
+ Thread.sleep(1000);
+ try {
+ service.stopAsync().awaitTerminated(100, SECONDS);
+ fail();
+ } catch (IllegalStateException e) {
+ assertEquals(State.FAILED, service.state());
+ }
+ }
- @Override
- protected ScheduledExecutorService executor() {
- // use a bunch of threads so that weird overlapping schedules are more likely to happen.
- return Executors.newScheduledThreadPool(10);
- }
+ private static class TestFailingCustomScheduledService extends AbstractScheduledService {
+ final AtomicInteger numIterations = new AtomicInteger(0);
+ final CyclicBarrier firstBarrier = new CyclicBarrier(2);
+ final CyclicBarrier secondBarrier = new CyclicBarrier(2);
- @Override
- protected Scheduler scheduler() {
- return new CustomScheduler() {
- @Override
- protected Schedule getNextSchedule() throws Exception {
- if (numIterations.get() > 2) {
- throw new IllegalStateException("Failed");
- }
- return new Schedule(DELAY, UNIT);
+ @Override
+ protected void runOneIteration() throws Exception {
+ numIterations.incrementAndGet();
+ firstBarrier.await();
+ secondBarrier.await();
+ }
+
+ @Override
+ protected ScheduledExecutorService executor() {
+ // use a bunch of threads so that weird overlapping schedules are more likely to happen.
+ return Executors.newScheduledThreadPool(10);
+ }
+
+ @Override
+ protected Scheduler scheduler() {
+ return new CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ if (numIterations.get() > 2) {
+ throw new IllegalStateException("Failed");
}
- };
- }
+ return new Schedule(DELAY, UNIT);
+ }
+ };
}
}
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java
index fec93946f..9ddcea9b7 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java
@@ -40,9 +40,9 @@ import junit.framework.TestSuite;
* </ul>
*
* To force selection of our fallback strategies we load {@link AggregateFutureState} (and all of
- * {@code com.google.common.util.concurrent} in degenerate class loaders which make certain platform
- * classes unavailable. Then we construct a test suite so we can run the normal FuturesTest test
- * methods in these degenerate classloaders.
+ * {@code com.google.common.util.concurrent}) in degenerate class loaders which make certain
+ * platform classes unavailable. Then we construct a test suite so we can run the normal FuturesTest
+ * test methods in these degenerate classloaders.
*/
public class AggregateFutureStateFallbackAtomicHelperTest extends TestCase {
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java b/android/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java
index 5bc92dc20..b4766bc8c 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java
@@ -26,6 +26,7 @@ import java.security.Permission;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link Callables}.
@@ -90,10 +91,10 @@ public class CallablesTest extends TestCase {
public void testRenaming() throws Exception {
String oldName = Thread.currentThread().getName();
final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
- Callable<Void> callable =
- new Callable<Void>() {
+ Callable<@Nullable Void> callable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
assertEquals(Thread.currentThread().getName(), newName.get());
return null;
}
@@ -107,10 +108,10 @@ public class CallablesTest extends TestCase {
String oldName = Thread.currentThread().getName();
final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
class MyException extends Exception {}
- Callable<Void> callable =
- new Callable<Void>() {
+ Callable<@Nullable Void> callable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
assertEquals(Thread.currentThread().getName(), newName.get());
throw new MyException();
}
@@ -141,10 +142,10 @@ public class CallablesTest extends TestCase {
try {
final String oldName = Thread.currentThread().getName();
Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
- Callable<Void> callable =
- new Callable<Void>() {
+ Callable<@Nullable Void> callable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
assertEquals(Thread.currentThread().getName(), oldName);
return null;
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java b/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
index 2b1dd2fa0..bf388b0ba 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
@@ -16,6 +16,7 @@
package com.google.common.util.concurrent;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Joiner;
import com.google.common.util.concurrent.CycleDetectingLockFactory.Policies;
@@ -26,8 +27,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import junit.framework.TestCase;
/**
@@ -543,16 +542,6 @@ public class CycleDetectingLockFactoryTest extends TestCase {
// "LockA -> LockB \b.*\b LockB -> LockC \b.*\b LockC -> LockA"
private void checkMessage(IllegalStateException exception, String... expectedLockCycle) {
String regex = Joiner.on("\\b.*\\b").join(expectedLockCycle);
- assertContainsRegex(regex, exception.getMessage());
- }
-
- // TODO(cpovirk): consider adding support for regex to Truth
- private static void assertContainsRegex(String expectedRegex, String actual) {
- Pattern pattern = Pattern.compile(expectedRegex);
- Matcher matcher = pattern.matcher(actual);
- if (!matcher.find()) {
- String actualDesc = (actual == null) ? "null" : ('<' + actual + '>');
- fail("expected to contain regex:<" + expectedRegex + "> but was:" + actualDesc);
- }
+ assertThat(exception).hasMessageThat().containsMatch(regex);
}
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java
index 068287c19..1dafb3b0b 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java
@@ -37,6 +37,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Tests for {@link ExecutionSequencer} */
public class ExecutionSequencerTest extends TestCase {
@@ -44,7 +45,7 @@ public class ExecutionSequencerTest extends TestCase {
ExecutorService executor;
private ExecutionSequencer serializer;
- private SettableFuture<Void> firstFuture;
+ private SettableFuture<@Nullable Void> firstFuture;
private TestCallable firstCallable;
@Override
@@ -76,7 +77,8 @@ public class ExecutionSequencerTest extends TestCase {
@SuppressWarnings({"unused", "nullness"})
Future<?> possiblyIgnoredError = serializer.submitAsync(firstCallable, directExecutor());
TestCallable secondCallable = new TestCallable(Futures.<Void>immediateFuture(null));
- ListenableFuture<Void> secondFuture = serializer.submitAsync(secondCallable, directExecutor());
+ ListenableFuture<@Nullable Void> secondFuture =
+ serializer.submitAsync(secondCallable, directExecutor());
TestCallable thirdCallable = new TestCallable(Futures.<Void>immediateFuture(null));
@SuppressWarnings({"unused", "nullness"})
Future<?> possiblyIgnoredError1 = serializer.submitAsync(thirdCallable, directExecutor());
@@ -90,7 +92,7 @@ public class ExecutionSequencerTest extends TestCase {
public void testCancellationMultipleThreads() throws Exception {
final BlockingCallable blockingCallable = new BlockingCallable();
- ListenableFuture<Void> unused = serializer.submit(blockingCallable, executor);
+ ListenableFuture<@Nullable Void> unused = serializer.submit(blockingCallable, executor);
ListenableFuture<Boolean> future2 =
serializer.submit(
new Callable<Boolean>() {
@@ -117,7 +119,7 @@ public class ExecutionSequencerTest extends TestCase {
public void testSecondTaskWaitsForFirstEvenIfCancelled() throws Exception {
final BlockingCallable blockingCallable = new BlockingCallable();
- ListenableFuture<Void> future1 = serializer.submit(blockingCallable, executor);
+ ListenableFuture<@Nullable Void> future1 = serializer.submit(blockingCallable, executor);
ListenableFuture<Boolean> future2 =
serializer.submit(
new Callable<Boolean>() {
@@ -153,12 +155,12 @@ public class ExecutionSequencerTest extends TestCase {
public void testCancellationWithReferencedObject() throws Exception {
Object toBeGCed = new Object();
WeakReference<Object> ref = new WeakReference<>(toBeGCed);
- final SettableFuture<Void> settableFuture = SettableFuture.create();
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
ListenableFuture<?> ignored =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -195,9 +197,9 @@ public class ExecutionSequencerTest extends TestCase {
final Future<?>[] thingToCancel = new Future<?>[1];
results.add(
serializer.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
thingToCancel[0].cancel(false);
return null;
}
@@ -223,13 +225,13 @@ public class ExecutionSequencerTest extends TestCase {
}
public void testAvoidsStackOverflow_manySubmitted() throws Exception {
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- ArrayList<ListenableFuture<Void>> results = new ArrayList<>(50_001);
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
+ ArrayList<ListenableFuture<@Nullable Void>> results = new ArrayList<>(50_001);
results.add(
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -242,12 +244,12 @@ public class ExecutionSequencerTest extends TestCase {
}
public void testAvoidsStackOverflow_manyCancelled() throws Exception {
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- ListenableFuture<Void> unused =
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
+ ListenableFuture<@Nullable Void> unused =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -270,12 +272,12 @@ public class ExecutionSequencerTest extends TestCase {
}
public void testAvoidsStackOverflow_alternatingCancelledAndSubmitted() throws Exception {
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- ListenableFuture<Void> unused =
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
+ ListenableFuture<@Nullable Void> unused =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -344,12 +346,12 @@ public class ExecutionSequencerTest extends TestCase {
},
service)
.get();
- final SettableFuture<Void> settableFuture = SettableFuture.create();
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
ListenableFuture<?> unused =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -359,9 +361,9 @@ public class ExecutionSequencerTest extends TestCase {
// after some number of iterations, switch threads
unused =
serializer.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
holder.count++;
return null;
}
@@ -383,9 +385,9 @@ public class ExecutionSequencerTest extends TestCase {
// Otherwise, schedule a task on directExecutor
unused =
serializer.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
holder.count++;
return null;
}
@@ -416,14 +418,14 @@ public class ExecutionSequencerTest extends TestCase {
assertThat(second.toString()).contains(secondCallable.future.toString());
}
- private static class BlockingCallable implements Callable<Void> {
+ private static class BlockingCallable implements Callable<@Nullable Void> {
private final CountDownLatch startLatch = new CountDownLatch(1);
private final CountDownLatch stopLatch = new CountDownLatch(1);
private volatile boolean running = false;
@Override
- public Void call() throws InterruptedException {
+ public @Nullable Void call() throws InterruptedException {
running = true;
startLatch.countDown();
stopLatch.await();
@@ -444,17 +446,17 @@ public class ExecutionSequencerTest extends TestCase {
}
}
- private static final class TestCallable implements AsyncCallable<Void> {
+ private static final class TestCallable implements AsyncCallable<@Nullable Void> {
- private final ListenableFuture<Void> future;
+ private final ListenableFuture<@Nullable Void> future;
private boolean called = false;
- private TestCallable(ListenableFuture<Void> future) {
+ private TestCallable(ListenableFuture<@Nullable Void> future) {
this.future = future;
}
@Override
- public ListenableFuture<Void> call() throws Exception {
+ public ListenableFuture<@Nullable Void> call() throws Exception {
called = true;
return future;
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java b/android/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
index 84b0426a6..ad391efdc 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
@@ -28,7 +28,7 @@ import java.lang.reflect.Method;
import java.util.Arrays;
/**
- * Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks.
+ * Tester for typical subclass of {@link ForwardingObject} by using Mockito.
*
* @author Ben Yu
*/
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java b/android/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java
index 5a1464d05..2efdebec5 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java
@@ -21,19 +21,17 @@ import static com.google.common.util.concurrent.Futures.addCallback;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import com.google.common.annotations.GwtCompatible;
-import com.google.common.annotations.GwtIncompatible;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
-import javax.annotation.CheckForNull;
import junit.framework.TestCase;
-import org.mockito.Mockito;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Test for {@link FutureCallback}.
*
* @author Anthony Zana
*/
-@GwtCompatible(emulated = true)
+@GwtCompatible
public class FutureCallbackTest extends TestCase {
public void testSameThreadSuccess() {
SettableFuture<String> f = SettableFuture.create();
@@ -89,38 +87,60 @@ public class FutureCallbackTest extends TestCase {
addCallback(f, callback, directExecutor());
}
- public void testRuntimeExeceptionFromGet() {
+ public void testRuntimeExceptionFromGet() {
RuntimeException e = new IllegalArgumentException("foo not found");
ListenableFuture<String> f = UncheckedThrowingFuture.throwingRuntimeException(e);
MockCallback callback = new MockCallback(e);
addCallback(f, callback, directExecutor());
}
- @GwtIncompatible // Mockito
public void testOnSuccessThrowsRuntimeException() throws Exception {
RuntimeException exception = new RuntimeException();
String result = "result";
SettableFuture<String> future = SettableFuture.create();
- @SuppressWarnings("unchecked") // Safe for a mock
- FutureCallback<String> callback = Mockito.mock(FutureCallback.class);
+ int[] successCalls = new int[1];
+ int[] failureCalls = new int[1];
+ FutureCallback<String> callback =
+ new FutureCallback<String>() {
+ @Override
+ public void onSuccess(String result) {
+ successCalls[0]++;
+ throw exception;
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ failureCalls[0]++;
+ }
+ };
addCallback(future, callback, directExecutor());
- Mockito.doThrow(exception).when(callback).onSuccess(result);
future.set(result);
assertEquals(result, future.get());
- Mockito.verify(callback).onSuccess(result);
- Mockito.verifyNoMoreInteractions(callback);
+ assertThat(successCalls[0]).isEqualTo(1);
+ assertThat(failureCalls[0]).isEqualTo(0);
}
- @GwtIncompatible // Mockito
public void testOnSuccessThrowsError() throws Exception {
class TestError extends Error {}
TestError error = new TestError();
String result = "result";
SettableFuture<String> future = SettableFuture.create();
- @SuppressWarnings("unchecked") // Safe for a mock
- FutureCallback<String> callback = Mockito.mock(FutureCallback.class);
+ int[] successCalls = new int[1];
+ int[] failureCalls = new int[1];
+ FutureCallback<String> callback =
+ new FutureCallback<String>() {
+ @Override
+ public void onSuccess(String result) {
+ successCalls[0]++;
+ throw error;
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ failureCalls[0]++;
+ }
+ };
addCallback(future, callback, directExecutor());
- Mockito.doThrow(error).when(callback).onSuccess(result);
try {
future.set(result);
fail("Should have thrown");
@@ -128,8 +148,8 @@ public class FutureCallbackTest extends TestCase {
assertSame(error, e);
}
assertEquals(result, future.get());
- Mockito.verify(callback).onSuccess(result);
- Mockito.verifyNoMoreInteractions(callback);
+ assertThat(successCalls[0]).isEqualTo(1);
+ assertThat(failureCalls[0]).isEqualTo(0);
}
public void testWildcardFuture() {
@@ -157,8 +177,8 @@ public class FutureCallbackTest extends TestCase {
}
private final class MockCallback implements FutureCallback<String> {
- @CheckForNull private String value = null;
- @CheckForNull private Throwable failure = null;
+ @Nullable private String value = null;
+ @Nullable private Throwable failure = null;
private boolean wasCalled = false;
MockCallback(String expectedValue) {
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java b/android/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
index 6fa2a32df..c46801b99 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
@@ -88,9 +88,9 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import javax.annotation.CheckForNull;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link Futures}.
@@ -141,7 +141,7 @@ public class FuturesTest extends TestCase {
}
public void testImmediateVoidFuture() throws Exception {
- ListenableFuture<Void> voidFuture = immediateVoidFuture();
+ ListenableFuture<@Nullable Void> voidFuture = immediateVoidFuture();
assertThat(getDone(voidFuture)).isNull();
assertThat(getDoneFromTimeoutOverload(voidFuture)).isNull();
@@ -388,7 +388,7 @@ public class FuturesTest extends TestCase {
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
- throw new AssertionFailedError("Unexpeted call to apply.");
+ throw new AssertionFailedError("Unexpected call to apply.");
}
};
assertTrue(transformAsync(input, function, directExecutor()).cancel(false));
@@ -402,7 +402,7 @@ public class FuturesTest extends TestCase {
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
- throw new AssertionFailedError("Unexpeted call to apply.");
+ throw new AssertionFailedError("Unexpected call to apply.");
}
};
assertTrue(transformAsync(input, function, directExecutor()).cancel(true));
@@ -1662,7 +1662,7 @@ public class FuturesTest extends TestCase {
}
private static <I, O> AsyncFunction<I, O> constantAsyncFunction(
- final ListenableFuture<O> output) {
+ final @Nullable ListenableFuture<O> output) {
return new AsyncFunction<I, O>() {
@Override
public ListenableFuture<O> apply(I input) {
@@ -1978,7 +1978,7 @@ public class FuturesTest extends TestCase {
pendingRunnables.add(runnable);
}
};
- ListenableFuture<Void> future = submit(runnable, executor);
+ ListenableFuture<@Nullable Void> future = submit(runnable, executor);
assertThat(future.isDone()).isFalse();
assertThat(executedRunnables).isEmpty();
assertThat(pendingRunnables).hasSize(1);
@@ -1997,7 +1997,7 @@ public class FuturesTest extends TestCase {
throw exception;
}
};
- ListenableFuture<Void> future = submit(runnable, directExecutor());
+ ListenableFuture<@Nullable Void> future = submit(runnable, directExecutor());
try {
getDone(future);
fail();
@@ -2110,7 +2110,8 @@ public class FuturesTest extends TestCase {
assertFalse(callableCalled.get());
}
- private static <T> AsyncCallable<T> constantAsyncCallable(final ListenableFuture<T> returnValue) {
+ private static <T> AsyncCallable<T> constantAsyncCallable(
+ final @Nullable ListenableFuture<T> returnValue) {
return new AsyncCallable<T>() {
@Override
public ListenableFuture<T> call() {
@@ -3677,7 +3678,7 @@ public class FuturesTest extends TestCase {
@GwtIncompatible // used only in GwtIncompatible tests
private static class TestException extends Exception {
- TestException(@CheckForNull Throwable cause) {
+ TestException(@Nullable Throwable cause) {
super(cause);
}
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java b/android/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
index adeb2d1aa..9054ea975 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
@@ -32,6 +32,7 @@ import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Generated tests for {@link Monitor}.
@@ -435,7 +436,11 @@ public class GeneratedMonitorTest extends TestCase {
private final CountDownLatch callCompletedLatch;
private GeneratedMonitorTest(
- Method method, Scenario scenario, boolean fair, Timeout timeout, Outcome expectedOutcome) {
+ Method method,
+ Scenario scenario,
+ boolean fair,
+ @Nullable Timeout timeout,
+ Outcome expectedOutcome) {
super(nameFor(method, scenario, fair, timeout, expectedOutcome));
this.method = method;
this.scenario = scenario;
@@ -469,7 +474,7 @@ public class GeneratedMonitorTest extends TestCase {
runChosenTest();
}
};
- final FutureTask<Void> task = new FutureTask<>(runChosenTest, null);
+ final FutureTask<@Nullable Void> task = new FutureTask<>(runChosenTest, null);
startThread(
new Runnable() {
@Override
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java b/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java
index fcfe744e0..6d1591354 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java
@@ -17,13 +17,13 @@ package com.google.common.util.concurrent;
import static com.google.common.truth.Truth.assertThat;
-import java.lang.reflect.Method;
+import com.google.common.util.concurrent.InterruptibleTask.Blocker;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.AbstractOwnableSynchronizer;
import java.util.concurrent.locks.LockSupport;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
public final class InterruptibleTaskTest extends TestCase {
@@ -31,10 +31,10 @@ public final class InterruptibleTaskTest extends TestCase {
// transition to DONE
public void testInterruptThrows() throws Exception {
final CountDownLatch isInterruptibleRegistered = new CountDownLatch(1);
- InterruptibleTask<Void> task =
- new InterruptibleTask<Void>() {
+ InterruptibleTask<@Nullable Void> task =
+ new InterruptibleTask<@Nullable Void>() {
@Override
- Void runInterruptibly() throws Exception {
+ @Nullable Void runInterruptibly() throws Exception {
BrokenChannel bc = new BrokenChannel();
bc.doBegin();
isInterruptibleRegistered.countDown();
@@ -53,7 +53,7 @@ public final class InterruptibleTaskTest extends TestCase {
}
@Override
- void afterRanInterruptiblySuccess(Void result) {}
+ void afterRanInterruptiblySuccess(@Nullable Void result) {}
@Override
void afterRanInterruptiblyFailure(Throwable error) {}
@@ -101,10 +101,10 @@ public final class InterruptibleTaskTest extends TestCase {
public void testInterruptIsSlow() throws Exception {
final CountDownLatch isInterruptibleRegistered = new CountDownLatch(1);
final SlowChannel slowChannel = new SlowChannel();
- final InterruptibleTask<Void> task =
- new InterruptibleTask<Void>() {
+ final InterruptibleTask<@Nullable Void> task =
+ new InterruptibleTask<@Nullable Void>() {
@Override
- Void runInterruptibly() throws Exception {
+ @Nullable Void runInterruptibly() throws Exception {
slowChannel.doBegin();
isInterruptibleRegistered.countDown();
try {
@@ -127,7 +127,7 @@ public final class InterruptibleTaskTest extends TestCase {
}
@Override
- void afterRanInterruptiblySuccess(Void result) {}
+ void afterRanInterruptiblySuccess(@Nullable Void result) {}
@Override
void afterRanInterruptiblyFailure(Throwable error) {}
@@ -152,12 +152,8 @@ public final class InterruptibleTaskTest extends TestCase {
// waiting for the slow interrupting thread to complete Thread.interrupt
awaitBlockedOnInstanceOf(runner, InterruptibleTask.Blocker.class);
- Object blocker = LockSupport.getBlocker(runner);
- assertThat(blocker).isInstanceOf(AbstractOwnableSynchronizer.class);
- Method getExclusiveOwnerThread =
- AbstractOwnableSynchronizer.class.getDeclaredMethod("getExclusiveOwnerThread");
- getExclusiveOwnerThread.setAccessible(true);
- Thread owner = (Thread) getExclusiveOwnerThread.invoke(blocker);
+ Blocker blocker = (Blocker) LockSupport.getBlocker(runner);
+ Thread owner = blocker.getOwner();
assertThat(owner).isSameInstanceAs(interrupter);
slowChannel.exitClose.countDown(); // release the interrupter
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java
new file mode 100644
index 000000000..5c12696ab
--- /dev/null
+++ b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 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.util.concurrent;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Future;
+import junit.framework.TestCase;
+
+/** Test for {@link ListenableFuture}. */
+public class ListenableFutureTest extends TestCase {
+ public void testNoNewApis() throws Exception {
+ assertWithMessage(
+ "Do not add new methods to ListenableFuture. Its API needs to continue to match the"
+ + " version we released in a separate artifact com.google.guava:listenablefuture.")
+ .that(ListenableFuture.class.getDeclaredMethods())
+ .asList()
+ .containsExactly(
+ ListenableFuture.class.getMethod("addListener", Runnable.class, Executor.class));
+ assertWithMessage(
+ "Do not add new supertypes to ListenableFuture. Its API needs to continue to match the"
+ + " version we released in a separate artifact com.google.guava:listenablefuture.")
+ .that(ListenableFuture.class.getInterfaces())
+ .asList()
+ .containsExactly(Future.class);
+ }
+}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
index 575ed0656..5c99bc881 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
@@ -29,7 +29,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Used to test listenable future implementations.
@@ -67,7 +67,7 @@ public class ListenableFutureTester {
exec.shutdown();
}
- public void testCompletedFuture(@CheckForNull Object expectedValue)
+ public void testCompletedFuture(@Nullable Object expectedValue)
throws InterruptedException, ExecutionException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
@@ -94,7 +94,7 @@ public class ListenableFutureTester {
}
}
- public void testFailedFuture(@CheckForNull String message) throws InterruptedException {
+ public void testFailedFuture(@Nullable String message) throws InterruptedException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java b/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
index aac61735e..dab6d92f9 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
@@ -72,6 +72,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -185,9 +186,9 @@ public class MoreExecutorsTest extends JSR166TestCase {
try {
Future<?> future =
executor.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
// WAIT #1
barrier.await(1, TimeUnit.SECONDS);
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java b/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
index 40713545b..a2773ba64 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
@@ -35,7 +35,6 @@ import java.util.Locale;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
-import org.easymock.EasyMock;
import org.mockito.Mockito;
/**
@@ -564,24 +563,9 @@ public class RateLimiterTest extends TestCase {
}
}
- /*
- * Note: Mockito appears to lose its ability to Mock doGetRate as of Android 21. If we start
- * testing with that version or newer, we'll need to suppress this test (or see if Mockito can be
- * changed to support this).
- */
+ @AndroidIncompatible // Mockito loses its ability to mock doGetRate as of Android 21
public void testMockingMockito() throws Exception {
RateLimiter mock = Mockito.mock(RateLimiter.class);
- doTestMocking(mock);
- }
-
- @AndroidIncompatible // EasyMock Class Extension doesn't appear to work on Android.
- public void testMockingEasyMock() throws Exception {
- RateLimiter mock = EasyMock.createNiceMock(RateLimiter.class);
- EasyMock.replay(mock);
- doTestMocking(mock);
- }
-
- private static void doTestMocking(RateLimiter mock) throws Exception {
for (Method method : RateLimiter.class.getMethods()) {
if (!isStatic(method.getModifiers())
&& !NOT_WORKING_ON_MOCKS.contains(method.getName())
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java b/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
index 80e7ab2e1..cbb6c1c82 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
@@ -310,7 +310,7 @@ public class SequentialExecutorTest extends TestCase {
executor.execute(errorTask);
service.execute(barrierTask); // submit directly to the service
// the barrier task runs after the error task so we know that the error has been observed by
- // SequentialExecutor by the time the barrier is satified
+ // SequentialExecutor by the time the barrier is satisfied
barrier.await(1, TimeUnit.SECONDS);
executor.execute(barrierTask);
// timeout means the second task wasn't even tried
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java
index 7db6b06ae..958be1972 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java
@@ -492,7 +492,7 @@ public class ServiceManagerTest extends TestCase {
}
};
stoppingThread.start();
- // this should be super fast since the only non stopped service is a NoOpService
+ // this should be super fast since the only non-stopped service is a NoOpService
stoppingThread.join(1000);
assertFalse("stopAsync has deadlocked!.", stoppingThread.isAlive());
failLeave.countDown(); // release the background thread
@@ -611,7 +611,7 @@ public class ServiceManagerTest extends TestCase {
}
/**
- * This service will shutdown very quickly after stopAsync is called and uses a background thread
+ * This service will shut down very quickly after stopAsync is called and uses a background thread
* so that we know that the stopping() listeners will execute on a different thread than the
* terminated() listeners.
*/
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java b/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
index 35406864d..37ef84f66 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
@@ -278,7 +278,7 @@ public class SimpleTimeLimiterTest extends TestCase {
finished = true;
return input;
} catch (InterruptedException e) {
- return null;
+ throw new AssertionError();
}
}
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/TestThread.java b/android/guava-tests/test/com/google/common/util/concurrent/TestThread.java
index f85d3134d..ef3b27410 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/TestThread.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/TestThread.java
@@ -28,8 +28,8 @@ import java.lang.reflect.Method;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import javax.annotation.CheckForNull;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A helper for concurrency testing. One or more {@code TestThread} instances are instantiated in a
@@ -58,7 +58,7 @@ public final class TestThread<L> extends Thread implements TearDown {
private final SynchronousQueue<Request> requestQueue = new SynchronousQueue<>();
private final SynchronousQueue<Response> responseQueue = new SynchronousQueue<>();
- private Throwable uncaughtThrowable = null;
+ private @Nullable Throwable uncaughtThrowable = null;
public TestThread(L lockLikeObject, String threadName) {
super(threadName);
@@ -168,7 +168,7 @@ public final class TestThread<L> extends Thread implements TearDown {
* Asserts that a prior call that had caused this thread to block or wait has since returned
* normally.
*/
- public void assertPriorCallReturns(@CheckForNull String methodName) throws Exception {
+ public void assertPriorCallReturns(@Nullable String methodName) throws Exception {
assertEquals(null, getResponse(methodName).getResult());
}
@@ -176,7 +176,7 @@ public final class TestThread<L> extends Thread implements TearDown {
* Asserts that a prior call that had caused this thread to block or wait has since returned the
* expected boolean value.
*/
- public void assertPriorCallReturns(boolean expected, @CheckForNull String methodName)
+ public void assertPriorCallReturns(boolean expected, @Nullable String methodName)
throws Exception {
assertEquals(expected, getResponse(methodName).getResult());
}
@@ -275,7 +275,7 @@ public final class TestThread<L> extends Thread implements TearDown {
final Object result;
final Throwable throwable;
- Response(String methodName, Object result, Throwable throwable) {
+ Response(String methodName, @Nullable Object result, @Nullable Throwable throwable) {
this.methodName = methodName;
this.result = result;
this.throwable = throwable;
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java b/android/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java
index e735ae02a..e58d3eef0 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java
@@ -33,6 +33,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Test case for {@link TrustedListenableFutureTask}. */
@GwtCompatible(emulated = true)
@@ -172,11 +173,11 @@ public class TrustedListenableFutureTaskTest extends TestCase {
public void testToString() throws Exception {
final CountDownLatch enterLatch = new CountDownLatch(1);
final CountDownLatch exitLatch = new CountDownLatch(1);
- final TrustedListenableFutureTask<Void> task =
+ final TrustedListenableFutureTask<@Nullable Void> task =
TrustedListenableFutureTask.create(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
enterLatch.countDown();
new CountDownLatch(1).await(); // wait forever
return null;
@@ -205,7 +206,7 @@ public class TrustedListenableFutureTaskTest extends TestCase {
exitLatch.await();
}
- @GwtIncompatible // used only in GwtIncomaptible tests
+ @GwtIncompatible // used only in GwtIncompatible tests
private void awaitUnchecked(CyclicBarrier barrier) {
try {
barrier.await();
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java
index fdb2c54e6..5cbc7c2b7 100644
--- a/android/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java
+++ b/android/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java
@@ -188,7 +188,7 @@ public class WrappingExecutorServiceTest extends TestCase {
}
}
- // TODO: If this test can ever depend on EasyMock or the like, use it instead.
+ // TODO: If this test can ever depend on Mockito or the like, use it instead.
private static final class MockExecutor implements ExecutorService {
private String lastMethodCalled = "";
private long lastTimeoutInMillis = -1;
diff --git a/android/guava/pom.xml b/android/guava/pom.xml
index 39611d4c9..a01c5a082 100644
--- a/android/guava/pom.xml
+++ b/android/guava/pom.xml
@@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <!-- do_not_remove: published-with-gradle-metadata -->
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-android</version>
+ <version>32.1.2-android</version>
</parent>
<artifactId>guava</artifactId>
<packaging>bundle</packaging>
@@ -47,6 +48,16 @@
<!-- TODO(cpovirk): want this only for dependency plugin but seems not to work there? Maven runs without failure, but the resulting Javadoc is missing the hoped-for inherited text -->
</dependencies>
<build>
+ <resources>
+ <resource>
+ <directory>..</directory>
+ <includes>
+ <include>LICENSE</include> <!-- copied from the parent pom because I couldn't figure out a way to make combine.children="append" work -->
+ <include>proguard/*</include>
+ </includes>
+ <targetPath>META-INF</targetPath>
+ </resource>
+ </resources>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
@@ -62,7 +73,7 @@
<extensions>true</extensions>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <version>2.5.0</version>
+ <version>5.1.8</version>
<executions>
<execution>
<id>bundle-manifest</id>
@@ -187,6 +198,7 @@
<links>
<link>https://errorprone.info/api/latest/</link>
</links>
+ <overview>../../overview.html</overview>
</configuration>
<executions>
<execution>
@@ -199,6 +211,50 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>gradle-module-metadata</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>target/publish</outputDirectory>
+ <resources>
+ <resource>
+ <directory>../../guava</directory>
+ <includes>
+ <include>module.json</include>
+ </includes>
+ <filtering>true</filtering>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-gradle-module-metadata</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>target/publish/module.json</file>
+ <type>module</type>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
<profiles>
diff --git a/android/guava/src/com/google/common/annotations/J2ktIncompatible.java b/android/guava/src/com/google/common/annotations/J2ktIncompatible.java
new file mode 100644
index 000000000..59511632e
--- /dev/null
+++ b/android/guava/src/com/google/common/annotations/J2ktIncompatible.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2009 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.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * The presence of this annotation on an API indicates that the method may <em>not</em> be used with
+ * J2kt.
+ *
+ * @since 32.0.0
+ */
+@Retention(RetentionPolicy.CLASS)
+@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
+@GwtCompatible
+public @interface J2ktIncompatible {}
diff --git a/android/guava/src/com/google/common/annotations/VisibleForTesting.java b/android/guava/src/com/google/common/annotations/VisibleForTesting.java
index e767afcdd..24b4db5bd 100644
--- a/android/guava/src/com/google/common/annotations/VisibleForTesting.java
+++ b/android/guava/src/com/google/common/annotations/VisibleForTesting.java
@@ -22,8 +22,8 @@ package com.google.common.annotations;
* bad design, and it does not prevent anyone from using the declaration---and experience has shown
* that they will. If the method breaks the encapsulation of its class, then its internal
* representation will be hard to change. Instead, use <a
- * href="http://errorprone.info/bugpattern/RestrictedApiChecker">RestrictedApiChecker</a>, which
- * enforces fine-grained visibility policies.
+ * href="http://errorprone.info/bugpattern/RestrictedApi">RestrictedApiChecker</a>, which enforces
+ * fine-grained visibility policies.
*
* @author Johannes Henkel
*/
diff --git a/android/guava/src/com/google/common/annotations/package-info.java b/android/guava/src/com/google/common/annotations/package-info.java
index 9ad041ffe..3cff985b7 100644
--- a/android/guava/src/com/google/common/annotations/package-info.java
+++ b/android/guava/src/com/google/common/annotations/package-info.java
@@ -13,7 +13,7 @@
*/
/**
- * Common annotation types. This package is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Annotation types. This package is a part of the open-source <a
+ * href="https://github.com/google/guava">Guava</a> library.
*/
package com.google.common.annotations;
diff --git a/android/guava/src/com/google/common/base/CaseFormat.java b/android/guava/src/com/google/common/base/CaseFormat.java
index 7b393ebd7..93fa7e4b7 100644
--- a/android/guava/src/com/google/common/base/CaseFormat.java
+++ b/android/guava/src/com/google/common/base/CaseFormat.java
@@ -151,7 +151,8 @@ public enum CaseFormat {
}
/**
- * Returns a {@code Converter} that converts strings from this format to {@code targetFormat}.
+ * Returns a serializable {@code Converter} that converts strings from this format to {@code
+ * targetFormat}.
*
* @since 16.0
*/
diff --git a/android/guava/src/com/google/common/base/CharMatcher.java b/android/guava/src/com/google/common/base/CharMatcher.java
index 2a2a89447..47b4ed2b1 100644
--- a/android/guava/src/com/google/common/base/CharMatcher.java
+++ b/android/guava/src/com/google/common/base/CharMatcher.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkPositionIndex;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.Arrays;
import java.util.BitSet;
@@ -411,6 +412,7 @@ public abstract class CharMatcher implements Predicate<Character> {
* constructs an eight-kilobyte bit array and queries that. In many situations this produces a
* matcher which is faster to query than the original.
*/
+ @J2ktIncompatible
@GwtIncompatible // SmallCharMatcher
CharMatcher precomputedInternal() {
final BitSet table = new BitSet();
@@ -441,6 +443,7 @@ public abstract class CharMatcher implements Predicate<Character> {
/**
* Helper method for {@link #precomputedInternal} that doesn't test if the negation is cheaper.
*/
+ @J2ktIncompatible
@GwtIncompatible // SmallCharMatcher
private static CharMatcher precomputedPositive(
int totalCharacters, BitSet table, String description) {
@@ -460,6 +463,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SmallCharMatcher
private static boolean isSmall(int totalCharacters, int tableLength) {
return totalCharacters <= SmallCharMatcher.MAX_SIZE
@@ -468,6 +472,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
/** Sets bits in {@code table} matched by this matcher. */
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
void setBits(BitSet table) {
for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) {
@@ -978,6 +983,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
/** Fast matcher using a {@link BitSet} table of matching characters. */
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
private static final class BitSetMatcher extends NamedFastMatcher {
@@ -1232,6 +1238,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return TABLE.charAt((MULTIPLIER * c) >>> SHIFT) == c;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1518,6 +1525,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return sequence.length() - original.countIn(sequence);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1554,6 +1562,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return first.matches(c) && second.matches(c);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1582,6 +1591,7 @@ public abstract class CharMatcher implements Predicate<Character> {
second = checkNotNull(b);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1636,6 +1646,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return isNot(match);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1672,6 +1683,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return other.matches(match) ? any() : this;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1710,6 +1722,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return c == match1 || c == match2;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1739,6 +1752,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
@Override
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
void setBits(BitSet table) {
for (char c : chars) {
@@ -1774,6 +1788,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return startInclusive <= c && c <= endInclusive;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
diff --git a/android/guava/src/com/google/common/base/Charsets.java b/android/guava/src/com/google/common/base/Charsets.java
index 7aebea826..538e604f2 100644
--- a/android/guava/src/com/google/common/base/Charsets.java
+++ b/android/guava/src/com/google/common/base/Charsets.java
@@ -16,6 +16,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.charset.Charset;
/**
@@ -42,6 +43,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#US_ASCII} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset US_ASCII = Charset.forName("US-ASCII");
@@ -70,6 +72,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#UTF_16BE} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
@@ -80,6 +83,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#UTF_16LE} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
@@ -91,6 +95,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#UTF_16} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset UTF_16 = Charset.forName("UTF-16");
diff --git a/android/guava/src/com/google/common/base/Converter.java b/android/guava/src/com/google/common/base/Converter.java
index 422480d16..63f4394f4 100644
--- a/android/guava/src/com/google/common/base/Converter.java
+++ b/android/guava/src/com/google/common/base/Converter.java
@@ -18,7 +18,6 @@ import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.ForOverride;
import com.google.errorprone.annotations.InlineMe;
@@ -191,7 +190,6 @@ public abstract class Converter<A, B> implements Function<A, B> {
*
* @return the converted value; is null <i>if and only if</i> {@code a} is null
*/
- @CanIgnoreReturnValue
@CheckForNull
public final B convert(@CheckForNull A a) {
return correctedDoForward(a);
@@ -261,7 +259,6 @@ public abstract class Converter<A, B> implements Function<A, B> {
* a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding
* element.
*/
- @CanIgnoreReturnValue
/*
* Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A,
* B>`, convertAll could accept and return iterables with nullable element types. In both cases,
@@ -286,8 +283,6 @@ public abstract class Converter<A, B> implements Function<A, B> {
}
@Override
- @SuppressWarnings("nullness") // See code comments on convertAll and Converter.apply.
- @CheckForNull
public B next() {
return convert(fromIterator.next());
}
@@ -461,41 +456,26 @@ public abstract class Converter<A, B> implements Function<A, B> {
*/
@Deprecated
@Override
- @CanIgnoreReturnValue
- /*
- * Even though we implement `Function<A, B>` instead of `Function<@Nullable A, @Nullable B>` (as
- * discussed in a code comment at the top of the class), we declare our override of Function.apply
- * to accept and return null. This requires a suppression, but it's safe:
- *
- * - Callers who use Converter as a Function<A, B> will neither pass null nor have it returned to
- * them. (Or, if they're not using nullness checking, they might be able to pass null and thus
- * have null returned to them. But our signature isn't making their existing nullness type error
- * any worse.)
- * - In the relatively unlikely event that anyone calls Converter.apply directly, that caller is
- * allowed to pass null but is also forced to deal with a potentially null return.
- * - Perhaps more important than actual *callers* of this method are various tools that look at
- * bytecode. Notably, NullPointerTester expects a method to throw NPE when passed null unless it
- * is annotated in a way that identifies its parameter type as potentially including null. (And
- * this method does not throw NPE -- nor do we want to enact a dangerous change to make it begin
- * doing so.) We can even imagine tools that rewrite bytecode to insert null checks before and
- * after calling methods with allegedly non-nullable parameters[*]. If we didn't annotate the
- * parameter and return type here, then anyone who used such a tool (and managed to pass null to
- * this method, presumably because that user doesn't run a normal nullness checker) could see
- * NullPointerException.
- *
- * [*] Granted, such tools could conceivably be smart enough to recognize that the apply() method
- * on a a Function<Foo, Bar> should never allow null inputs and never produce null outputs even if
- * this specific subclass claims otherwise. Such tools might still produce NPE for calls to this
- * method. And that is one reason that we should be nervous about "lying" by extending Function<A,
- * B> in the first place. But for now, we're giving it a try, since extending Function<@Nullable
- * A, @Nullable B> will cause issues *today*, whereas extending Function<A, B> causes problems in
- * various hypothetical futures. (Plus, a tool that were that smart would likely already introduce
- * problems with LegacyConverter.)
- */
- @SuppressWarnings("nullness")
- @CheckForNull
@InlineMe(replacement = "this.convert(a)")
- public final B apply(@CheckForNull A a) {
+ public final B apply(A a) {
+ /*
+ * Given that we declare this method as accepting and returning non-nullable values (because we
+ * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to
+ * perform runtime null checks on the input and output. (That would also make NullPointerTester
+ * happy!) However, since we didn't do that for many years, we're not about to start now.
+ * (Runtime checks could be particularly bad for users of LegacyConverter.)
+ *
+ * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like
+ * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to
+ * perform even a cast, much less a runtime check.
+ *
+ * All that said, don't forget that everyone should call converter.convert() instead of
+ * converter.apply(), anyway. If clients use only converter.convert(), then their nullness
+ * checkers are unlikely to ever look at the annotations on this declaration.
+ *
+ * Historical note: At one point, we'd declared this method as accepting and returning nullable
+ * values. For details on that, see earlier revisions of this file.
+ */
return convert(a);
}
diff --git a/android/guava/src/com/google/common/base/Defaults.java b/android/guava/src/com/google/common/base/Defaults.java
index 5d12343ed..089f4b572 100644
--- a/android/guava/src/com/google/common/base/Defaults.java
+++ b/android/guava/src/com/google/common/base/Defaults.java
@@ -17,6 +17,7 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
@@ -25,6 +26,7 @@ import javax.annotation.CheckForNull;
* @author Ben Yu
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Defaults {
diff --git a/android/guava/src/com/google/common/base/Enums.java b/android/guava/src/com/google/common/base/Enums.java
index 5c55b6594..d1749f016 100644
--- a/android/guava/src/com/google/common/base/Enums.java
+++ b/android/guava/src/com/google/common/base/Enums.java
@@ -16,8 +16,8 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
@@ -33,7 +33,8 @@ import javax.annotation.CheckForNull;
* @author Steve McKay
* @since 9.0
*/
-@GwtCompatible(emulated = true)
+@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class Enums {
@@ -48,7 +49,8 @@ public final class Enums {
*/
@GwtIncompatible // reflection
public static Field getField(Enum<?> enumValue) {
- Class<?> clazz = enumValue.getDeclaringClass();
+ Class<?>
+ clazz = enumValue.getDeclaringClass();
try {
return clazz.getDeclaredField(enumValue.name());
} catch (NoSuchFieldException impossible) {
@@ -98,17 +100,19 @@ public final class Enums {
}
/**
- * Returns a converter that converts between strings and {@code enum} values of type {@code
- * enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The converter
- * will throw an {@code IllegalArgumentException} if the argument is not the name of any enum
- * constant in the specified enum.
+ * Returns a serializable converter that converts between strings and {@code enum} values of type
+ * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The
+ * converter will throw an {@code IllegalArgumentException} if the argument is not the name of any
+ * enum constant in the specified enum.
*
* @since 16.0
*/
+ @GwtIncompatible
public static <T extends Enum<T>> Converter<String, T> stringConverter(Class<T> enumClass) {
return new StringConverter<>(enumClass);
}
+ @GwtIncompatible
private static final class StringConverter<T extends Enum<T>> extends Converter<String, T>
implements Serializable {
diff --git a/android/guava/src/com/google/common/base/Equivalence.java b/android/guava/src/com/google/common/base/Equivalence.java
index 1bf7f9899..d4c9566c0 100644
--- a/android/guava/src/com/google/common/base/Equivalence.java
+++ b/android/guava/src/com/google/common/base/Equivalence.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.ForOverride;
import java.io.Serializable;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -150,46 +151,13 @@ public abstract class Equivalence<T> {
* Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a,
* b)}.
*
+ * <p>The returned object is serializable if both this {@code Equivalence} and {@code reference}
+ * are serializable (including when {@code reference} is null).
+ *
* @since 10.0
*/
public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) {
- /*
- * I'm pretty sure that this warning "makes sense" but doesn't indicate a real problem.
- *
- * Why it "makes sense": If we pass a `@Nullable Foo`, then we should also pass an
- * `Equivalence<? super @Nullable Foo>`. And there's no such thing because Equivalence doesn't
- * permit nullable type arguments.
- *
- * Why there's no real problem: Every Equivalence can handle null.
- *
- * We could work around this by giving Wrapper 2 type parameters. In the terms of this method,
- * that would be both the T parameter (from the class) and the S parameter (from this method).
- * However, such a change would be source-incompatible. (Plus, there's no reason for the S
- * parameter from the user's perspective, so it would be a wart.)
- *
- * We could probably also work around this by making Wrapper non-final and putting the
- * implementation into a subclass with those 2 type parameters. But we like `final`, if only to
- * deter users from using mocking frameworks to construct instances. (And could also complicate
- * serialization, which is discussed more in the next paragraph.)
- *
- * We could probably also work around this by having Wrapper accept an instance of a new
- * WrapperGuts class, which would then be the class that would declare the 2 type parameters.
- * But that would break deserialization of previously serialized Wrapper instances. And while we
- * specifically say not to rely on serialization across Guava versions, users sometimes do. So
- * we'd rather not break them without a good enough reason.
- *
- * (We could work around the serialization problem by writing custom serialization code. But
- * even that helps only the case of serializing with an old version and deserializing with a
- * new, not vice versa -- unless we introduce WrapperGuts and the logic to handle it today, wait
- * until "everyone" has picked up a version of Guava with that code, and *then* change to use
- * WrapperGuts.)
- *
- * Anyway, a suppression isn't really a big deal. But I have tried to do some due diligence on
- * avoiding it :)
- */
- @SuppressWarnings("nullness")
- Wrapper<S> w = new Wrapper<>(this, reference);
- return w;
+ return new Wrapper<>(this, reference);
}
/**
@@ -213,10 +181,19 @@ public abstract class Equivalence<T> {
* @since 10.0
*/
public static final class Wrapper<T extends @Nullable Object> implements Serializable {
- private final Equivalence<? super T> equivalence;
+ /*
+ * Equivalence's type argument is always non-nullable: Equivalence<Number>, never
+ * Equivalence<@Nullable Number>. That can still produce wrappers of various types --
+ * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just
+ * Equivalence<? super T> below, no type could satisfy both that bound and T's own
+ * bound. With this type, they have some overlap: in our example, Equivalence<Number>
+ * and Equivalence<Object>.
+ */
+ private final Equivalence<? super @NonNull T> equivalence;
+
@ParametricNullness private final T reference;
- private Wrapper(Equivalence<? super T> equivalence, @ParametricNullness T reference) {
+ private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) {
this.equivalence = checkNotNull(equivalence);
this.reference = reference;
}
@@ -280,6 +257,8 @@ public abstract class Equivalence<T> {
* <p>Note that this method performs a similar function for equivalences as {@link
* com.google.common.collect.Ordering#lexicographical} does for orderings.
*
+ * <p>The returned object is serializable if this object is serializable.
+ *
* @since 10.0
*/
@GwtCompatible(serializable = true)
diff --git a/android/guava/src/com/google/common/base/FinalizablePhantomReference.java b/android/guava/src/com/google/common/base/FinalizablePhantomReference.java
index 4f9399669..6f76b63f7 100644
--- a/android/guava/src/com/google/common/base/FinalizablePhantomReference.java
+++ b/android/guava/src/com/google/common/base/FinalizablePhantomReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import javax.annotation.CheckForNull;
@@ -29,6 +30,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class FinalizablePhantomReference<T> extends PhantomReference<T>
diff --git a/android/guava/src/com/google/common/base/FinalizableReference.java b/android/guava/src/com/google/common/base/FinalizableReference.java
index 73753c9b3..f538f9dc0 100644
--- a/android/guava/src/com/google/common/base/FinalizableReference.java
+++ b/android/guava/src/com/google/common/base/FinalizableReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
/**
@@ -25,6 +26,7 @@ import com.google.errorprone.annotations.DoNotMock;
* @since 2.0
*/
@DoNotMock("Use an instance of one of the Finalizable*Reference classes")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface FinalizableReference {
diff --git a/android/guava/src/com/google/common/base/FinalizableReferenceQueue.java b/android/guava/src/com/google/common/base/FinalizableReferenceQueue.java
index 7447b8051..7f1afbb39 100644
--- a/android/guava/src/com/google/common/base/FinalizableReferenceQueue.java
+++ b/android/guava/src/com/google/common/base/FinalizableReferenceQueue.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.FileNotFoundException;
@@ -88,6 +89,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class FinalizableReferenceQueue implements Closeable {
diff --git a/android/guava/src/com/google/common/base/FinalizableSoftReference.java b/android/guava/src/com/google/common/base/FinalizableSoftReference.java
index c0e9b6bae..f4b7c8005 100644
--- a/android/guava/src/com/google/common/base/FinalizableSoftReference.java
+++ b/android/guava/src/com/google/common/base/FinalizableSoftReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import javax.annotation.CheckForNull;
@@ -27,6 +28,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class FinalizableSoftReference<T> extends SoftReference<T>
diff --git a/android/guava/src/com/google/common/base/FinalizableWeakReference.java b/android/guava/src/com/google/common/base/FinalizableWeakReference.java
index 9cca92ed5..12c8dfbfc 100644
--- a/android/guava/src/com/google/common/base/FinalizableWeakReference.java
+++ b/android/guava/src/com/google/common/base/FinalizableWeakReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import javax.annotation.CheckForNull;
@@ -27,6 +28,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class FinalizableWeakReference<T> extends WeakReference<T>
diff --git a/android/guava/src/com/google/common/base/Function.java b/android/guava/src/com/google/common/base/Function.java
index 7d633af21..bbc185dc8 100644
--- a/android/guava/src/com/google/common/base/Function.java
+++ b/android/guava/src/com/google/common/base/Function.java
@@ -15,7 +15,6 @@
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -61,7 +60,6 @@ public interface Function<F extends @Nullable Object, T extends @Nullable Object
* @throws NullPointerException if {@code input} is null and this function does not accept null
* arguments
*/
- @CanIgnoreReturnValue // TODO(kevinb): remove this
@ParametricNullness
T apply(@ParametricNullness F input);
diff --git a/android/guava/src/com/google/common/base/FunctionalEquivalence.java b/android/guava/src/com/google/common/base/FunctionalEquivalence.java
index 4383f4f36..1cd8c416d 100644
--- a/android/guava/src/com/google/common/base/FunctionalEquivalence.java
+++ b/android/guava/src/com/google/common/base/FunctionalEquivalence.java
@@ -16,7 +16,6 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
@@ -28,7 +27,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Bob Lee
* @since 10.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
final class FunctionalEquivalence<F, T> extends Equivalence<F> implements Serializable {
diff --git a/android/guava/src/com/google/common/base/Functions.java b/android/guava/src/com/google/common/base/Functions.java
index 78785047e..c0091ff7f 100644
--- a/android/guava/src/com/google/common/base/Functions.java
+++ b/android/guava/src/com/google/common/base/Functions.java
@@ -79,7 +79,12 @@ public final class Functions {
}
}
- /** Returns the identity function. */
+ /**
+ * Returns the identity function.
+ *
+ * <p><b>Discouraged:</b> Prefer using a lambda like {@code v -> v}, which is shorter and often
+ * more readable.
+ */
// implementation is "fully variant"; E has become a "pass-through" type
@SuppressWarnings("unchecked")
public static <E extends @Nullable Object> Function<E, E> identity() {
diff --git a/android/guava/src/com/google/common/base/Java8Compatibility.java b/android/guava/src/com/google/common/base/Java8Compatibility.java
index edc8b73bd..2dfbd6b1c 100644
--- a/android/guava/src/com/google/common/base/Java8Compatibility.java
+++ b/android/guava/src/com/google/common/base/Java8Compatibility.java
@@ -15,12 +15,14 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.Buffer;
/**
* Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
* https://github.com/google/guava/issues/3990
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
diff --git a/android/guava/src/com/google/common/base/JdkPattern.java b/android/guava/src/com/google/common/base/JdkPattern.java
index 4788398b7..a259d0061 100644
--- a/android/guava/src/com/google/common/base/JdkPattern.java
+++ b/android/guava/src/com/google/common/base/JdkPattern.java
@@ -15,12 +15,14 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** A regex pattern implementation which is backed by the {@link Pattern}. */
@ElementTypesAreNonnullByDefault
+@J2ktIncompatible
@GwtIncompatible
final class JdkPattern extends CommonPattern implements Serializable {
private final Pattern pattern;
diff --git a/android/guava/src/com/google/common/base/Joiner.java b/android/guava/src/com/google/common/base/Joiner.java
index 8b29f68f8..fe1b40a5e 100644
--- a/android/guava/src/com/google/common/base/Joiner.java
+++ b/android/guava/src/com/google/common/base/Joiner.java
@@ -17,7 +17,6 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -366,7 +365,6 @@ public class Joiner {
*
* @since 10.0
*/
- @Beta
@CanIgnoreReturnValue
public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)
throws IOException {
@@ -379,7 +377,6 @@ public class Joiner {
*
* @since 11.0
*/
- @Beta
@CanIgnoreReturnValue
public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)
throws IOException {
@@ -407,7 +404,6 @@ public class Joiner {
*
* @since 10.0
*/
- @Beta
@CanIgnoreReturnValue
public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {
return appendTo(builder, entries.iterator());
@@ -420,7 +416,6 @@ public class Joiner {
*
* @since 11.0
*/
- @Beta
@CanIgnoreReturnValue
public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {
try {
@@ -445,7 +440,6 @@ public class Joiner {
*
* @since 10.0
*/
- @Beta
public String join(Iterable<? extends Entry<?, ?>> entries) {
return join(entries.iterator());
}
@@ -456,7 +450,6 @@ public class Joiner {
*
* @since 11.0
*/
- @Beta
public String join(Iterator<? extends Entry<?, ?>> entries) {
return appendTo(new StringBuilder(), entries).toString();
}
diff --git a/android/guava/src/com/google/common/base/MoreObjects.java b/android/guava/src/com/google/common/base/MoreObjects.java
index da9762424..033ac3aa9 100644
--- a/android/guava/src/com/google/common/base/MoreObjects.java
+++ b/android/guava/src/com/google/common/base/MoreObjects.java
@@ -58,24 +58,7 @@ public final class MoreObjects {
* @throws NullPointerException if both {@code first} and {@code second} are null
* @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
*/
- /*
- * We annotate firstNonNull in a way that protects against NullPointerException at the cost of
- * forbidding some reasonable calls.
- *
- * The more permissive signature would be to accept (@CheckForNull T first, @CheckForNull T
- * second), since it's OK for `second` to be null as long as `first` is not also null. But we
- * expect for that flexibility to be useful relatively rarely: The more common use case is to
- * supply a clearly non-null default, like `firstNonNull(someString, "")`. And users who really
- * know that `first` is guaranteed non-null when `second` is null can write the logic out
- * longhand, including a requireNonNull call, which calls attention to the fact that the static
- * analyzer can't prove that the operation is safe.
- *
- * This matches the signature we currently have for requireNonNullElse in our own checker. (And
- * that in turn matches that method's signature under the Checker Framework.) As always, we could
- * consider the more flexible signature if we judge it worth the risks. If we do, we would likely
- * update both methods so that they continue to match.
- */
- public static <T> T firstNonNull(@CheckForNull T first, T second) {
+ public static <T> T firstNonNull(@CheckForNull T first, @CheckForNull T second) {
if (first != null) {
return first;
}
@@ -346,7 +329,7 @@ public final class MoreObjects {
}
private static boolean isEmpty(Object value) {
- // Put types estimated to be most frequent first.
+ // Put types estimated to be the most frequent first.
if (value instanceof CharSequence) {
return ((CharSequence) value).length() == 0;
} else if (value instanceof Collection) {
@@ -408,12 +391,14 @@ public final class MoreObjects {
return valueHolder;
}
+ @CanIgnoreReturnValue
private ToStringHelper addHolder(@CheckForNull Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
+ @CanIgnoreReturnValue
private ToStringHelper addHolder(String name, @CheckForNull Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
@@ -427,12 +412,14 @@ public final class MoreObjects {
return valueHolder;
}
+ @CanIgnoreReturnValue
private ToStringHelper addUnconditionalHolder(Object value) {
UnconditionalValueHolder valueHolder = addUnconditionalHolder();
valueHolder.value = value;
return this;
}
+ @CanIgnoreReturnValue
private ToStringHelper addUnconditionalHolder(String name, Object value) {
UnconditionalValueHolder valueHolder = addUnconditionalHolder();
valueHolder.value = value;
diff --git a/android/guava/src/com/google/common/base/Optional.java b/android/guava/src/com/google/common/base/Optional.java
index a7a0b3d72..6eac98326 100644
--- a/android/guava/src/com/google/common/base/Optional.java
+++ b/android/guava/src/com/google/common/base/Optional.java
@@ -16,7 +16,6 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.io.Serializable;
@@ -52,6 +51,9 @@ import javax.annotation.CheckForNull;
* <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct
* from other programming environments, though it may bear some similarities.
*
+ * <p>An instance of this class is serializable if its reference is absent or is a serializable
+ * object.
+ *
* <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional}
* class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot
* share a common supertype). <i>All</i> known differences are listed either here or with the
@@ -197,7 +199,6 @@ public abstract class Optional<T> implements Serializable {
* @throws NullPointerException if this optional's value is absent and the supplier returns {@code
* null}
*/
- @Beta
public abstract T or(Supplier<? extends T> supplier);
/**
@@ -289,7 +290,6 @@ public abstract class Optional<T> implements Serializable {
*
* @since 11.0 (generics widened in 13.0)
*/
- @Beta
public static <T> Iterable<T> presentInstances(
final Iterable<? extends Optional<? extends T>> optionals) {
checkNotNull(optionals);
diff --git a/android/guava/src/com/google/common/base/PairwiseEquivalence.java b/android/guava/src/com/google/common/base/PairwiseEquivalence.java
index 74be27fd7..ea40518c5 100644
--- a/android/guava/src/com/google/common/base/PairwiseEquivalence.java
+++ b/android/guava/src/com/google/common/base/PairwiseEquivalence.java
@@ -56,7 +56,8 @@ final class PairwiseEquivalence<E, T extends @Nullable E> extends Equivalence<It
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof PairwiseEquivalence) {
- PairwiseEquivalence<?, ?> that = (PairwiseEquivalence<?, ?>) object;
+ @SuppressWarnings("unchecked")
+ PairwiseEquivalence<Object, Object> that = (PairwiseEquivalence<Object, Object>) object;
return this.elementEquivalence.equals(that.elementEquivalence);
}
diff --git a/android/guava/src/com/google/common/base/ParametricNullness.java b/android/guava/src/com/google/common/base/ParametricNullness.java
index 5b595adb3..0bcc65dc2 100644
--- a/android/guava/src/com/google/common/base/ParametricNullness.java
+++ b/android/guava/src/com/google/common/base/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/base/PatternCompiler.java b/android/guava/src/com/google/common/base/PatternCompiler.java
index 72a45faae..6a7b620b2 100644
--- a/android/guava/src/com/google/common/base/PatternCompiler.java
+++ b/android/guava/src/com/google/common/base/PatternCompiler.java
@@ -15,12 +15,14 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
/**
* Pluggable interface for compiling a regex pattern. By default this package uses the {@code
* java.util.regex} library, but an alternate implementation can be supplied using the {@link
* java.util.ServiceLoader} mechanism.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
interface PatternCompiler {
diff --git a/android/guava/src/com/google/common/base/Platform.java b/android/guava/src/com/google/common/base/Platform.java
index 703b8605b..e5719cc80 100644
--- a/android/guava/src/com/google/common/base/Platform.java
+++ b/android/guava/src/com/google/common/base/Platform.java
@@ -36,12 +36,6 @@ final class Platform {
private Platform() {}
- /** Calls {@link System#nanoTime()}. */
- @SuppressWarnings("GoodTime") // reading system time without TimeSource
- static long systemNanoTime() {
- return System.nanoTime();
- }
-
static CharMatcher precomputeCharMatcher(CharMatcher matcher) {
return matcher.precomputedInternal();
}
@@ -113,6 +107,4 @@ final class Platform {
return true;
}
}
-
- static void checkGwtRpcEnabled() {}
}
diff --git a/android/guava/src/com/google/common/base/Preconditions.java b/android/guava/src/com/google/common/base/Preconditions.java
index 13ff77b7f..1e9ac39cb 100644
--- a/android/guava/src/com/google/common/base/Preconditions.java
+++ b/android/guava/src/com/google/common/base/Preconditions.java
@@ -118,8 +118,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public final class Preconditions {
private Preconditions() {}
- // TODO(cpovirk): Standardize parameter names (expression vs. b, reference vs. obj).
-
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
@@ -175,8 +173,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1) {
- if (!b) {
+ public static void checkArgument(boolean expression, String errorMessageTemplate, char p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -188,8 +186,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1) {
- if (!b) {
+ public static void checkArgument(boolean expression, String errorMessageTemplate, int p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -201,8 +199,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1) {
- if (!b) {
+ public static void checkArgument(boolean expression, String errorMessageTemplate, long p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -215,8 +213,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -228,8 +226,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1, char p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, char p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -241,8 +240,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1, int p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, char p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -254,8 +254,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1, long p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, char p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -268,8 +269,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -281,8 +282,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1, char p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, int p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -294,8 +296,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1, int p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, int p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -307,8 +310,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1, long p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, int p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -321,8 +325,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -334,8 +338,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1, char p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, long p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -347,8 +352,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1, int p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, long p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -360,8 +366,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1, long p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, long p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -374,8 +381,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -388,8 +395,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -402,8 +409,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -416,8 +423,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -430,8 +437,11 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression,
+ String errorMessageTemplate,
+ @CheckForNull Object p1,
+ @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -444,12 +454,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3) {
- if (!b) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
@@ -462,13 +472,13 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3,
@CheckForNull Object p4) {
- if (!b) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
}
@@ -522,7 +532,7 @@ public final class Preconditions {
boolean expression,
/*
* TODO(cpovirk): Consider removing @CheckForNull here, as we've done with the other methods'
- * errorMessageTemplate parameters: It it unlikely that callers intend for their string
+ * errorMessageTemplate parameters: It is unlikely that callers intend for their string
* template to be null (though we do handle that case gracefully at runtime). I've left this
* one as it is because one of our users has defined a wrapper API around Preconditions,
* declaring a checkState method that accepts a possibly null template. So we'd need to update
@@ -543,8 +553,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -557,8 +567,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -571,8 +581,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -585,8 +595,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, @CheckForNull Object p1) {
- if (!b) {
+ public static void checkState(
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -599,8 +610,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1, char p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -613,8 +624,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1, int p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -627,8 +638,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1, long p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -642,8 +653,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -656,8 +667,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1, char p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -670,8 +681,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1, int p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -684,8 +695,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1, long p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -699,8 +710,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -713,8 +724,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1, char p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -727,8 +738,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1, int p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -741,8 +752,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1, long p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -756,8 +767,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -771,8 +782,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -786,8 +797,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -801,8 +812,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -816,8 +827,11 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression,
+ String errorMessageTemplate,
+ @CheckForNull Object p1,
+ @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -831,12 +845,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3) {
- if (!b) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
@@ -850,13 +864,13 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3,
@CheckForNull Object p4) {
- if (!b) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
}
@@ -943,11 +957,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
- public static <T> T checkNotNull(@CheckForNull T obj, String errorMessageTemplate, char p1) {
- if (obj == null) {
+ public static <T> T checkNotNull(
+ @CheckForNull T reference, String errorMessageTemplate, char p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -958,11 +973,11 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
- public static <T> T checkNotNull(@CheckForNull T obj, String errorMessageTemplate, int p1) {
- if (obj == null) {
+ public static <T> T checkNotNull(@CheckForNull T reference, String errorMessageTemplate, int p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -973,11 +988,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
- public static <T> T checkNotNull(@CheckForNull T obj, String errorMessageTemplate, long p1) {
- if (obj == null) {
+ public static <T> T checkNotNull(
+ @CheckForNull T reference, String errorMessageTemplate, long p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -989,11 +1005,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -1005,11 +1021,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1021,11 +1037,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1037,11 +1053,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1053,11 +1069,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1069,11 +1085,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1085,11 +1101,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1101,11 +1117,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1117,11 +1133,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1133,11 +1149,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1149,11 +1165,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1165,11 +1181,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1181,11 +1197,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1197,11 +1213,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1213,11 +1229,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1229,11 +1245,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1245,14 +1261,14 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj,
+ @CheckForNull T reference,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2) {
- if (obj == null) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1264,15 +1280,15 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj,
+ @CheckForNull T reference,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3) {
- if (obj == null) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
- return obj;
+ return reference;
}
/**
@@ -1284,16 +1300,16 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj,
+ @CheckForNull T reference,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3,
@CheckForNull Object p4) {
- if (obj == null) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
- return obj;
+ return reference;
}
/*
diff --git a/android/guava/src/com/google/common/base/Predicate.java b/android/guava/src/com/google/common/base/Predicate.java
index 35d57a601..983b24307 100644
--- a/android/guava/src/com/google/common/base/Predicate.java
+++ b/android/guava/src/com/google/common/base/Predicate.java
@@ -15,7 +15,6 @@
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -63,7 +62,6 @@ public interface Predicate<T extends @Nullable Object> {
* @throws NullPointerException if {@code input} is null and this predicate does not accept null
* arguments
*/
- @CanIgnoreReturnValue
boolean apply(@ParametricNullness T input);
/**
diff --git a/android/guava/src/com/google/common/base/Predicates.java b/android/guava/src/com/google/common/base/Predicates.java
index dc487fc56..30d2ac7dc 100644
--- a/android/guava/src/com/google/common/base/Predicates.java
+++ b/android/guava/src/com/google/common/base/Predicates.java
@@ -16,9 +16,9 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
@@ -195,8 +195,8 @@ public final class Predicates {
*
* @since 20.0 (since 10.0 under the incorrect name {@code assignableFrom})
*/
+ @J2ktIncompatible
@GwtIncompatible // Class.isAssignableFrom
- @Beta
public static Predicate<Class<?>> subtypeOf(Class<?> clazz) {
return new SubtypeOfPredicate(clazz);
}
@@ -235,6 +235,7 @@ public final class Predicates {
* @throws IllegalArgumentException if the pattern is invalid
* @since 3.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Only used by other GWT-incompatible code.
public static Predicate<CharSequence> containsPattern(String pattern) {
return new ContainsPatternFromStringPredicate(pattern);
@@ -247,6 +248,7 @@ public final class Predicates {
*
* @since 3.0
*/
+ @J2ktIncompatible
@GwtIncompatible(value = "java.util.regex.Pattern")
public static Predicate<CharSequence> contains(Pattern pattern) {
return new ContainsPatternPredicate(new JdkPattern(pattern));
@@ -486,7 +488,9 @@ public final class Predicates {
}
}
- /** @see Predicates#instanceOf(Class) */
+ /**
+ * @see Predicates#instanceOf(Class)
+ */
@GwtIncompatible // Class.isInstance
private static class InstanceOfPredicate<T extends @Nullable Object>
implements Predicate<T>, Serializable {
@@ -520,10 +524,13 @@ public final class Predicates {
return "Predicates.instanceOf(" + clazz.getName() + ")";
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
- /** @see Predicates#subtypeOf(Class) */
+ /**
+ * @see Predicates#subtypeOf(Class)
+ */
+ @J2ktIncompatible
@GwtIncompatible // Class.isAssignableFrom
private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable {
private final Class<?> clazz;
@@ -638,7 +645,10 @@ public final class Predicates {
private static final long serialVersionUID = 0;
}
- /** @see Predicates#contains(Pattern) */
+ /**
+ * @see Predicates#contains(Pattern)
+ */
+ @J2ktIncompatible
@GwtIncompatible // Only used by other GWT-incompatible code.
private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable {
final CommonPattern pattern;
@@ -686,7 +696,10 @@ public final class Predicates {
private static final long serialVersionUID = 0;
}
- /** @see Predicates#containsPattern(String) */
+ /**
+ * @see Predicates#containsPattern(String)
+ */
+ @J2ktIncompatible
@GwtIncompatible // Only used by other GWT-incompatible code.
private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate {
diff --git a/android/guava/src/com/google/common/base/SmallCharMatcher.java b/android/guava/src/com/google/common/base/SmallCharMatcher.java
index f0e801b67..816825641 100644
--- a/android/guava/src/com/google/common/base/SmallCharMatcher.java
+++ b/android/guava/src/com/google/common/base/SmallCharMatcher.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.NamedFastMatcher;
import java.util.BitSet;
@@ -25,6 +26,7 @@ import java.util.BitSet;
*
* @author Christopher Swenson
*/
+@J2ktIncompatible
@GwtIncompatible // no precomputation is done in GWT
@ElementTypesAreNonnullByDefault
final class SmallCharMatcher extends NamedFastMatcher {
diff --git a/android/guava/src/com/google/common/base/Splitter.java b/android/guava/src/com/google/common/base/Splitter.java
index bde2e0ec4..7630ecae1 100644
--- a/android/guava/src/com/google/common/base/Splitter.java
+++ b/android/guava/src/com/google/common/base/Splitter.java
@@ -17,9 +17,9 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
@@ -212,6 +212,7 @@ public final class Splitter {
* @return a splitter, with default settings, that uses this pattern
* @throws IllegalArgumentException if {@code separatorPattern} matches the empty string
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex
public static Splitter on(Pattern separatorPattern) {
return on(new JdkPattern(separatorPattern));
@@ -255,6 +256,7 @@ public final class Splitter {
* @throws IllegalArgumentException if {@code separatorPattern} matches the empty string or is a
* malformed expression
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex
public static Splitter onPattern(String separatorPattern) {
return on(Platform.compilePattern(separatorPattern));
@@ -429,7 +431,6 @@ public final class Splitter {
*
* @since 10.0
*/
- @Beta
public MapSplitter withKeyValueSeparator(String separator) {
return withKeyValueSeparator(on(separator));
}
@@ -440,7 +441,6 @@ public final class Splitter {
*
* @since 14.0
*/
- @Beta
public MapSplitter withKeyValueSeparator(char separator) {
return withKeyValueSeparator(on(separator));
}
@@ -464,7 +464,6 @@ public final class Splitter {
*
* @since 10.0
*/
- @Beta
public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
return new MapSplitter(this, keyValueSplitter);
}
@@ -477,7 +476,6 @@ public final class Splitter {
*
* @since 10.0
*/
- @Beta
public static final class MapSplitter {
private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry";
private final Splitter outerSplitter;
diff --git a/android/guava/src/com/google/common/base/StandardSystemProperty.java b/android/guava/src/com/google/common/base/StandardSystemProperty.java
index dc29792de..155037761 100644
--- a/android/guava/src/com/google/common/base/StandardSystemProperty.java
+++ b/android/guava/src/com/google/common/base/StandardSystemProperty.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
@@ -23,6 +24,7 @@ import javax.annotation.CheckForNull;
* @author Kurt Alfred Kluever
* @since 15.0
*/
+@J2ktIncompatible
@GwtIncompatible // java.lang.System#getProperty
@ElementTypesAreNonnullByDefault
public enum StandardSystemProperty {
@@ -125,7 +127,7 @@ public enum StandardSystemProperty {
this.key = key;
}
- /** Returns the key used to lookup this system property. */
+ /** Returns the key used to look up this system property. */
public String key() {
return key;
}
diff --git a/android/guava/src/com/google/common/base/Stopwatch.java b/android/guava/src/com/google/common/base/Stopwatch.java
index f76c09861..e68d666d5 100644
--- a/android/guava/src/com/google/common/base/Stopwatch.java
+++ b/android/guava/src/com/google/common/base/Stopwatch.java
@@ -33,12 +33,11 @@ import java.util.concurrent.TimeUnit;
* successive readings of "now" in the same process.
*
* <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like
- * {@link System#currentTimeMillis()}, best represented as an {@link Instant}. Such values
- *
- * <p><i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}),
- * but doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time
- * readings are inherently approximate, routinely affected by periodic clock corrections. Because
- * this class (by default) uses {@link System#nanoTime}, it is unaffected by these changes.
+ * {@link System#currentTimeMillis()}, best represented as an {@link java.time.Instant}. Such values
+ * <i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}), but
+ * doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings
+ * are inherently approximate, routinely affected by periodic clock corrections. Because this class
+ * (by default) uses {@link System#nanoTime}, it is unaffected by these changes.
*
* <p>Use this class instead of direct calls to {@link System#nanoTime} for two reasons:
*
@@ -49,6 +48,12 @@ import java.util.concurrent.TimeUnit;
* performance reasons, without affecting most of your code.
* </ul>
*
+ * <p>The one downside of {@code Stopwatch} relative to {@link System#nanoTime()} is that {@code
+ * Stopwatch} requires object allocation and additional method calls, which can reduce the accuracy
+ * of the elapsed times reported. {@code Stopwatch} is still suitable for logging and metrics where
+ * reasonably accurate values are sufficient. If the uncommon case that you need to maximize
+ * accuracy, use {@code System.nanoTime()} directly instead.
+ *
* <p>Basic usage:
*
* <pre>{@code
diff --git a/android/guava/src/com/google/common/base/Supplier.java b/android/guava/src/com/google/common/base/Supplier.java
index f9e1e34f1..6081af3c3 100644
--- a/android/guava/src/com/google/common/base/Supplier.java
+++ b/android/guava/src/com/google/common/base/Supplier.java
@@ -15,7 +15,6 @@
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -54,7 +53,6 @@ public interface Supplier<T extends @Nullable Object> {
*
* @return an instance of the appropriate type
*/
- @CanIgnoreReturnValue
@ParametricNullness
T get();
}
diff --git a/android/guava/src/com/google/common/base/Suppliers.java b/android/guava/src/com/google/common/base/Suppliers.java
index 6ced905b9..d97bff626 100644
--- a/android/guava/src/com/google/common/base/Suppliers.java
+++ b/android/guava/src/com/google/common/base/Suppliers.java
@@ -17,7 +17,6 @@ package com.google.common.base;
import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
@@ -97,7 +96,7 @@ public final class Suppliers {
* <p>The returned supplier is thread-safe. The delegate's {@code get()} method will be invoked at
* most once unless the underlying {@code get()} throws an exception. The supplier's serialized
* form does not contain the cached value, which will be recalculated when {@code get()} is called
- * on the reserialized instance.
+ * on the deserialized instance.
*
* <p>When the underlying delegate throws an exception then this memoizing supplier will keep
* delegating calls until it returns valid data.
@@ -157,11 +156,15 @@ public final class Suppliers {
@VisibleForTesting
static class NonSerializableMemoizingSupplier<T extends @Nullable Object> implements Supplier<T> {
- @CheckForNull volatile Supplier<T> delegate;
- volatile boolean initialized;
- // "value" does not need to be volatile; visibility piggy-backs
- // on volatile read of "initialized".
- @CheckForNull T value;
+ @SuppressWarnings("UnnecessaryLambda") // Must be a fixed singleton object
+ private static final Supplier<Void> SUCCESSFULLY_COMPUTED =
+ () -> {
+ throw new IllegalStateException(); // Should never get called.
+ };
+
+ private volatile Supplier<T> delegate;
+ // "value" does not need to be volatile; visibility piggy-backs on volatile read of "delegate".
+ @CheckForNull private T value;
NonSerializableMemoizingSupplier(Supplier<T> delegate) {
this.delegate = checkNotNull(delegate);
@@ -169,27 +172,20 @@ public final class Suppliers {
@Override
@ParametricNullness
+ @SuppressWarnings("unchecked") // Cast from Supplier<Void> to Supplier<T> is always valid
public T get() {
- // A 2-field variant of Double Checked Locking.
- if (!initialized) {
+ // Because Supplier is read-heavy, we use the "double-checked locking" pattern.
+ if (delegate != SUCCESSFULLY_COMPUTED) {
synchronized (this) {
- if (!initialized) {
- /*
- * requireNonNull is safe because we read and write `delegate` under synchronization.
- *
- * TODO(cpovirk): To avoid having to check for null, replace `delegate` with a singleton
- * `Supplier` that always throws an exception.
- */
- T t = requireNonNull(delegate).get();
+ if (delegate != SUCCESSFULLY_COMPUTED) {
+ T t = delegate.get();
value = t;
- initialized = true;
- // Release the delegate to GC.
- delegate = null;
+ delegate = (Supplier<T>) SUCCESSFULLY_COMPUTED;
return t;
}
}
}
- // This is safe because we checked `initialized.`
+ // This is safe because we checked `delegate.`
return uncheckedCastNullableTToT(value);
}
@@ -197,7 +193,9 @@ public final class Suppliers {
public String toString() {
Supplier<T> delegate = this.delegate;
return "Suppliers.memoize("
- + (delegate == null ? "<supplier that returned " + value + ">" : delegate)
+ + (delegate == SUCCESSFULLY_COMPUTED
+ ? "<supplier that returned " + value + ">"
+ : delegate)
+ ")";
}
}
@@ -247,6 +245,7 @@ public final class Suppliers {
@Override
@ParametricNullness
+ @SuppressWarnings("GoodTime") // reading system time without TimeSource
public T get() {
// Another variant of Double Checked Locking.
//
@@ -255,7 +254,7 @@ public final class Suppliers {
// the extra memory consumption and indirection are more
// expensive than the extra volatile reads.
long nanos = expirationNanos;
- long now = Platform.systemNanoTime();
+ long now = System.nanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
diff --git a/android/guava/src/com/google/common/base/Throwables.java b/android/guava/src/com/google/common/base/Throwables.java
index e45ce800c..23936897d 100644
--- a/android/guava/src/com/google/common/base/Throwables.java
+++ b/android/guava/src/com/google/common/base/Throwables.java
@@ -21,6 +21,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -69,6 +70,7 @@ public final class Throwables {
*
* @since 20.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Class.cast, Class.isInstance
public static <X extends Throwable> void throwIfInstanceOf(
Throwable throwable, Class<X> declaredType) throws X {
@@ -98,6 +100,7 @@ public final class Throwables {
* null}.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public static <X extends Throwable> void propagateIfInstanceOf(
@CheckForNull Throwable throwable, Class<X> declaredType) throws X {
@@ -154,6 +157,7 @@ public final class Throwables {
* null}.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible
public static void propagateIfPossible(@CheckForNull Throwable throwable) {
if (throwable != null) {
@@ -179,6 +183,7 @@ public final class Throwables {
* @param throwable the Throwable to possibly propagate
* @param declaredType the single checked exception type declared by the calling method
*/
+ @J2ktIncompatible
@GwtIncompatible // propagateIfInstanceOf
public static <X extends Throwable> void propagateIfPossible(
@CheckForNull Throwable throwable, Class<X> declaredType) throws X {
@@ -197,6 +202,7 @@ public final class Throwables {
* @param declaredType1 any checked exception type declared by the calling method
* @param declaredType2 any other checked exception type declared by the calling method
*/
+ @J2ktIncompatible
@GwtIncompatible // propagateIfInstanceOf
public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
@CheckForNull Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
@@ -235,6 +241,7 @@ public final class Throwables {
* {@code Throwables.propagate}</a>.
*/
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible
@Deprecated
public static RuntimeException propagate(Throwable throwable) {
@@ -328,6 +335,7 @@ public final class Throwables {
* ClassCastException}'s cause is {@code throwable}.
* @since 22.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Class.cast(Object)
@CheckForNull
public static <X extends Throwable> X getCauseAs(
@@ -384,6 +392,7 @@ public final class Throwables {
* possible use the {@code java.lang.StackWalker.walk} method introduced in JDK 9.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace
public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
return lazyStackTraceIsLazy()
@@ -400,11 +409,13 @@ public final class Throwables {
* versions.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible // getStackTraceElementMethod
public static boolean lazyStackTraceIsLazy() {
return getStackTraceElementMethod != null && getStackTraceDepthMethod != null;
}
+ @J2ktIncompatible
@GwtIncompatible // invokeAccessibleNonThrowingMethod
private static List<StackTraceElement> jlaStackTrace(Throwable t) {
checkNotNull(t);
@@ -435,6 +446,7 @@ public final class Throwables {
};
}
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
private static Object invokeAccessibleNonThrowingMethod(
Method method, Object receiver, Object... params) {
@@ -448,15 +460,17 @@ public final class Throwables {
}
/** JavaLangAccess class name to load using reflection */
- @GwtIncompatible // not used by GWT emulation
+ @J2ktIncompatible @GwtIncompatible // not used by GWT emulation
private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess";
/** SharedSecrets class name to load using reflection */
+ @J2ktIncompatible
@GwtIncompatible // not used by GWT emulation
@VisibleForTesting
static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets";
/** Access to some fancy internal JVM internals. */
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static final Object jla = getJLA();
@@ -465,6 +479,7 @@ public final class Throwables {
* The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to
* find it when available. When this is null, use the slow way.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod();
@@ -473,6 +488,7 @@ public final class Throwables {
* The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it
* when available. When this is null, use the slow way.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(jla);
@@ -481,6 +497,7 @@ public final class Throwables {
* Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in
* AppEngine, and not present in non-Sun JDKs.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Object getJLA() {
@@ -507,6 +524,7 @@ public final class Throwables {
* Returns the Method that can be used to resolve an individual StackTraceElement, or null if that
* method cannot be found (it is only to be found in fairly recent JDKs).
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Method getGetMethod() {
@@ -516,12 +534,13 @@ public final class Throwables {
/**
* Returns the Method that can be used to return the size of a stack, or null if that method
* cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link
- * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable)} getStackTraceDepth} prior to return it
+ * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable) getStackTraceDepth} prior to return it
* (might fail some JDKs).
*
* <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws
* UnsupportedOperationException</a>.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Method getSizeMethod(Object jla) {
@@ -537,6 +556,7 @@ public final class Throwables {
}
}
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath {
diff --git a/android/guava/src/com/google/common/base/Ticker.java b/android/guava/src/com/google/common/base/Ticker.java
index d898735c0..5b7a48688 100644
--- a/android/guava/src/com/google/common/base/Ticker.java
+++ b/android/guava/src/com/google/common/base/Ticker.java
@@ -48,8 +48,9 @@ public abstract class Ticker {
private static final Ticker SYSTEM_TICKER =
new Ticker() {
@Override
+ @SuppressWarnings("GoodTime") // reading system time without TimeSource
public long read() {
- return Platform.systemNanoTime();
+ return System.nanoTime();
}
};
}
diff --git a/android/guava/src/com/google/common/base/Utf8.java b/android/guava/src/com/google/common/base/Utf8.java
index bb945a35f..f1209bf45 100644
--- a/android/guava/src/com/google/common/base/Utf8.java
+++ b/android/guava/src/com/google/common/base/Utf8.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Character.MAX_SURROGATE;
import static java.lang.Character.MIN_SURROGATE;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
@@ -36,7 +35,6 @@ import com.google.common.annotations.GwtCompatible;
* @author Clément Roux
* @since 16.0
*/
-@Beta
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Utf8 {
diff --git a/android/guava/src/com/google/common/base/package-info.java b/android/guava/src/com/google/common/base/package-info.java
index f2218562e..bfae42674 100644
--- a/android/guava/src/com/google/common/base/package-info.java
+++ b/android/guava/src/com/google/common/base/package-info.java
@@ -15,45 +15,46 @@
/**
* Basic utility libraries and interfaces.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* <h2>Contents</h2>
*
- * <h3>String-related utilities</h3>
+ * The classes in this package that are most commonly useful are:
+ *
+ * <h3>String utilities</h3>
*
* <ul>
- * <li>{@link com.google.common.base.Ascii}
- * <li>{@link com.google.common.base.CaseFormat}
- * <li>{@link com.google.common.base.CharMatcher}
- * <li>{@link com.google.common.base.Charsets}
- * <li>{@link com.google.common.base.Joiner}
- * <li>{@link com.google.common.base.Splitter}
- * <li>{@link com.google.common.base.Strings}
+ * <li>{@link Ascii}
+ * <li>{@link CaseFormat}
+ * <li>{@link CharMatcher}
+ * <li>{@link Splitter}
+ * <li>{@link Strings}
* </ul>
*
* <h3>Function types</h3>
*
* <ul>
- * <li>{@link com.google.common.base.Function}, {@link com.google.common.base.Functions}
- * <li>{@link com.google.common.base.Predicate}, {@link com.google.common.base.Predicates}
- * <li>{@link com.google.common.base.Equivalence}
- * <li>{@link com.google.common.base.Converter}
- * <li>{@link com.google.common.base.Supplier}, {@link com.google.common.base.Suppliers}
+ * <li>{@link Converter}
+ * <li>{@link Equivalence}
* </ul>
*
* <h3>Other</h3>
*
* <ul>
- * <li>{@link com.google.common.base.Defaults}
- * <li>{@link com.google.common.base.Enums}
- * <li>{@link com.google.common.base.Objects}
- * <li>{@link com.google.common.base.Optional}
- * <li>{@link com.google.common.base.Preconditions}
- * <li>{@link com.google.common.base.Stopwatch}
- * <li>{@link com.google.common.base.Throwables}
+ * <li>{@link Enums}
+ * <li>{@link MoreObjects}
+ * <li>{@link Preconditions}
+ * <li>{@link StandardSystemProperty}
+ * <li>{@link Stopwatch}
+ * <li>{@link Throwables}
+ * <li>{@link Verify}
* </ul>
*
+ * <h3>The rest</h3>
+ *
+ * This package also contains some classes with niche use cases (e.g., {@link Utf8} and {@link
+ * Defaults}), as well as a number of classes that have been superseded by additions to the JDK.
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
diff --git a/android/guava/src/com/google/common/cache/AbstractLoadingCache.java b/android/guava/src/com/google/common/cache/AbstractLoadingCache.java
index 489597c51..5081a785b 100644
--- a/android/guava/src/com/google/common/cache/AbstractLoadingCache.java
+++ b/android/guava/src/com/google/common/cache/AbstractLoadingCache.java
@@ -18,6 +18,7 @@ import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.UncheckedExecutionException;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -45,6 +46,7 @@ public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V>
/** Constructor for use by subclasses. */
protected AbstractLoadingCache() {}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
@Override
public V getUnchecked(K key) {
try {
diff --git a/android/guava/src/com/google/common/cache/Cache.java b/android/guava/src/com/google/common/cache/Cache.java
index 1234bb6a3..985f66582 100644
--- a/android/guava/src/com/google/common/cache/Cache.java
+++ b/android/guava/src/com/google/common/cache/Cache.java
@@ -18,7 +18,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
-import com.google.errorprone.annotations.CheckReturnValue;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CompatibleWith;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Map;
@@ -52,6 +52,7 @@ public interface Cache<K, V> {
* @since 11.0
*/
@CheckForNull
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
V getIfPresent(@CompatibleWith("K") Object key);
/**
@@ -100,6 +101,7 @@ public interface Cache<K, V> {
* @throws ExecutionError if an error was thrown while loading the value
* @since 11.0
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
V get(K key, Callable<? extends V> loader) throws ExecutionException;
/**
@@ -150,7 +152,6 @@ public interface Cache<K, V> {
void invalidateAll();
/** Returns the approximate number of entries in this cache. */
- @CheckReturnValue
long size();
/**
@@ -164,7 +165,6 @@ public interface Cache<K, V> {
* all values is returned.
*
*/
- @CheckReturnValue
CacheStats stats();
/**
@@ -180,7 +180,6 @@ public interface Cache<K, V> {
* {@code ConcurrentMap} documentation. They will not function correctly and it is impossible for
* Guava to fix them until Guava is ready to <i>require</i> Java 8 for all users.
*/
- @CheckReturnValue
ConcurrentMap<K, V> asMap();
/**
diff --git a/android/guava/src/com/google/common/cache/CacheBuilder.java b/android/guava/src/com/google/common/cache/CacheBuilder.java
index b690973b2..5d21c5b18 100644
--- a/android/guava/src/com/google/common/cache/CacheBuilder.java
+++ b/android/guava/src/com/google/common/cache/CacheBuilder.java
@@ -29,17 +29,16 @@ import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.cache.LocalCache.Strength;
-import com.google.errorprone.annotations.CheckReturnValue;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ConcurrentModificationException;
import java.util.IdentityHashMap;
import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.checkerframework.checker.nullness.qual.Nullable;
+import javax.annotation.CheckForNull;
/**
* A builder of {@link LoadingCache} and {@link Cache} instances.
@@ -97,7 +96,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* <li>accumulation of cache access statistics
* </ul>
*
- * <p>These features are all optional; caches can be created using all or none of them. By default
+ * <p>These features are all optional; caches can be created using all or none of them. By default,
* cache instances created by {@code CacheBuilder} will not perform any type of eviction.
*
* <p>Usage example:
@@ -131,13 +130,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* });
* }</pre>
*
- * <p>The returned cache is implemented as a hash table with similar performance characteristics to
- * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
- * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
- * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
- * modify the cache after the iterator is created, it is undefined which of these changes, if any,
- * are reflected in that iterator. These iterators never throw {@link
- * ConcurrentModificationException}.
+ * <p>The returned cache implements all optional operations of the {@link LoadingCache} and {@link
+ * Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly consistent
+ * iterators</i>. This means that they are safe for concurrent use, but if other threads modify the
+ * cache after the iterator is created, it is undefined which of these changes, if any, are
+ * reflected in that iterator. These iterators never throw {@link ConcurrentModificationException}.
*
* <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link
* Object#equals equals} method) to determine equality for keys or values. However, if {@link
@@ -145,34 +142,33 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity
* comparisons for values.
*
- * <p>Entries are automatically evicted from the cache when any of {@linkplain #maximumSize(long)
- * maximumSize}, {@linkplain #maximumWeight(long) maximumWeight}, {@linkplain #expireAfterWrite
- * expireAfterWrite}, {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys
- * weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are
- * requested.
+ * <p>Entries are automatically evicted from the cache when any of {@link #maximumSize(long)
+ * maximumSize}, {@link #maximumWeight(long) maximumWeight}, {@link #expireAfterWrite
+ * expireAfterWrite}, {@link #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys},
+ * {@link #weakValues weakValues}, or {@link #softValues softValues} are requested.
*
- * <p>If {@linkplain #maximumSize(long) maximumSize} or {@linkplain #maximumWeight(long)
- * maximumWeight} is requested entries may be evicted on each cache modification.
+ * <p>If {@link #maximumSize(long) maximumSize} or {@link #maximumWeight(long) maximumWeight} is
+ * requested entries may be evicted on each cache modification.
*
- * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or {@linkplain #expireAfterAccess
- * expireAfterAccess} is requested entries may be evicted on each cache modification, on occasional
- * cache accesses, or on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link
- * Cache#size}, but will never be visible to read or write operations.
+ * <p>If {@link #expireAfterWrite expireAfterWrite} or {@link #expireAfterAccess expireAfterAccess}
+ * is requested entries may be evicted on each cache modification, on occasional cache accesses, or
+ * on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link Cache#size}, but will
+ * never be visible to read or write operations.
*
- * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain
- * #softValues softValues} are requested, it is possible for a key or value present in the cache to
- * be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from
- * the cache on each cache modification, on occasional cache accesses, or on calls to {@link
- * Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be visible to
- * read or write operations.
+ * <p>If {@link #weakKeys weakKeys}, {@link #weakValues weakValues}, or {@link #softValues
+ * softValues} are requested, it is possible for a key or value present in the cache to be reclaimed
+ * by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on
+ * each cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}; such
+ * entries may be counted in {@link Cache#size}, but will never be visible to read or write
+ * operations.
*
* <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
* will be performed during write operations, or during occasional read operations in the absence of
* writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
- * calling it should not be necessary with a high throughput cache. Only caches built with
- * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
- * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys}, {@linkplain
- * #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic maintenance.
+ * calling it should not be necessary with a high throughput cache. Only caches built with {@link
+ * #removalListener removalListener}, {@link #expireAfterWrite expireAfterWrite}, {@link
+ * #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys}, {@link #weakValues
+ * weakValues}, or {@link #softValues softValues} perform periodic maintenance.
*
* <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
* retain all the configuration properties of the original cache. Note that the serialized form does
@@ -231,6 +227,18 @@ public final class CacheBuilder<K, V> {
});
static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
+ /*
+ * We avoid using a method reference or lambda here for now:
+ *
+ * - method reference: Inside Google, CacheBuilder is used from the implementation of a custom
+ * ClassLoader that is sometimes used as a system classloader. That's a problem because
+ * method-reference linking tries to look up the system classloader, and it fails because there
+ * isn't one yet.
+ *
+ * - lambda: Outside Google, we got a report of a similar problem in
+ * https://github.com/google/guava/issues/6565
+ */
+ @SuppressWarnings("AnonymousToLambda")
static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
new Supplier<StatsCounter>() {
@Override
@@ -263,7 +271,10 @@ public final class CacheBuilder<K, V> {
}
};
- private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
+ // We use a holder class to delay initialization: https://github.com/google/guava/issues/6566
+ private static final class LoggerHolder {
+ static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
+ }
static final int UNSET_INT = -1;
@@ -273,10 +284,10 @@ public final class CacheBuilder<K, V> {
int concurrencyLevel = UNSET_INT;
long maximumSize = UNSET_INT;
long maximumWeight = UNSET_INT;
- @Nullable Weigher<? super K, ? super V> weigher;
+ @CheckForNull Weigher<? super K, ? super V> weigher;
- @Nullable Strength keyStrength;
- @Nullable Strength valueStrength;
+ @CheckForNull Strength keyStrength;
+ @CheckForNull Strength valueStrength;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long expireAfterWriteNanos = UNSET_INT;
@@ -287,11 +298,11 @@ public final class CacheBuilder<K, V> {
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long refreshNanos = UNSET_INT;
- @Nullable Equivalence<Object> keyEquivalence;
- @Nullable Equivalence<Object> valueEquivalence;
+ @CheckForNull Equivalence<Object> keyEquivalence;
+ @CheckForNull Equivalence<Object> valueEquivalence;
- @Nullable RemovalListener<? super K, ? super V> removalListener;
- @Nullable Ticker ticker;
+ @CheckForNull RemovalListener<? super K, ? super V> removalListener;
+ @CheckForNull Ticker ticker;
Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
@@ -304,7 +315,6 @@ public final class CacheBuilder<K, V> {
* <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on
* the {@link #build} methods allow you to create a cache of any key and value type desired.
*/
- @CheckReturnValue
public static CacheBuilder<Object, Object> newBuilder() {
return new CacheBuilder<>();
}
@@ -315,7 +325,6 @@ public final class CacheBuilder<K, V> {
* @since 12.0
*/
@GwtIncompatible // To be supported
- @CheckReturnValue
public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
return spec.toCacheBuilder().lenientParsing();
}
@@ -328,7 +337,6 @@ public final class CacheBuilder<K, V> {
* @since 12.0
*/
@GwtIncompatible // To be supported
- @CheckReturnValue
public static CacheBuilder<Object, Object> from(String spec) {
return from(CacheBuilderSpec.parse(spec));
}
@@ -339,6 +347,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
CacheBuilder<K, V> lenientParsing() {
strictParsing = false;
return this;
@@ -353,6 +362,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = checkNotNull(equivalence);
@@ -373,6 +383,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
checkState(
valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
@@ -395,6 +406,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalArgumentException if {@code initialCapacity} is negative
* @throws IllegalStateException if an initial capacity was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
checkState(
this.initialCapacity == UNSET_INT,
@@ -440,6 +452,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
checkState(
this.concurrencyLevel == UNSET_INT,
@@ -475,6 +488,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalArgumentException if {@code maximumSize} is negative
* @throws IllegalStateException if a maximum size or weight was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> maximumSize(long maximumSize) {
checkState(
this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
@@ -516,6 +530,7 @@ public final class CacheBuilder<K, V> {
* @since 11.0
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
checkState(
this.maximumWeight == UNSET_INT,
@@ -558,13 +573,14 @@ public final class CacheBuilder<K, V> {
* @since 11.0
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
Weigher<? super K1, ? super V1> weigher) {
checkState(this.weigher == null);
if (strictParsing) {
checkState(
this.maximumSize == UNSET_INT,
- "weigher can not be combined with maximum size",
+ "weigher can not be combined with maximum size (%s provided)",
this.maximumSize);
}
@@ -605,10 +621,12 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if the key strength was already set
*/
@GwtIncompatible // java.lang.ref.WeakReference
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> weakKeys() {
return setKeyStrength(Strength.WEAK);
}
+ @CanIgnoreReturnValue
CacheBuilder<K, V> setKeyStrength(Strength strength) {
checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = checkNotNull(strength);
@@ -637,6 +655,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if the value strength was already set
*/
@GwtIncompatible // java.lang.ref.WeakReference
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> weakValues() {
return setValueStrength(Strength.WEAK);
}
@@ -662,10 +681,12 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if the value strength was already set
*/
@GwtIncompatible // java.lang.ref.SoftReference
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> softValues() {
return setValueStrength(Strength.SOFT);
}
+ @CanIgnoreReturnValue
CacheBuilder<K, V> setValueStrength(Strength strength) {
checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = checkNotNull(strength);
@@ -696,6 +717,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if {@link #expireAfterWrite} was already set
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
checkState(
expireAfterWriteNanos == UNSET_INT,
@@ -736,6 +758,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if {@link #expireAfterAccess} was already set
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
checkState(
expireAfterAccessNanos == UNSET_INT,
@@ -782,6 +805,7 @@ public final class CacheBuilder<K, V> {
*/
@GwtIncompatible // To be supported (synchronously).
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
checkNotNull(unit);
checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
@@ -805,6 +829,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a ticker was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> ticker(Ticker ticker) {
checkState(this.ticker == null);
this.ticker = checkNotNull(ticker);
@@ -825,11 +850,11 @@ public final class CacheBuilder<K, V> {
*
* <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
* reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
- * same instance, but only the returned reference has the correct generic type information so as
- * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in
- * the class documentation above, configuring a builder and building your cache in a single
- * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown
- * by a cache operation at some <i>undefined</i> point in the future.
+ * same instance, but only the returned reference has the correct generic type information to
+ * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the
+ * class documentation above, configuring a builder and building your cache in a single statement.
+ * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache
+ * operation at some <i>undefined</i> point in the future.
*
* <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
* the {@code Cache} user, only logged via a {@link Logger}.
@@ -839,7 +864,6 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a removal listener was already set
*/
- @CheckReturnValue
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
RemovalListener<? super K1, ? super V1> listener) {
checkState(this.removalListener == null);
@@ -867,6 +891,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
* @since 12.0 (previously, stats collection was automatic)
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> recordStats() {
statsCounterSupplier = CACHE_STATS_COUNTER;
return this;
@@ -892,7 +917,6 @@ public final class CacheBuilder<K, V> {
* @param loader the cache loader used to obtain new values
* @return a cache having the requested features
*/
- @CheckReturnValue
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
CacheLoader<? super K1, V1> loader) {
checkWeightWithWeigher();
@@ -911,7 +935,6 @@ public final class CacheBuilder<K, V> {
* @return a cache having the requested features
* @since 11.0
*/
- @CheckReturnValue
public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
checkWeightWithWeigher();
checkNonLoadingCache();
@@ -930,7 +953,8 @@ public final class CacheBuilder<K, V> {
checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
} else {
if (maximumWeight == UNSET_INT) {
- logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
+ LoggerHolder.logger.log(
+ Level.WARNING, "ignoring weigher specified without maximumWeight");
}
}
}
diff --git a/android/guava/src/com/google/common/cache/CacheBuilderSpec.java b/android/guava/src/com/google/common/cache/CacheBuilderSpec.java
index 7757f3bc4..adc55e0c6 100644
--- a/android/guava/src/com/google/common/cache/CacheBuilderSpec.java
+++ b/android/guava/src/com/google/common/cache/CacheBuilderSpec.java
@@ -328,7 +328,7 @@ public final class CacheBuilderSpec {
protected void parseInteger(CacheBuilderSpec spec, int value) {
checkArgument(
spec.initialCapacity == null,
- "initial capacity was already set to ",
+ "initial capacity was already set to %s",
spec.initialCapacity);
spec.initialCapacity = value;
}
@@ -338,9 +338,10 @@ public final class CacheBuilderSpec {
static class MaximumSizeParser extends LongParser {
@Override
protected void parseLong(CacheBuilderSpec spec, long value) {
- checkArgument(spec.maximumSize == null, "maximum size was already set to ", spec.maximumSize);
checkArgument(
- spec.maximumWeight == null, "maximum weight was already set to ", spec.maximumWeight);
+ spec.maximumSize == null, "maximum size was already set to %s", spec.maximumSize);
+ checkArgument(
+ spec.maximumWeight == null, "maximum weight was already set to %s", spec.maximumWeight);
spec.maximumSize = value;
}
}
@@ -350,8 +351,9 @@ public final class CacheBuilderSpec {
@Override
protected void parseLong(CacheBuilderSpec spec, long value) {
checkArgument(
- spec.maximumWeight == null, "maximum weight was already set to ", spec.maximumWeight);
- checkArgument(spec.maximumSize == null, "maximum size was already set to ", spec.maximumSize);
+ spec.maximumWeight == null, "maximum weight was already set to %s", spec.maximumWeight);
+ checkArgument(
+ spec.maximumSize == null, "maximum size was already set to %s", spec.maximumSize);
spec.maximumWeight = value;
}
}
@@ -362,7 +364,7 @@ public final class CacheBuilderSpec {
protected void parseInteger(CacheBuilderSpec spec, int value) {
checkArgument(
spec.concurrencyLevel == null,
- "concurrency level was already set to ",
+ "concurrency level was already set to %s",
spec.concurrencyLevel);
spec.concurrencyLevel = value;
}
diff --git a/android/guava/src/com/google/common/cache/CacheLoader.java b/android/guava/src/com/google/common/cache/CacheLoader.java
index bb544cdcd..b5b8aef9f 100644
--- a/android/guava/src/com/google/common/cache/CacheLoader.java
+++ b/android/guava/src/com/google/common/cache/CacheLoader.java
@@ -23,10 +23,8 @@ import com.google.common.base.Supplier;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
-import com.google.errorprone.annotations.CheckReturnValue;
import java.io.Serializable;
import java.util.Map;
-import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
/**
@@ -135,10 +133,11 @@ public abstract class CacheLoader<K, V> {
* reloading or bulk loading. This is most useful when you can pass a lambda expression. Otherwise
* it is useful mostly when you already have an existing function instance.
*
+ * <p>The returned object is serializable if {@code function} is serializable.
+ *
* @param function the function to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by passing each key to {@code function}
*/
- @CheckReturnValue
public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
return new FunctionToCacheLoader<>(function);
}
@@ -148,13 +147,14 @@ public abstract class CacheLoader<K, V> {
* to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
+ * <p>The returned object is serializable if {@code supplier} is serializable.
+ *
* @param supplier the supplier to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
* key
*/
- @CheckReturnValue
public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
- return new SupplierToCacheLoader<V>(supplier);
+ return new SupplierToCacheLoader<>(supplier);
}
private static final class FunctionToCacheLoader<K, V> extends CacheLoader<K, V>
@@ -182,7 +182,6 @@ public abstract class CacheLoader<K, V> {
*
* @since 17.0
*/
- @CheckReturnValue
@GwtIncompatible // Executor + Futures
public static <K, V> CacheLoader<K, V> asyncReloading(
final CacheLoader<K, V> loader, final Executor executor) {
@@ -195,15 +194,9 @@ public abstract class CacheLoader<K, V> {
}
@Override
- public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
+ public ListenableFuture<V> reload(final K key, final V oldValue) {
ListenableFutureTask<V> task =
- ListenableFutureTask.create(
- new Callable<V>() {
- @Override
- public V call() throws Exception {
- return loader.reload(key, oldValue).get();
- }
- });
+ ListenableFutureTask.create(() -> loader.reload(key, oldValue).get());
executor.execute(task);
return task;
}
diff --git a/android/guava/src/com/google/common/cache/CacheStats.java b/android/guava/src/com/google/common/cache/CacheStats.java
index 8307e942a..3ca54e12e 100644
--- a/android/guava/src/com/google/common/cache/CacheStats.java
+++ b/android/guava/src/com/google/common/cache/CacheStats.java
@@ -151,8 +151,8 @@ public final class CacheStats {
/**
* Returns the total number of times that {@link Cache} lookup methods attempted to load new
- * values. This includes both successful load operations, as well as those that threw exceptions.
- * This is defined as {@code loadSuccessCount + loadExceptionCount}.
+ * values. This includes both successful load operations and those that threw exceptions. This is
+ * defined as {@code loadSuccessCount + loadExceptionCount}.
*
* <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
* guaranteed not to throw an exception). If you require specific handling, we recommend
diff --git a/android/guava/src/com/google/common/cache/ForwardingLoadingCache.java b/android/guava/src/com/google/common/cache/ForwardingLoadingCache.java
index ecd44ca8d..d98e2a627 100644
--- a/android/guava/src/com/google/common/cache/ForwardingLoadingCache.java
+++ b/android/guava/src/com/google/common/cache/ForwardingLoadingCache.java
@@ -17,6 +17,7 @@ package com.google.common.cache;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.ExecutionException;
/**
@@ -41,16 +42,19 @@ public abstract class ForwardingLoadingCache<K, V> extends ForwardingCache<K, V>
@Override
protected abstract LoadingCache<K, V> delegate();
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V get(K key) throws ExecutionException {
return delegate().get(key);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V getUnchecked(K key) {
return delegate().getUnchecked(key);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return delegate().getAll(keys);
diff --git a/android/guava/src/com/google/common/cache/LoadingCache.java b/android/guava/src/com/google/common/cache/LoadingCache.java
index e338ac4c3..a782aef55 100644
--- a/android/guava/src/com/google/common/cache/LoadingCache.java
+++ b/android/guava/src/com/google/common/cache/LoadingCache.java
@@ -19,6 +19,7 @@ import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
@@ -67,6 +68,7 @@ public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
* value
* @throws ExecutionError if an error was thrown while loading the value
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
V get(K key) throws ExecutionException;
/**
@@ -93,6 +95,7 @@ public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
* explained in the last paragraph above, this should be an unchecked exception only.)
* @throws ExecutionError if an error was thrown while loading the value
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
V getUnchecked(K key);
/**
@@ -119,6 +122,7 @@ public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
* @throws ExecutionError if an error was thrown while loading the values
* @since 11.0
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException;
/**
diff --git a/android/guava/src/com/google/common/cache/LocalCache.java b/android/guava/src/com/google/common/cache/LocalCache.java
index f3744e59c..239afe204 100644
--- a/android/guava/src/com/google/common/cache/LocalCache.java
+++ b/android/guava/src/com/google/common/cache/LocalCache.java
@@ -28,7 +28,6 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
-import com.google.common.base.Function;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
@@ -51,10 +50,13 @@ import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.Uninterruptibles;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import java.io.IOException;
+import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
@@ -69,7 +71,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
@@ -256,8 +257,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
removalListener = builder.getRemovalListener();
removalNotificationQueue =
(removalListener == NullListener.INSTANCE)
- ? LocalCache.<RemovalNotification<K, V>>discardingQueue()
- : new ConcurrentLinkedQueue<RemovalNotification<K, V>>();
+ ? LocalCache.discardingQueue()
+ : new ConcurrentLinkedQueue<>();
ticker = builder.getTicker(recordsTime());
entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries());
@@ -455,8 +456,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
@@ -470,8 +474,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
@@ -485,8 +492,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
@@ -508,8 +518,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
@@ -523,8 +536,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
@@ -538,8 +554,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
@@ -587,13 +606,18 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/**
* Copies an entry, assigning it a new {@code next} entry.
*
- * @param original the entry to copy
+ * @param original the entry to copy. But avoid calling {@code getKey} on it: Instead, use the
+ * {@code key} parameter. That way, we prevent the key from being garbage collected in the
+ * case of weak keys. If we create a new entry with a key that is null at construction time,
+ * we're not sure if entry will necessarily ever be garbage collected.
* @param newNext entry in the same bucket
+ * @param key the key to copy from the original entry to the new one. Use this in preference to
+ * {@code original.getKey()}.
*/
// Guarded By Segment.this
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- return newEntry(segment, original.getKey(), original.getHash(), newNext);
+ Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) {
+ return newEntry(segment, key, original.getHash(), newNext);
}
// Guarded By Segment.this
@@ -661,8 +685,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
void notifyNewValue(@CheckForNull V newValue);
/**
- * Returns true if a new value is currently loading, regardless of whether or not there is an
- * existing value. It is assumed that the return value of this method is constant for any given
+ * Returns true if a new value is currently loading, regardless of whether there is an existing
+ * value. It is assumed that the return value of this method is constant for any given
* ValueReference instance.
*/
boolean isLoading();
@@ -680,6 +704,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/** Placeholder. Indicates that the value hasn't been set yet. */
static final ValueReference<Object, Object> UNSET =
new ValueReference<Object, Object>() {
+ @CheckForNull
@Override
public Object get() {
return null;
@@ -690,6 +715,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return 0;
}
+ @CheckForNull
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
@@ -713,6 +739,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return false;
}
+ @CheckForNull
@Override
public Object waitForValue() {
return null;
@@ -731,6 +758,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
+ @CheckForNull
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
@@ -739,6 +767,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
+ @CheckForNull
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
@@ -749,6 +778,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return 0;
}
+ @CheckForNull
@Override
public Object getKey() {
return null;
@@ -902,11 +932,13 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return true;
}
+ @CheckForNull
@Override
public Object peek() {
return null;
}
+ @CheckForNull
@Override
public Object poll() {
return null;
@@ -1740,9 +1772,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
- * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to
- * cleanup stale entries. As such it should only be called outside of a segment context, such as
- * during iteration.
+ * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean
+ * up stale entries. As such it should only be called outside a segment context, such as during
+ * iteration.
*/
@CheckForNull
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
@@ -1946,24 +1978,16 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
this.statsCounter = checkNotNull(statsCounter);
initTable(newEntryArray(initialCapacity));
- keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<K>() : null;
+ keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null;
- valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<V>() : null;
+ valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null;
recencyQueue =
- map.usesAccessQueue()
- ? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
- : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
+ map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue();
- writeQueue =
- map.usesWriteQueue()
- ? new WriteQueue<K, V>()
- : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
+ writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue();
- accessQueue =
- map.usesAccessQueue()
- ? new AccessQueue<K, V>()
- : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
+ accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
@@ -1988,9 +2012,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
+ @CheckForNull
@GuardedBy("this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- if (original.getKey() == null) {
+ K key = original.getKey();
+ if (key == null) {
// key collected
return null;
}
@@ -2002,7 +2028,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return null;
}
- ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext);
+ ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext, key);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
@@ -2023,6 +2049,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// loading
+ @CanIgnoreReturnValue
V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
checkNotNull(key);
checkNotNull(loader);
@@ -2208,15 +2235,12 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
CacheLoader<? super K, V> loader) {
final ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
loadingFuture.addListener(
- new Runnable() {
- @Override
- public void run() {
- try {
- getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
- } catch (Throwable t) {
- logger.log(Level.WARNING, "Exception thrown during refresh", t);
- loadingValueReference.setException(t);
- }
+ () -> {
+ try {
+ getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
+ } catch (Throwable t) {
+ logger.log(Level.WARNING, "Exception thrown during refresh", t);
+ loadingValueReference.setException(t);
}
},
directExecutor());
@@ -2224,6 +2248,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
/** Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats. */
+ @CanIgnoreReturnValue
V getAndRecordStats(
K key,
int hash,
@@ -2271,6 +2296,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* {@code null} if another thread is performing the refresh or if an error occurs during
* refresh.
*/
+ @CanIgnoreReturnValue
@CheckForNull
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
final LoadingValueReference<K, V> loadingValueReference =
@@ -2482,7 +2508,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
- // all of the segment's entries.
+ // all the segment's entries.
if (accessQueue.contains(e)) {
accessQueue.add(e);
}
@@ -2688,6 +2714,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
+ @CanIgnoreReturnValue
@CheckForNull
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
@@ -3042,6 +3069,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
+ @CanIgnoreReturnValue
boolean storeLoadedValue(
K key, int hash, LoadingValueReference<K, V> oldValueReference, V newValue) {
lock();
@@ -3194,6 +3222,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
/** Removes an entry whose key has been garbage collected. */
+ @CanIgnoreReturnValue
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
@@ -3229,6 +3258,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
/** Removes an entry whose value has been garbage collected. */
+ @CanIgnoreReturnValue
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
@@ -3266,12 +3296,13 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return false;
} finally {
unlock();
- if (!isHeldByCurrentThread()) { // don't cleanup inside of put
+ if (!isHeldByCurrentThread()) { // don't clean up inside of put
postWriteCleanup();
}
}
}
+ @CanIgnoreReturnValue
boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) {
lock();
try {
@@ -3307,6 +3338,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@VisibleForTesting
@GuardedBy("this")
+ @CanIgnoreReturnValue
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
@@ -3417,10 +3449,12 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return oldValue.getWeight();
}
+ @CanIgnoreReturnValue
public boolean set(@CheckForNull V newValue) {
return futureValue.set(newValue);
}
+ @CanIgnoreReturnValue
public boolean setException(Throwable t) {
return futureValue.setException(t);
}
@@ -3459,12 +3493,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// *before* returning newValue from the cache query.
return transform(
newValue,
- new Function<V, V>() {
- @Override
- public V apply(V newValue) {
- LoadingValueReference.this.set(newValue);
- return newValue;
- }
+ newResult -> {
+ LoadingValueReference.this.set(newResult);
+ return newResult;
},
directExecutor());
} catch (Throwable t) {
@@ -3570,12 +3601,14 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return true;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
return (next == head) ? null : next;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
@@ -3589,6 +3622,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
@SuppressWarnings("unchecked")
+ @CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInWriteQueue();
@@ -3638,6 +3672,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
+ @CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInWriteQueue();
@@ -3709,12 +3744,14 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return true;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
return (next == head) ? null : next;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
@@ -3728,6 +3765,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
@SuppressWarnings("unchecked")
+ @CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInAccessQueue();
@@ -3777,6 +3815,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
+ @CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInAccessQueue();
@@ -3807,19 +3846,19 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].count != 0) {
+ for (Segment<K, V> segment : segments) {
+ if (segment.count != 0) {
return false;
}
- sum += segments[i].modCount;
+ sum += segment.modCount;
}
if (sum != 0L) { // recheck unless no modifications
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].count != 0) {
+ for (Segment<K, V> segment : segments) {
+ if (segment.count != 0) {
return false;
}
- sum -= segments[i].modCount;
+ sum -= segment.modCount;
}
return sum == 0L;
}
@@ -3829,8 +3868,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
long longSize() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
- for (int i = 0; i < segments.length; ++i) {
- sum += Math.max(0, segments[i].count); // see https://github.com/google/guava/issues/2108
+ for (Segment<K, V> segment : segments) {
+ sum += Math.max(0, segment.count); // see https://github.com/google/guava/issues/2108
}
return sum;
}
@@ -3840,6 +3879,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return Ints.saturatedCast(longSize());
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
@@ -3850,6 +3890,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).get(key, hash);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).get(key, hash, loader);
@@ -3867,7 +3908,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return value;
}
- @SuppressWarnings("MissingOverride") // Supermethod will not exist if we build with --release 7.
+ @Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
V result = get(key);
@@ -4013,6 +4054,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Returns the internal entry for the specified key. The entry may be loading, expired, or
* partially collected.
*/
+ @CheckForNull
ReferenceEntry<K, V> getEntry(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
@@ -4077,6 +4119,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return false;
}
+ @CheckForNull
+ @CanIgnoreReturnValue
@Override
public V put(K key, V value) {
checkNotNull(key);
@@ -4085,6 +4129,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).put(key, hash, value, false);
}
+ @CheckForNull
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
@@ -4100,6 +4145,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
+ @CheckForNull
+ @CanIgnoreReturnValue
@Override
public V remove(@CheckForNull Object key) {
if (key == null) {
@@ -4109,6 +4156,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).remove(key, hash);
}
+ @CanIgnoreReturnValue
@Override
public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
if (key == null || value == null) {
@@ -4118,6 +4166,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).remove(key, hash, value);
}
+ @CanIgnoreReturnValue
@Override
public boolean replace(K key, @CheckForNull V oldValue, V newValue) {
checkNotNull(key);
@@ -4129,6 +4178,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
+ @CheckForNull
+ @CanIgnoreReturnValue
@Override
public V replace(K key, V value) {
checkNotNull(key);
@@ -4151,7 +4202,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
- @RetainedWith @CheckForNull Set<K> keySet;
+ @LazyInit @RetainedWith @CheckForNull Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -4160,7 +4211,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return (ks != null) ? ks : (keySet = new KeySet());
}
- @RetainedWith @CheckForNull Collection<V> values;
+ @LazyInit @RetainedWith @CheckForNull Collection<V> values;
@Override
public Collection<V> values() {
@@ -4169,7 +4220,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return (vs != null) ? vs : (values = new Values());
}
- @RetainedWith @CheckForNull Set<Entry<K, V>> entrySet;
+ @LazyInit @RetainedWith @CheckForNull Set<Entry<K, V>> entrySet;
@Override
@GwtIncompatible // Not supported.
@@ -4398,7 +4449,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
private static <E> ArrayList<E> toArrayList(Collection<E> c) {
// Avoid calling ArrayList(Collection), which may call back into toArray.
- ArrayList<E> result = new ArrayList<E>(c.size());
+ ArrayList<E> result = new ArrayList<>(c.size());
Iterators.addAll(result, c.iterator());
return result;
}
@@ -4583,7 +4634,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
builder.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (weigher != OneWeigher.INSTANCE) {
- builder.weigher(weigher);
+ Object unused = builder.weigher(weigher);
if (maxWeight != UNSET_INT) {
builder.maximumWeight(maxWeight);
}
@@ -4654,7 +4705,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public final V apply(K key) {
+ public V apply(K key) {
return autoDelegate.apply(key);
}
@@ -4672,7 +4723,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
final LocalCache<K, V> localCache;
LocalManualCache(CacheBuilder<? super K, ? super V> builder) {
- this(new LocalCache<K, V>(builder, null));
+ this(new LocalCache<>(builder, null));
}
private LocalManualCache(LocalCache<K, V> localCache) {
@@ -4763,6 +4814,10 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
Object writeReplace() {
return new ManualSerializationProxy<>(localCache);
}
+
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use ManualSerializationProxy");
+ }
}
static class LocalLoadingCache<K, V> extends LocalManualCache<K, V>
@@ -4770,7 +4825,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
LocalLoadingCache(
CacheBuilder<? super K, ? super V> builder, CacheLoader<? super K, V> loader) {
- super(new LocalCache<K, V>(builder, checkNotNull(loader)));
+ super(new LocalCache<>(builder, checkNotNull(loader)));
}
// LoadingCache methods
@@ -4780,6 +4835,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return localCache.getOrLoad(key);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V getUnchecked(K key) {
try {
@@ -4812,5 +4868,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
Object writeReplace() {
return new LoadingSerializationProxy<>(localCache);
}
+
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use LoadingSerializationProxy");
+ }
}
}
diff --git a/android/guava/src/com/google/common/cache/ParametricNullness.java b/android/guava/src/com/google/common/cache/ParametricNullness.java
index 64682de55..eaf194d4a 100644
--- a/android/guava/src/com/google/common/cache/ParametricNullness.java
+++ b/android/guava/src/com/google/common/cache/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/cache/package-info.java b/android/guava/src/com/google/common/cache/package-info.java
index a7791de49..fc678d44a 100644
--- a/android/guava/src/com/google/common/cache/package-info.java
+++ b/android/guava/src/com/google/common/cache/package-info.java
@@ -13,23 +13,24 @@
*/
/**
- * This package contains caching utilities.
+ * <a href="https://guava.dev/CacheBuilder">Discouraged</a> (in favor of <a
+ * href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>) caching utilities.
*
- * <p>The core interface used to represent caches is {@link com.google.common.cache.Cache}.
- * In-memory caches can be configured and created using {@link
- * com.google.common.cache.CacheBuilder}, with cache entries being loaded by {@link
- * com.google.common.cache.CacheLoader}. Statistics about cache performance are exposed using {@link
- * com.google.common.cache.CacheStats}.
+ * <p>The core interface used to represent caches is {@link Cache}. In-memory caches can be
+ * configured and created using {@link CacheBuilder}, with cache entries being loaded by {@link
+ * CacheLoader}. Statistics about cache performance are exposed using {@link CacheStats}.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/CachesExplained">caches</a>.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* @author Charles Fry
*/
+@CheckReturnValue
@ParametersAreNonnullByDefault
package com.google.common.cache;
+import com.google.errorprone.annotations.CheckReturnValue;
import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/android/guava/src/com/google/common/collect/AbstractBiMap.java b/android/guava/src/com/google/common/collect/AbstractBiMap.java
index 151764be8..10edc5c4c 100644
--- a/android/guava/src/com/google/common/collect/AbstractBiMap.java
+++ b/android/guava/src/com/google/common/collect/AbstractBiMap.java
@@ -22,8 +22,10 @@ import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
@@ -51,8 +53,12 @@ import org.checkerframework.checker.nullness.qual.Nullable;
abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
+ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (lateinit)
private transient Map<K, V> delegate;
- @RetainedWith transient AbstractBiMap<V, K> inverse;
+
+ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (lateinit)
+ @RetainedWith
+ transient AbstractBiMap<V, K> inverse;
/** Package-private constructor for creating a map-backed bimap. */
AbstractBiMap(Map<K, V> forward, Map<V, K> backward) {
@@ -201,7 +207,7 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
return inverse;
}
- @CheckForNull private transient Set<K> keySet;
+ @LazyInit @CheckForNull private transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -246,7 +252,7 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- @CheckForNull private transient Set<V> valueSet;
+ @LazyInit @CheckForNull private transient Set<V> valueSet;
@Override
public Set<V> values() {
@@ -289,7 +295,7 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- @CheckForNull private transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -398,15 +404,8 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
// See java.util.Collections.CheckedEntrySet for details on attacks.
@Override
- public Object[] toArray() {
- /*
- * standardToArray returns `@Nullable Object[]` rather than `Object[]` but only because it can
- * be used with collections that may contain null. This collection never contains nulls, so we
- * can treat it as a plain `Object[]`.
- */
- @SuppressWarnings("nullness")
- Object[] result = standardToArray();
- return result;
+ public @Nullable Object[] toArray() {
+ return standardToArray();
}
@Override
@@ -464,14 +463,18 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
return inverse.checkKey(value);
}
- /** @serialData the forward bimap */
+ /**
+ * @serialData the forward bimap
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(inverse());
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -479,14 +482,17 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
@GwtIncompatible // Not needed in the emulated source.
+ @J2ktIncompatible
Object readResolve() {
return inverse().inverse();
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/AbstractIterator.java b/android/guava/src/com/google/common/collect/AbstractIterator.java
index 66273f438..aa01300be 100644
--- a/android/guava/src/com/google/common/collect/AbstractIterator.java
+++ b/android/guava/src/com/google/common/collect/AbstractIterator.java
@@ -127,7 +127,6 @@ public abstract class AbstractIterator<T extends @Nullable Object> extends Unmod
return null;
}
- @CanIgnoreReturnValue // TODO(kak): Should we remove this? Some people are using it to prefetch?
@Override
public final boolean hasNext() {
checkState(state != State.FAILED);
diff --git a/android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java b/android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
index 72cf8f1ee..9a2612edf 100644
--- a/android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
+++ b/android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
@@ -1175,6 +1175,7 @@ abstract class AbstractMapBasedMultimap<K extends @Nullable Object, V extends @N
}
@Override
+ @ParametricNullness
public T next() {
if (!valueIterator.hasNext()) {
Entry<K, Collection<V>> mapEntry = keyIterator.next();
diff --git a/android/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java b/android/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
index 8c71e682d..45530f267 100644
--- a/android/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
+++ b/android/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -255,12 +256,14 @@ abstract class AbstractMapBasedMultiset<E extends @Nullable Object> extends Abst
* its count, and so on
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultiset(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int distinctElements = Serialization.readCount(stream);
@@ -269,5 +272,6 @@ abstract class AbstractMapBasedMultiset<E extends @Nullable Object> extends Abst
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/AbstractNavigableMap.java b/android/guava/src/com/google/common/collect/AbstractNavigableMap.java
index 47048d06a..fa68dc524 100644
--- a/android/guava/src/com/google/common/collect/AbstractNavigableMap.java
+++ b/android/guava/src/com/google/common/collect/AbstractNavigableMap.java
@@ -44,13 +44,13 @@ abstract class AbstractNavigableMap<K extends @Nullable Object, V extends @Nulla
@Override
@CheckForNull
public Entry<K, V> firstEntry() {
- return Iterators.getNext(entryIterator(), null);
+ return Iterators.<@Nullable Entry<K, V>>getNext(entryIterator(), null);
}
@Override
@CheckForNull
public Entry<K, V> lastEntry() {
- return Iterators.getNext(descendingEntryIterator(), null);
+ return Iterators.<@Nullable Entry<K, V>>getNext(descendingEntryIterator(), null);
}
@Override
diff --git a/android/guava/src/com/google/common/collect/AbstractSortedMultiset.java b/android/guava/src/com/google/common/collect/AbstractSortedMultiset.java
index 621e8f98a..98b6211a7 100644
--- a/android/guava/src/com/google/common/collect/AbstractSortedMultiset.java
+++ b/android/guava/src/com/google/common/collect/AbstractSortedMultiset.java
@@ -17,6 +17,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Comparator;
import java.util.Iterator;
@@ -122,7 +123,7 @@ abstract class AbstractSortedMultiset<E extends @Nullable Object> extends Abstra
return Multisets.iteratorImpl(descendingMultiset());
}
- @CheckForNull private transient SortedMultiset<E> descendingMultiset;
+ @LazyInit @CheckForNull private transient SortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
diff --git a/android/guava/src/com/google/common/collect/AllEqualOrdering.java b/android/guava/src/com/google/common/collect/AllEqualOrdering.java
index f6ca6faff..366044b01 100644
--- a/android/guava/src/com/google/common/collect/AllEqualOrdering.java
+++ b/android/guava/src/com/google/common/collect/AllEqualOrdering.java
@@ -43,8 +43,7 @@ final class AllEqualOrdering extends Ordering<@Nullable Object> implements Seria
}
@Override
- @SuppressWarnings("nullness") // unsafe: see supertype
- public <E extends @Nullable Object> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
+ public <E> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
return ImmutableList.copyOf(iterable);
}
diff --git a/android/guava/src/com/google/common/collect/ArrayListMultimap.java b/android/guava/src/com/google/common/collect/ArrayListMultimap.java
index 349f40770..5983a58ed 100644
--- a/android/guava/src/com/google/common/collect/ArrayListMultimap.java
+++ b/android/guava/src/com/google/common/collect/ArrayListMultimap.java
@@ -20,6 +20,7 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -155,12 +156,14 @@ public final class ArrayListMultimap<K extends @Nullable Object, V extends @Null
* key, number of values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
@@ -171,5 +174,6 @@ public final class ArrayListMultimap<K extends @Nullable Object, V extends @Null
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/ArrayTable.java b/android/guava/src/com/google/common/collect/ArrayTable.java
index aa042877c..97a784bac 100644
--- a/android/guava/src/com/google/common/collect/ArrayTable.java
+++ b/android/guava/src/com/google/common/collect/ArrayTable.java
@@ -21,13 +21,13 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.emptyMap;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.lang.reflect.Array;
@@ -88,7 +88,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jared Levy
* @since 10.0
*/
-@Beta
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
@@ -650,7 +649,7 @@ public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
return columnKeyToIndex.keySet();
}
- @CheckForNull private transient ColumnMap columnMap;
+ @LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, @Nullable V>> columnMap() {
@@ -745,7 +744,7 @@ public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
return rowKeyToIndex.keySet();
}
- @CheckForNull private transient RowMap rowMap;
+ @LazyInit @CheckForNull private transient RowMap rowMap;
@Override
public Map<R, Map<C, @Nullable V>> rowMap() {
diff --git a/android/guava/src/com/google/common/collect/BiMap.java b/android/guava/src/com/google/common/collect/BiMap.java
index 12eb4e3e1..d95a71eb7 100644
--- a/android/guava/src/com/google/common/collect/BiMap.java
+++ b/android/guava/src/com/google/common/collect/BiMap.java
@@ -28,6 +28,15 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* that of its keys. This constraint enables bimaps to support an "inverse view", which is another
* bimap containing the same entries as this bimap but with reversed keys and values.
*
+ * <h3>Implementations</h3>
+ *
+ * <ul>
+ * <li>{@link ImmutableBiMap}
+ * <li>{@link HashBiMap}
+ * <li>{@link EnumBiMap}
+ * <li>{@link EnumHashBiMap}
+ * </ul>
+ *
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">{@code BiMap}</a>.
*
diff --git a/android/guava/src/com/google/common/collect/ClassToInstanceMap.java b/android/guava/src/com/google/common/collect/ClassToInstanceMap.java
index 9bd826fd9..094a7fdd7 100644
--- a/android/guava/src/com/google/common/collect/ClassToInstanceMap.java
+++ b/android/guava/src/com/google/common/collect/ClassToInstanceMap.java
@@ -21,6 +21,8 @@ import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Map;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A map, each entry of which maps a Java <a href="http://tinyurl.com/2cmwkz">raw type</a> to an
@@ -30,43 +32,36 @@ import javax.annotation.CheckForNull;
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries for primitive types,
* and a primitive type and its corresponding wrapper type may map to different values.
*
- * <p>This class's support for {@code null} requires some explanation: From release 31.0 onward,
- * Guava specifies the nullness of its types through annotations. In the case of {@code
- * ClassToInstanceMap}, it specifies that both the key and value types are restricted to
- * non-nullable types. This specification is reasonable for <i>keys</i>, which must be non-null
- * classes. This is in contrast to the specification for <i>values</i>: Null values <i>are</i>
- * supported by the implementation {@link MutableClassToInstanceMap}, even though that
- * implementation and this interface specify otherwise. Thus, if you use a nullness checker, you can
- * safely suppress any warnings it produces when you write null values into a {@code
- * MutableClassToInstanceMap}. Just be sure to be prepared for null values when reading from it,
- * since nullness checkers will assume that vaules are non-null then, too.
+ * <h3>Implementations</h3>
*
- * <p>See the Guava User Guide article on <a href=
- * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
- * ClassToInstanceMap}</a>.
+ * <ul>
+ * <li>{@link ImmutableClassToInstanceMap}
+ * <li>{@link MutableClassToInstanceMap}
+ * </ul>
*
* <p>To map a generic type to an instance of that type, use {@link
* com.google.common.reflect.TypeToInstanceMap} instead.
*
- * @param <B> the common supertype that all entries must share; often this is simply {@link Object}
- * @author Kevin Bourrillion
+ * <p>See the Guava User Guide article on <a href=
+ * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
+ * ClassToInstanceMap}</a>.
+ *
+ * @param <B> the common supertype that all values will share. When in doubt, just use {@link
+ * Object}, or use {@code @Nullable Object} to allow null values.
* @since 2.0
*/
@DoNotMock("Use ImmutableClassToInstanceMap or MutableClassToInstanceMap")
@GwtCompatible
@ElementTypesAreNonnullByDefault
-// If we ever support non-null projections (https://github.com/jspecify/jspecify/issues/86), we
-// we might annotate this as...
-// ClassToInstanceMap<B extends @Nullable Object> extends Map<Class<? extends @Nonnull B>, B>
-// ...and change its methods similarly (<T extends @Nonnull B> or Class<@Nonnull T>).
-public interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B> {
+public interface ClassToInstanceMap<B extends @Nullable Object>
+ extends Map<Class<? extends @NonNull B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no entry for this class
* is present. This will only return a value that was bound to this specific class, not a value
* that may have been bound to a subtype.
*/
@CheckForNull
- <T extends B> T getInstance(Class<T> type);
+ <T extends @NonNull B> T getInstance(Class<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate this value with any
@@ -77,5 +72,5 @@ public interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B> {
*/
@CanIgnoreReturnValue
@CheckForNull
- <T extends B> T putInstance(Class<T> type, T value);
+ <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value);
}
diff --git a/android/guava/src/com/google/common/collect/Collections2.java b/android/guava/src/com/google/common/collect/Collections2.java
index 8d799d593..f2790c9db 100644
--- a/android/guava/src/com/google/common/collect/Collections2.java
+++ b/android/guava/src/com/google/common/collect/Collections2.java
@@ -21,7 +21,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
@@ -357,7 +356,6 @@ public final class Collections2 {
* @throws NullPointerException if the specified iterable is null or has any null elements.
* @since 12.0
*/
- @Beta
public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(
Iterable<E> elements) {
return orderedPermutations(elements, Ordering.natural());
@@ -409,7 +407,6 @@ public final class Collections2 {
* the specified comparator is null.
* @since 12.0
*/
- @Beta
public static <E> Collection<List<E>> orderedPermutations(
Iterable<E> elements, Comparator<? super E> comparator) {
return new OrderedPermutationCollection<E>(elements, comparator);
@@ -571,7 +568,6 @@ public final class Collections2 {
* @throws NullPointerException if the specified collection is null or has any null elements.
* @since 12.0
*/
- @Beta
public static <E> Collection<List<E>> permutations(Collection<E> elements) {
return new PermutationCollection<E>(ImmutableList.copyOf(elements));
}
diff --git a/android/guava/src/com/google/common/collect/CompactHashMap.java b/android/guava/src/com/google/common/collect/CompactHashMap.java
index e70596dd2..d664c46ac 100644
--- a/android/guava/src/com/google/common/collect/CompactHashMap.java
+++ b/android/guava/src/com/google/common/collect/CompactHashMap.java
@@ -24,11 +24,13 @@ import static com.google.common.collect.NullnessCasts.unsafeNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.InvalidObjectException;
@@ -670,7 +672,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
}
- @CheckForNull private transient Set<K> keySetView;
+ @LazyInit @CheckForNull private transient Set<K> keySetView;
@Override
public Set<K> keySet() {
@@ -726,7 +728,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
};
}
- @CheckForNull private transient Set<Entry<K, V>> entrySetView;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySetView;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -906,7 +908,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
return false;
}
- @CheckForNull private transient Collection<V> valuesView;
+ @LazyInit @CheckForNull private transient Collection<V> valuesView;
@Override
public Collection<V> values() {
@@ -997,6 +999,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
}
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
@@ -1009,6 +1012,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
@SuppressWarnings("unchecked")
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
diff --git a/android/guava/src/com/google/common/collect/CompactHashSet.java b/android/guava/src/com/google/common/collect/CompactHashSet.java
index 08c729423..52f8a4a67 100644
--- a/android/guava/src/com/google/common/collect/CompactHashSet.java
+++ b/android/guava/src/com/google/common/collect/CompactHashSet.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.Hashing.smearedHash;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
@@ -669,6 +670,7 @@ class CompactHashSet<E extends @Nullable Object> extends AbstractSet<E> implemen
}
}
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
@@ -678,6 +680,7 @@ class CompactHashSet<E extends @Nullable Object> extends AbstractSet<E> implemen
}
@SuppressWarnings("unchecked")
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
diff --git a/android/guava/src/com/google/common/collect/CompactLinkedHashMap.java b/android/guava/src/com/google/common/collect/CompactLinkedHashMap.java
index fb648a7a4..d32e38f92 100644
--- a/android/guava/src/com/google/common/collect/CompactLinkedHashMap.java
+++ b/android/guava/src/com/google/common/collect/CompactLinkedHashMap.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
@@ -47,6 +48,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Louis Wasserman
*/
+@J2ktIncompatible // no support for access-order mode in LinkedHashMap delegate
@GwtIncompatible // not worth using in GWT for now
@ElementTypesAreNonnullByDefault
class CompactLinkedHashMap<K extends @Nullable Object, V extends @Nullable Object>
diff --git a/android/guava/src/com/google/common/collect/CompoundOrdering.java b/android/guava/src/com/google/common/collect/CompoundOrdering.java
index 42feed373..95ebb82bb 100644
--- a/android/guava/src/com/google/common/collect/CompoundOrdering.java
+++ b/android/guava/src/com/google/common/collect/CompoundOrdering.java
@@ -30,12 +30,14 @@ final class CompoundOrdering<T extends @Nullable Object> extends Ordering<T>
implements Serializable {
final Comparator<? super T>[] comparators;
+ @SuppressWarnings("unchecked") // Generic array creation
CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) {
this.comparators = (Comparator<? super T>[]) new Comparator[] {primary, secondary};
}
+ @SuppressWarnings("unchecked") // Generic array creation
CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) {
- this.comparators = Iterables.toArray(comparators, new Comparator[0]);
+ this.comparators = Iterables.toArray(comparators, (Comparator<? super T>[]) new Comparator[0]);
}
@Override
diff --git a/android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java b/android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
index 47248412b..723ab0696 100644
--- a/android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
+++ b/android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
@@ -21,8 +21,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Serialization.FieldSetter;
import com.google.common.math.IntMath;
@@ -55,6 +55,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author mike nonemacher
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable {
@@ -118,7 +119,6 @@ public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> impleme
* @throws IllegalArgumentException if {@code countMap} is not empty
* @since 20.0
*/
- @Beta
public static <E> ConcurrentHashMultiset<E> create(ConcurrentMap<E, AtomicInteger> countMap) {
return new ConcurrentHashMultiset<>(countMap);
}
@@ -594,6 +594,7 @@ public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> impleme
stream.writeObject(countMap);
}
+ @J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
diff --git a/android/guava/src/com/google/common/collect/ConsumingQueueIterator.java b/android/guava/src/com/google/common/collect/ConsumingQueueIterator.java
index 7721e1277..3a923ae21 100644
--- a/android/guava/src/com/google/common/collect/ConsumingQueueIterator.java
+++ b/android/guava/src/com/google/common/collect/ConsumingQueueIterator.java
@@ -23,7 +23,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An Iterator implementation which draws elements from a queue, removing them from the queue as it
- * iterates.
+ * iterates. This class is not thread safe.
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
@@ -36,7 +36,7 @@ final class ConsumingQueueIterator<T extends @Nullable Object> extends AbstractI
@Override
@CheckForNull
- public T computeNext() {
+ protected T computeNext() {
// TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker.
if (queue.isEmpty()) {
return endOfData();
diff --git a/android/guava/src/com/google/common/collect/ContiguousSet.java b/android/guava/src/com/google/common/collect/ContiguousSet.java
index b3e4889d7..d0792054e 100644
--- a/android/guava/src/com/google/common/collect/ContiguousSet.java
+++ b/android/guava/src/com/google/common/collect/ContiguousSet.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotCall;
@@ -103,7 +102,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Integer> closed(int lower, int upper) {
return create(Range.closed(lower, upper), DiscreteDomain.integers());
}
@@ -116,7 +114,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Long> closed(long lower, long upper) {
return create(Range.closed(lower, upper), DiscreteDomain.longs());
}
@@ -129,7 +126,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Integer> closedOpen(int lower, int upper) {
return create(Range.closedOpen(lower, upper), DiscreteDomain.integers());
}
@@ -142,7 +138,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Long> closedOpen(long lower, long upper) {
return create(Range.closedOpen(lower, upper), DiscreteDomain.longs());
}
@@ -245,7 +240,7 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
return new DescendingImmutableSortedSet<>(this);
}
- /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
+ /** Returns a shorthand representation of the contents such as {@code "[1..100]"}. */
@Override
public String toString() {
return range().toString();
diff --git a/android/guava/src/com/google/common/collect/DescendingMultiset.java b/android/guava/src/com/google/common/collect/DescendingMultiset.java
index 7db0fbbd4..23ff8319c 100644
--- a/android/guava/src/com/google/common/collect/DescendingMultiset.java
+++ b/android/guava/src/com/google/common/collect/DescendingMultiset.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Comparator;
import java.util.Iterator;
@@ -37,7 +38,7 @@ abstract class DescendingMultiset<E extends @Nullable Object> extends Forwarding
implements SortedMultiset<E> {
abstract SortedMultiset<E> forwardMultiset();
- @CheckForNull private transient Comparator<? super E> comparator;
+ @LazyInit @CheckForNull private transient Comparator<? super E> comparator;
@Override
public Comparator<? super E> comparator() {
@@ -48,7 +49,7 @@ abstract class DescendingMultiset<E extends @Nullable Object> extends Forwarding
return result;
}
- @CheckForNull private transient NavigableSet<E> elementSet;
+ @LazyInit @CheckForNull private transient NavigableSet<E> elementSet;
@Override
public NavigableSet<E> elementSet() {
@@ -116,7 +117,7 @@ abstract class DescendingMultiset<E extends @Nullable Object> extends Forwarding
abstract Iterator<Entry<E>> entryIterator();
- @CheckForNull private transient Set<Entry<E>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<E>> entrySet;
@Override
public Set<Entry<E>> entrySet() {
diff --git a/android/guava/src/com/google/common/collect/DiscreteDomain.java b/android/guava/src/com/google/common/collect/DiscreteDomain.java
index 222ebe528..c32ea8408 100644
--- a/android/guava/src/com/google/common/collect/DiscreteDomain.java
+++ b/android/guava/src/com/google/common/collect/DiscreteDomain.java
@@ -50,6 +50,9 @@ public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code Integer}.
*
+ * <p>This method always returns the same object. That object is serializable; deserializing it
+ * results in the same object too.
+ *
* @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()})
*/
public static DiscreteDomain<Integer> integers() {
@@ -113,6 +116,9 @@ public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code Long}.
*
+ * <p>This method always returns the same object. That object is serializable; deserializing it
+ * results in the same object too.
+ *
* @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()})
*/
public static DiscreteDomain<Long> longs() {
@@ -187,6 +193,9 @@ public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code BigInteger}.
*
+ * <p>This method always returns the same object. That object is serializable; deserializing it
+ * results in the same object too.
+ *
* @since 15.0
*/
public static DiscreteDomain<BigInteger> bigIntegers() {
diff --git a/android/guava/src/com/google/common/collect/EmptyContiguousSet.java b/android/guava/src/com/google/common/collect/EmptyContiguousSet.java
index 50d7b126a..5ae3d23f4 100644
--- a/android/guava/src/com/google/common/collect/EmptyContiguousSet.java
+++ b/android/guava/src/com/google/common/collect/EmptyContiguousSet.java
@@ -15,6 +15,9 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.Set;
@@ -142,6 +145,7 @@ final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private static final class SerializedForm<C extends Comparable> implements Serializable {
private final DiscreteDomain<C> domain;
@@ -157,14 +161,21 @@ final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm<>(domain);
}
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
@GwtIncompatible // NavigableSet
@Override
ImmutableSortedSet<C> createDescendingSet() {
- return ImmutableSortedSet.emptySet(Ordering.natural().reverse());
+ return ImmutableSortedSet.emptySet(Ordering.<C>natural().reverse());
}
}
diff --git a/android/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java b/android/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java
index 10d030fbd..8a6030182 100644
--- a/android/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java
+++ b/android/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import java.util.Collection;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
@@ -32,6 +33,17 @@ class EmptyImmutableListMultimap extends ImmutableListMultimap<Object, Object> {
super(ImmutableMap.<Object, ImmutableList<Object>>of(), 0);
}
+ /*
+ * TODO(b/242884182): Figure out why this helps produce the same class file when we compile most
+ * of common.collect a second time with the results of the first compilation on the classpath. Or
+ * just back this out once we stop doing that (which we'll do after our internal GWT setup
+ * changes).
+ */
+ @Override
+ public ImmutableMap<Object, Collection<Object>> asMap() {
+ return super.asMap();
+ }
+
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
diff --git a/android/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java b/android/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
index bd0a67aa0..087112e10 100644
--- a/android/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
+++ b/android/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import java.util.Collection;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
@@ -32,6 +33,17 @@ class EmptyImmutableSetMultimap extends ImmutableSetMultimap<Object, Object> {
super(ImmutableMap.<Object, ImmutableSet<Object>>of(), 0, null);
}
+ /*
+ * TODO(b/242884182): Figure out why this helps produce the same class file when we compile most
+ * of common.collect a second time with the results of the first compilation on the classpath. Or
+ * just back this out once we stop doing that (which we'll do after our internal GWT setup
+ * changes).
+ */
+ @Override
+ public ImmutableMap<Object, Collection<Object>> asMap() {
+ return super.asMap();
+ }
+
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
diff --git a/android/guava/src/com/google/common/collect/EnumBiMap.java b/android/guava/src/com/google/common/collect/EnumBiMap.java
index 97d3c2e7c..c4b540b56 100644
--- a/android/guava/src/com/google/common/collect/EnumBiMap.java
+++ b/android/guava/src/com/google/common/collect/EnumBiMap.java
@@ -18,9 +18,11 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.collect.Platform.getDeclaringClassOrObjectForJ2cl;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -38,10 +40,25 @@ import java.util.Map;
* @since 2.0
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends AbstractBiMap<K, V> {
- private transient Class<K> keyType;
- private transient Class<V> valueType;
+ /*
+ * J2CL's EnumMap does not need the Class instance, so we can use Object.class instead. (Or we
+ * could use null, but that messes with our nullness checking, including under J2KT. We could
+ * probably work around it by changing how we annotate the J2CL EnumMap, but that's probably more
+ * trouble than just using Object.class.)
+ *
+ * Then we declare the getters for these fields as @GwtIncompatible so that no one can try to use
+ * them under J2CL—or, as an unfortunate side effect, under GWT. We do still give the fields
+ * themselves their proper values under GWT, since GWT's EnumMap does need the Class instance.
+ *
+ * Note that sometimes these fields *do* have correct values under J2CL: They will if the caller
+ * calls `create(Foo.class)`, rather than `create(map)`. That's fine; we just shouldn't rely on
+ * it.
+ */
+ transient Class<K> keyTypeOrObjectUnderJ2cl;
+ transient Class<V> valueTypeOrObjectUnderJ2cl;
/**
* Returns a new, empty {@code EnumBiMap} using the specified key and value types.
@@ -64,44 +81,48 @@ public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends Abstr
* mappings
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Map<K, V> map) {
- EnumBiMap<K, V> bimap = create(inferKeyType(map), inferValueType(map));
+ EnumBiMap<K, V> bimap =
+ create(inferKeyTypeOrObjectUnderJ2cl(map), inferValueTypeOrObjectUnderJ2cl(map));
bimap.putAll(map);
return bimap;
}
- private EnumBiMap(Class<K> keyType, Class<V> valueType) {
- super(new EnumMap<K, V>(keyType), new EnumMap<V, K>(valueType));
- this.keyType = keyType;
- this.valueType = valueType;
+ private EnumBiMap(Class<K> keyTypeOrObjectUnderJ2cl, Class<V> valueTypeOrObjectUnderJ2cl) {
+ super(
+ new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
+ this.keyTypeOrObjectUnderJ2cl = keyTypeOrObjectUnderJ2cl;
+ this.valueTypeOrObjectUnderJ2cl = valueTypeOrObjectUnderJ2cl;
}
- static <K extends Enum<K>> Class<K> inferKeyType(Map<K, ?> map) {
+ static <K extends Enum<K>> Class<K> inferKeyTypeOrObjectUnderJ2cl(Map<K, ?> map) {
if (map instanceof EnumBiMap) {
- return ((EnumBiMap<K, ?>) map).keyType();
+ return ((EnumBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
}
if (map instanceof EnumHashBiMap) {
- return ((EnumHashBiMap<K, ?>) map).keyType();
+ return ((EnumHashBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
}
checkArgument(!map.isEmpty());
- return map.keySet().iterator().next().getDeclaringClass();
+ return getDeclaringClassOrObjectForJ2cl(map.keySet().iterator().next());
}
- private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) {
+ private static <V extends Enum<V>> Class<V> inferValueTypeOrObjectUnderJ2cl(Map<?, V> map) {
if (map instanceof EnumBiMap) {
- return ((EnumBiMap<?, V>) map).valueType;
+ return ((EnumBiMap<?, V>) map).valueTypeOrObjectUnderJ2cl;
}
checkArgument(!map.isEmpty());
- return map.values().iterator().next().getDeclaringClass();
+ return getDeclaringClassOrObjectForJ2cl(map.values().iterator().next());
}
/** Returns the associated key type. */
+ @GwtIncompatible
public Class<K> keyType() {
- return keyType;
+ return keyTypeOrObjectUnderJ2cl;
}
/** Returns the associated value type. */
+ @GwtIncompatible
public Class<V> valueType() {
- return valueType;
+ return valueTypeOrObjectUnderJ2cl;
}
@Override
@@ -121,8 +142,8 @@ public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends Abstr
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
- stream.writeObject(keyType);
- stream.writeObject(valueType);
+ stream.writeObject(keyTypeOrObjectUnderJ2cl);
+ stream.writeObject(valueTypeOrObjectUnderJ2cl);
Serialization.writeMap(this, stream);
}
@@ -130,9 +151,10 @@ public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends Abstr
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
- keyType = (Class<K>) stream.readObject();
- valueType = (Class<V>) stream.readObject();
- setDelegates(new EnumMap<K, V>(keyType), new EnumMap<V, K>(valueType));
+ keyTypeOrObjectUnderJ2cl = (Class<K>) stream.readObject();
+ valueTypeOrObjectUnderJ2cl = (Class<V>) stream.readObject();
+ setDelegates(
+ new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
Serialization.populateMap(this, stream);
}
diff --git a/android/guava/src/com/google/common/collect/EnumHashBiMap.java b/android/guava/src/com/google/common/collect/EnumHashBiMap.java
index 5fbbb70c6..33b45b95c 100644
--- a/android/guava/src/com/google/common/collect/EnumHashBiMap.java
+++ b/android/guava/src/com/google/common/collect/EnumHashBiMap.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -42,10 +43,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 2.0
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
extends AbstractBiMap<K, V> {
- private transient Class<K> keyType;
+ transient Class<K> keyTypeOrObjectUnderJ2cl;
/**
* Returns a new, empty {@code EnumHashBiMap} using the specified key type.
@@ -69,16 +71,15 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
*/
public static <K extends Enum<K>, V extends @Nullable Object> EnumHashBiMap<K, V> create(
Map<K, ? extends V> map) {
- EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
+ EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyTypeOrObjectUnderJ2cl(map));
bimap.putAll(map);
return bimap;
}
private EnumHashBiMap(Class<K> keyType) {
- super(
- new EnumMap<K, V>(keyType),
- Maps.<V, K>newHashMapWithExpectedSize(keyType.getEnumConstants().length));
- this.keyType = keyType;
+ super(new EnumMap<K, V>(keyType), new HashMap<V, K>());
+ // TODO: cpovirk - Pre-size the HashMap based on the number of enum values?
+ this.keyTypeOrObjectUnderJ2cl = keyType;
}
// Overriding these 3 methods to show that values may be null (but not keys)
@@ -107,8 +108,9 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
}
/** Returns the associated key type. */
+ @GwtIncompatible
public Class<K> keyType() {
- return keyType;
+ return keyTypeOrObjectUnderJ2cl;
}
/**
@@ -118,7 +120,7 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
- stream.writeObject(keyType);
+ stream.writeObject(keyTypeOrObjectUnderJ2cl);
Serialization.writeMap(this, stream);
}
@@ -126,9 +128,13 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
- keyType = (Class<K>) stream.readObject();
- setDelegates(
- new EnumMap<K, V>(keyType), new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
+ keyTypeOrObjectUnderJ2cl = (Class<K>) stream.readObject();
+ /*
+ * TODO: cpovirk - Pre-size the HashMap based on the number of enum values? (But *not* based on
+ * the number of entries in the map, as that makes it easy for hostile inputs to trigger lots of
+ * allocation—not that any program should be deserializing hostile inputs to begin with!)
+ */
+ setDelegates(new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new HashMap<V, K>());
Serialization.populateMap(this, stream);
}
diff --git a/android/guava/src/com/google/common/collect/EnumMultiset.java b/android/guava/src/com/google/common/collect/EnumMultiset.java
index 57a3a873e..493bcc73a 100644
--- a/android/guava/src/com/google/common/collect/EnumMultiset.java
+++ b/android/guava/src/com/google/common/collect/EnumMultiset.java
@@ -21,6 +21,7 @@ import static com.google.common.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -43,6 +44,7 @@ import javax.annotation.CheckForNull;
* @since 2.0
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumMultiset<E extends Enum<E>> extends AbstractMultiset<E>
implements Serializable {
diff --git a/android/guava/src/com/google/common/collect/EvictingQueue.java b/android/guava/src/com/google/common/collect/EvictingQueue.java
index 5667dfa8c..71770b72a 100644
--- a/android/guava/src/com/google/common/collect/EvictingQueue.java
+++ b/android/guava/src/com/google/common/collect/EvictingQueue.java
@@ -19,8 +19,8 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
@@ -43,7 +43,6 @@ import java.util.Queue;
* @author Kurt Alfred Kluever
* @since 15.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serializable {
@@ -127,6 +126,7 @@ public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serial
}
@Override
+ @J2ktIncompatible // Incompatible return type change. Use inherited implementation
public Object[] toArray() {
/*
* If we could, we'd declare the no-arg `Collection.toArray()` to return "Object[] but elements
diff --git a/android/guava/src/com/google/common/collect/FluentIterable.java b/android/guava/src/com/google/common/collect/FluentIterable.java
index 72401d752..64b5ed1cf 100644
--- a/android/guava/src/com/google/common/collect/FluentIterable.java
+++ b/android/guava/src/com/google/common/collect/FluentIterable.java
@@ -16,7 +16,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
@@ -33,6 +32,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -162,7 +162,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0 (since 18.0 as an overload of {@code of})
*/
- @Beta
public static <E extends @Nullable Object> FluentIterable<E> from(E[] elements) {
return from(Arrays.asList(elements));
}
@@ -195,7 +194,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b) {
return concatNoDefensiveCopy(a, b);
@@ -214,7 +212,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
return concatNoDefensiveCopy(a, b, c);
@@ -234,7 +231,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T> a,
Iterable<? extends T> b,
@@ -258,7 +254,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @throws NullPointerException if any of the provided iterables is {@code null}
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T>... inputs) {
return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
@@ -278,14 +273,13 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
final Iterable<? extends Iterable<? extends T>> inputs) {
checkNotNull(inputs);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
- return Iterators.concat(Iterators.transform(inputs.iterator(), Iterables.<T>toIterator()));
+ return Iterators.concat(Iterators.transform(inputs.iterator(), Iterable::iterator));
}
};
}
@@ -318,7 +312,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <E extends @Nullable Object> FluentIterable<E> of() {
return FluentIterable.from(Collections.<E>emptyList());
}
@@ -331,7 +324,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <E extends @Nullable Object> FluentIterable<E> of(
@ParametricNullness E element, E... elements) {
return from(Lists.asList(element, elements));
@@ -400,7 +392,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 18.0
*/
- @Beta
public final FluentIterable<E> append(Iterable<? extends E> other) {
return FluentIterable.concat(getDelegate(), other);
}
@@ -413,7 +404,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 18.0
*/
- @Beta
public final FluentIterable<E> append(E... elements) {
return FluentIterable.concat(getDelegate(), Arrays.asList(elements));
}
@@ -475,8 +465,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final Optional<E> firstMatch(Predicate<? super E> predicate) {
- return Iterables.tryFind(getDelegate(), predicate);
+ public final Optional<@NonNull E> firstMatch(Predicate<? super E> predicate) {
+ return Iterables.<E>tryFind((Iterable<@NonNull E>) getDelegate(), predicate);
}
/**
@@ -523,9 +513,9 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* iterator().next()} or {@link Iterables#getFirst} instead.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final Optional<E> first() {
+ public final Optional<@NonNull E> first() {
Iterator<E> iterator = getDelegate().iterator();
- return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent();
+ return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.absent();
}
/**
@@ -540,7 +530,7 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* Iterables#getLast} instead.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final Optional<E> last() {
+ public final Optional<@NonNull E> last() {
// Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
// TODO(kevinb): Support a concurrently modified collection?
@@ -580,7 +570,7 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* iterable skips all of its elements.
*
* <p>Modifications to this fluent iterable before a call to {@code iterator()} are reflected in
- * the returned fluent iterable. That is, the its iterator skips the first {@code numberToSkip}
+ * the returned fluent iterable. That is, the iterator skips the first {@code numberToSkip}
* elements that exist when the iterator is created, not when {@code skip()} is called.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of
@@ -630,8 +620,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 12.0 as {@code toImmutableList()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableList<E> toList() {
- return ImmutableList.copyOf(getDelegate());
+ public final ImmutableList<@NonNull E> toList() {
+ return ImmutableList.copyOf((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -648,8 +638,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
- return Ordering.from(comparator).immutableSortedCopy(getDelegate());
+ public final ImmutableList<@NonNull E> toSortedList(Comparator<? super E> comparator) {
+ return Ordering.from(comparator).immutableSortedCopy((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -663,8 +653,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 12.0 as {@code toImmutableSet()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableSet<E> toSet() {
- return ImmutableSet.copyOf(getDelegate());
+ public final ImmutableSet<@NonNull E> toSet() {
+ return ImmutableSet.copyOf((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -682,8 +672,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
- return ImmutableSortedSet.copyOf(comparator, getDelegate());
+ public final ImmutableSortedSet<@NonNull E> toSortedSet(Comparator<? super E> comparator) {
+ return ImmutableSortedSet.copyOf(comparator, (Iterable<@NonNull E>) getDelegate());
}
/**
@@ -696,8 +686,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 19.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableMultiset<E> toMultiset() {
- return ImmutableMultiset.copyOf(getDelegate());
+ public final ImmutableMultiset<@NonNull E> toMultiset() {
+ return ImmutableMultiset.copyOf((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -718,8 +708,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
- return Maps.toMap(getDelegate(), valueFunction);
+ public final <V> ImmutableMap<@NonNull E, V> toMap(Function<? super E, V> valueFunction) {
+ return Maps.toMap((Iterable<@NonNull E>) getDelegate(), valueFunction);
}
/**
@@ -741,8 +731,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
- return Multimaps.index(getDelegate(), keyFunction);
+ public final <K> ImmutableListMultimap<K, @NonNull E> index(Function<? super E, K> keyFunction) {
+ return Multimaps.index((Iterable<@NonNull E>) getDelegate(), keyFunction);
}
/**
@@ -778,8 +768,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
- return Maps.uniqueIndex(getDelegate(), keyFunction);
+ public final <K> ImmutableMap<K, @NonNull E> uniqueIndex(Function<? super E, K> keyFunction) {
+ return Maps.uniqueIndex((Iterable<@NonNull E>) getDelegate(), keyFunction);
}
/**
@@ -795,16 +785,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* copied
*/
@GwtIncompatible // Array.newArray(Class, int)
- /*
- * Both the declaration of our Class<E> parameter and its usage in a call to Iterables.toArray
- * produce a nullness error: E may be a nullable type, and our nullness checker has Class's type
- * parameter bounded to non-null types. To avoid that, we'd use Class<@Nonnull E> if we could.
- * (Granted, this is only one of many nullness-checking problems that arise from letting
- * FluentIterable support null elements, and most of the other produce outright unsoundness.)
- */
- @SuppressWarnings("nullness")
- public final @Nullable E[] toArray(Class<E> type) {
- return Iterables.toArray(getDelegate(), type);
+ public final E[] toArray(Class<@NonNull E> type) {
+ return Iterables.<E>toArray(getDelegate(), type);
}
/**
@@ -842,7 +824,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 18.0
*/
- @Beta
public final String join(Joiner joiner) {
return joiner.join(this);
}
diff --git a/android/guava/src/com/google/common/collect/ForwardingBlockingDeque.java b/android/guava/src/com/google/common/collect/ForwardingBlockingDeque.java
index 49d4bcf6c..13b5b236e 100644
--- a/android/guava/src/com/google/common/collect/ForwardingBlockingDeque.java
+++ b/android/guava/src/com/google/common/collect/ForwardingBlockingDeque.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Collection;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;
@@ -46,6 +47,7 @@ import javax.annotation.CheckForNull;
* com.google.common.util.concurrent.ForwardingBlockingDeque} instead.
*/
@Deprecated
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingDeque<E> extends ForwardingDeque<E>
diff --git a/android/guava/src/com/google/common/collect/ForwardingDeque.java b/android/guava/src/com/google/common/collect/ForwardingDeque.java
index 571535cab..2730dad0e 100644
--- a/android/guava/src/com/google/common/collect/ForwardingDeque.java
+++ b/android/guava/src/com/google/common/collect/ForwardingDeque.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Deque;
import java.util.Iterator;
@@ -40,6 +41,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Kurt Alfred Kluever
* @since 12.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingDeque<E extends @Nullable Object> extends ForwardingQueue<E>
diff --git a/android/guava/src/com/google/common/collect/ForwardingList.java b/android/guava/src/com/google/common/collect/ForwardingList.java
index 4b4551e5e..e9b4d8e35 100644
--- a/android/guava/src/com/google/common/collect/ForwardingList.java
+++ b/android/guava/src/com/google/common/collect/ForwardingList.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
@@ -204,7 +203,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected ListIterator<E> standardListIterator(int start) {
return Lists.listIteratorImpl(this, start);
}
@@ -215,7 +213,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected List<E> standardSubList(int fromIndex, int toIndex) {
return Lists.subListImpl(this, fromIndex, toIndex);
}
@@ -227,7 +224,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected boolean standardEquals(@CheckForNull Object object) {
return Lists.equalsImpl(this, object);
}
@@ -239,7 +235,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected int standardHashCode() {
return Lists.hashCodeImpl(this);
}
diff --git a/android/guava/src/com/google/common/collect/ForwardingMap.java b/android/guava/src/com/google/common/collect/ForwardingMap.java
index 315a4fabc..24c40f23c 100644
--- a/android/guava/src/com/google/common/collect/ForwardingMap.java
+++ b/android/guava/src/com/google/common/collect/ForwardingMap.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -163,7 +162,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 7.0
*/
- @Beta
@CheckForNull
protected V standardRemove(@CheckForNull Object key) {
Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
@@ -198,7 +196,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 10.0
*/
- @Beta
protected class StandardKeySet extends Maps.KeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardKeySet() {
@@ -213,7 +210,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 7.0
*/
- @Beta
protected boolean standardContainsKey(@CheckForNull Object key) {
return Maps.containsKeyImpl(this, key);
}
@@ -227,7 +223,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 10.0
*/
- @Beta
protected class StandardValues extends Maps.Values<K, V> {
/** Constructor for use by subclasses. */
public StandardValues() {
@@ -255,10 +250,9 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 10.0
*/
- @Beta
protected abstract class StandardEntrySet extends Maps.EntrySet<K, V> {
/** Constructor for use by subclasses. */
- public StandardEntrySet() {}
+ protected StandardEntrySet() {}
@Override
Map<K, V> map() {
diff --git a/android/guava/src/com/google/common/collect/ForwardingMapEntry.java b/android/guava/src/com/google/common/collect/ForwardingMapEntry.java
index 6816ccbbe..2faa65152 100644
--- a/android/guava/src/com/google/common/collect/ForwardingMapEntry.java
+++ b/android/guava/src/com/google/common/collect/ForwardingMapEntry.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Map;
@@ -123,7 +122,6 @@ public abstract class ForwardingMapEntry<K extends @Nullable Object, V extends @
*
* @since 7.0
*/
- @Beta
protected String standardToString() {
return getKey() + "=" + getValue();
}
diff --git a/android/guava/src/com/google/common/collect/ForwardingMultiset.java b/android/guava/src/com/google/common/collect/ForwardingMultiset.java
index 857b9aec7..d1187d4c5 100644
--- a/android/guava/src/com/google/common/collect/ForwardingMultiset.java
+++ b/android/guava/src/com/google/common/collect/ForwardingMultiset.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -138,7 +137,6 @@ public abstract class ForwardingMultiset<E extends @Nullable Object> extends For
*
* @since 7.0
*/
- @Beta
protected int standardCount(@CheckForNull Object object) {
for (Entry<?> entry : this.entrySet()) {
if (Objects.equal(entry.getElement(), object)) {
@@ -167,7 +165,6 @@ public abstract class ForwardingMultiset<E extends @Nullable Object> extends For
*
* @since 7.0
*/
- @Beta
@Override
protected boolean standardAddAll(Collection<? extends E> elementsToAdd) {
return Multisets.addAllImpl(this, elementsToAdd);
@@ -243,7 +240,6 @@ public abstract class ForwardingMultiset<E extends @Nullable Object> extends For
*
* @since 10.0
*/
- @Beta
protected class StandardElementSet extends Multisets.ElementSet<E> {
/** Constructor for use by subclasses. */
public StandardElementSet() {}
diff --git a/android/guava/src/com/google/common/collect/ForwardingNavigableMap.java b/android/guava/src/com/google/common/collect/ForwardingNavigableMap.java
index e0e1c39e8..87ebc9898 100644
--- a/android/guava/src/com/google/common/collect/ForwardingNavigableMap.java
+++ b/android/guava/src/com/google/common/collect/ForwardingNavigableMap.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.collect.Maps.keyOrNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import java.util.Iterator;
import java.util.NavigableMap;
@@ -206,7 +205,7 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*/
@CheckForNull
protected Entry<K, V> standardFirstEntry() {
- return Iterables.getFirst(entrySet(), null);
+ return Iterables.<@Nullable Entry<K, V>>getFirst(entrySet(), null);
}
/**
@@ -236,7 +235,7 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*/
@CheckForNull
protected Entry<K, V> standardLastEntry() {
- return Iterables.getFirst(descendingMap().entrySet(), null);
+ return Iterables.<@Nullable Entry<K, V>>getFirst(descendingMap().entrySet(), null);
}
/**
@@ -300,7 +299,6 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*
* @since 12.0
*/
- @Beta
protected class StandardDescendingMap extends Maps.DescendingMap<K, V> {
/** Constructor for use by subclasses. */
public StandardDescendingMap() {}
@@ -359,7 +357,6 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*
* @since 12.0
*/
- @Beta
protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardNavigableKeySet() {
@@ -379,7 +376,6 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
* descendingMap}, you may wish to override {@code descendingKeySet} to forward to this
* implementation.
*/
- @Beta
protected NavigableSet<K> standardDescendingKeySet() {
return descendingMap().navigableKeySet();
}
diff --git a/android/guava/src/com/google/common/collect/ForwardingNavigableSet.java b/android/guava/src/com/google/common/collect/ForwardingNavigableSet.java
index 6822aa87d..97f137a59 100644
--- a/android/guava/src/com/google/common/collect/ForwardingNavigableSet.java
+++ b/android/guava/src/com/google/common/collect/ForwardingNavigableSet.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import java.util.Iterator;
import java.util.NavigableSet;
@@ -181,7 +180,6 @@ public abstract class ForwardingNavigableSet<E extends @Nullable Object>
*
* @since 12.0
*/
- @Beta
protected class StandardDescendingSet extends Sets.DescendingSet<E> {
/** Constructor for use by subclasses. */
public StandardDescendingSet() {
@@ -208,7 +206,6 @@ public abstract class ForwardingNavigableSet<E extends @Nullable Object>
* {@code headSet} and {@code tailSet} methods. In many cases, you may wish to override {@link
* #subSet(Object, boolean, Object, boolean)} to forward to this implementation.
*/
- @Beta
protected NavigableSet<E> standardSubSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
diff --git a/android/guava/src/com/google/common/collect/ForwardingSortedMap.java b/android/guava/src/com/google/common/collect/ForwardingSortedMap.java
index e0882abc7..9779b97a7 100644
--- a/android/guava/src/com/google/common/collect/ForwardingSortedMap.java
+++ b/android/guava/src/com/google/common/collect/ForwardingSortedMap.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.NoSuchElementException;
@@ -103,7 +102,6 @@ public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends
*
* @since 15.0
*/
- @Beta
protected class StandardKeySet extends Maps.SortedKeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardKeySet() {
@@ -130,7 +128,6 @@ public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends
* @since 7.0
*/
@Override
- @Beta
protected boolean standardContainsKey(@CheckForNull Object key) {
try {
// any CCE or NPE will be caught
@@ -150,7 +147,6 @@ public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends
*
* @since 7.0
*/
- @Beta
protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
checkArgument(unsafeCompare(comparator(), fromKey, toKey) <= 0, "fromKey must be <= toKey");
return tailMap(fromKey).headMap(toKey);
diff --git a/android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java b/android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
index 4626d3193..777735741 100644
--- a/android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
+++ b/android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
@@ -14,7 +14,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
@@ -44,7 +43,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
* @since 15.0
*/
-@Beta
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public abstract class ForwardingSortedMultiset<E extends @Nullable Object>
diff --git a/android/guava/src/com/google/common/collect/ForwardingSortedSet.java b/android/guava/src/com/google/common/collect/ForwardingSortedSet.java
index 32625afd1..ad7ef1223 100644
--- a/android/guava/src/com/google/common/collect/ForwardingSortedSet.java
+++ b/android/guava/src/com/google/common/collect/ForwardingSortedSet.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.collect.ForwardingSortedMap.unsafeCompare;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
@@ -106,7 +105,6 @@ public abstract class ForwardingSortedSet<E extends @Nullable Object> extends Fo
* @since 7.0
*/
@Override
- @Beta
protected boolean standardContains(@CheckForNull Object object) {
try {
// any ClassCastExceptions and NullPointerExceptions are caught
@@ -127,7 +125,6 @@ public abstract class ForwardingSortedSet<E extends @Nullable Object> extends Fo
* @since 7.0
*/
@Override
- @Beta
protected boolean standardRemove(@CheckForNull Object object) {
try {
// any ClassCastExceptions and NullPointerExceptions are caught
@@ -154,7 +151,6 @@ public abstract class ForwardingSortedSet<E extends @Nullable Object> extends Fo
*
* @since 7.0
*/
- @Beta
protected SortedSet<E> standardSubSet(
@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return tailSet(fromElement).headSet(toElement);
diff --git a/android/guava/src/com/google/common/collect/GeneralRange.java b/android/guava/src/com/google/common/collect/GeneralRange.java
index 3d7256ff8..e462b7a01 100644
--- a/android/guava/src/com/google/common/collect/GeneralRange.java
+++ b/android/guava/src/com/google/common/collect/GeneralRange.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Comparator;
import javax.annotation.CheckForNull;
@@ -122,12 +123,14 @@ final class GeneralRange<T extends @Nullable Object> implements Serializable {
* whenever they pass `true` for the matching `has*Bound` parameter.
*/
if (hasLowerBound) {
- comparator.compare(
- uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint));
+ int unused =
+ comparator.compare(
+ uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint));
}
if (hasUpperBound) {
- comparator.compare(
- uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint));
+ int unused =
+ comparator.compare(
+ uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint));
}
if (hasLowerBound && hasUpperBound) {
@@ -261,7 +264,7 @@ final class GeneralRange<T extends @Nullable Object> implements Serializable {
getUpperBoundType());
}
- @CheckForNull private transient GeneralRange<T> reverse;
+ @LazyInit @CheckForNull private transient GeneralRange<T> reverse;
/** Returns the same range relative to the reversed comparator. */
GeneralRange<T> reverse() {
diff --git a/android/guava/src/com/google/common/collect/HashBiMap.java b/android/guava/src/com/google/common/collect/HashBiMap.java
index 8639cb071..a2933a5cd 100644
--- a/android/guava/src/com/google/common/collect/HashBiMap.java
+++ b/android/guava/src/com/google/common/collect/HashBiMap.java
@@ -20,6 +20,7 @@ import static com.google.common.collect.NullnessCasts.unsafeNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
@@ -749,7 +750,7 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- private transient Set<K> keySet;
+ @LazyInit private transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -787,7 +788,7 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- private transient Set<V> valueSet;
+ @LazyInit private transient Set<V> valueSet;
@Override
public Set<V> values() {
@@ -825,7 +826,7 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- private transient Set<Entry<K, V>> entrySet;
+ @LazyInit private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -1134,12 +1135,14 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
* @serialData the number of entries, first key, first value, second key, second value, and so on.
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int size = Serialization.readCount(stream);
diff --git a/android/guava/src/com/google/common/collect/HashMultimap.java b/android/guava/src/com/google/common/collect/HashMultimap.java
index 9e4c1c223..51567cdce 100644
--- a/android/guava/src/com/google/common/collect/HashMultimap.java
+++ b/android/guava/src/com/google/common/collect/HashMultimap.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.io.IOException;
@@ -131,12 +132,14 @@ public final class HashMultimap<K extends @Nullable Object, V extends @Nullable
* key, number of values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
@@ -147,5 +150,6 @@ public final class HashMultimap<K extends @Nullable Object, V extends @Nullable
}
@GwtIncompatible // Not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/HashMultiset.java b/android/guava/src/com/google/common/collect/HashMultiset.java
index 0748e68be..0bc4ccac4 100644
--- a/android/guava/src/com/google/common/collect/HashMultiset.java
+++ b/android/guava/src/com/google/common/collect/HashMultiset.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -71,5 +72,6 @@ public final class HashMultiset<E extends @Nullable Object> extends AbstractMapB
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/IgnoreJRERequirement.java b/android/guava/src/com/google/common/collect/IgnoreJRERequirement.java
new file mode 100644
index 000000000..2a1006831
--- /dev/null
+++ b/android/guava/src/com/google/common/collect/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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 static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/android/guava/src/com/google/common/collect/ImmutableAsList.java b/android/guava/src/com/google/common/collect/ImmutableAsList.java
index c39747931..b7c585cc2 100644
--- a/android/guava/src/com/google/common/collect/ImmutableAsList.java
+++ b/android/guava/src/com/google/common/collect/ImmutableAsList.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
@@ -60,6 +61,7 @@ abstract class ImmutableAsList<E> extends ImmutableList<E> {
/** Serialized form that leads to the same performance as the original list. */
@GwtIncompatible // serialization
+ @J2ktIncompatible
static class SerializedForm implements Serializable {
final ImmutableCollection<?> collection;
@@ -75,11 +77,13 @@ abstract class ImmutableAsList<E> extends ImmutableList<E> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm(delegateCollection());
diff --git a/android/guava/src/com/google/common/collect/ImmutableBiMap.java b/android/guava/src/com/google/common/collect/ImmutableBiMap.java
index 1de5bd10f..30e293ebf 100644
--- a/android/guava/src/com/google/common/collect/ImmutableBiMap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableBiMap.java
@@ -19,10 +19,12 @@ package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
@@ -294,7 +296,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements
*
* @since 23.1
*/
- @Beta
public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<>(expectedSize);
@@ -386,7 +387,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -404,7 +404,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
super.orderEntriesByValue(valueComparator);
@@ -512,7 +511,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableBiMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
int estimatedSize =
@@ -569,6 +567,7 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements
* <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
* bimap and its inverse in sync during serialization, the way AbstractBiMap does.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
SerializedForm(ImmutableBiMap<K, V> bimap) {
super(bimap);
@@ -583,7 +582,13 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
+
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java b/android/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
index c59e9fdab..0ad82e917 100644
--- a/android/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
@@ -26,6 +26,7 @@ import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A {@link ClassToInstanceMap} whose contents will never change, with many other important
@@ -37,7 +38,9 @@ import javax.annotation.CheckForNull;
@Immutable(containerOf = "B")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
-public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B>
+// TODO(b/278589132): Remove the redundant "@NonNull" on B once it's no longer required by J2KT.
+public final class ImmutableClassToInstanceMap<B>
+ extends ForwardingMap<Class<? extends @NonNull B>, B>
implements ClassToInstanceMap<B>, Serializable {
private static final ImmutableClassToInstanceMap<Object> EMPTY =
@@ -120,7 +123,7 @@ public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<?
return this;
}
- private static <B, T extends B> T cast(Class<T> type, B value) {
+ private static <T> T cast(Class<T> type, Object value) {
return Primitives.wrap(type).cast(value);
}
@@ -154,8 +157,10 @@ public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<?
public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf(
Map<? extends Class<? extends S>, ? extends S> map) {
if (map instanceof ImmutableClassToInstanceMap) {
+ @SuppressWarnings("rawtypes") // JDT-based J2KT Java frontend does not permit the direct cast
+ Map rawMap = map;
@SuppressWarnings("unchecked") // covariant casts safe (unmodifiable)
- ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap<B>) map;
+ ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap<B>) rawMap;
return cast;
}
return new Builder<B>().putAll(map).build();
diff --git a/android/guava/src/com/google/common/collect/ImmutableCollection.java b/android/guava/src/com/google/common/collect/ImmutableCollection.java
index d5420e040..4ef25aa78 100644
--- a/android/guava/src/com/google/common/collect/ImmutableCollection.java
+++ b/android/guava/src/com/google/common/collect/ImmutableCollection.java
@@ -21,9 +21,12 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Arrays;
@@ -177,6 +180,7 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
private static final Object[] EMPTY_ARRAY = {};
@Override
+ @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation
public final Object[] toArray() {
return toArray(EMPTY_ARRAY);
}
@@ -356,11 +360,17 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
return offset;
}
+ @J2ktIncompatible // serialization
Object writeReplace() {
// We serialize by default to ImmutableList, the simplest thing that works.
return new ImmutableList.SerializedForm(toArray());
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/**
* Abstract base class for builders of {@link ImmutableCollection} types.
*
diff --git a/android/guava/src/com/google/common/collect/ImmutableEntry.java b/android/guava/src/com/google/common/collect/ImmutableEntry.java
index edc25f490..f88fcc1c6 100644
--- a/android/guava/src/com/google/common/collect/ImmutableEntry.java
+++ b/android/guava/src/com/google/common/collect/ImmutableEntry.java
@@ -20,7 +20,11 @@ import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import org.checkerframework.checker.nullness.qual.Nullable;
-/** @see com.google.common.collect.Maps#immutableEntry(Object, Object) */
+/**
+ * An immutable {@code Map.Entry}, used both by {@link
+ * com.google.common.collect.Maps#immutableEntry(Object, Object)} and by other parts of {@code
+ * common.collect} as a superclass.
+ */
@GwtCompatible(serializable = true)
@ElementTypesAreNonnullByDefault
class ImmutableEntry<K extends @Nullable Object, V extends @Nullable Object>
diff --git a/android/guava/src/com/google/common/collect/ImmutableEnumMap.java b/android/guava/src/com/google/common/collect/ImmutableEnumMap.java
index 66680f0e9..72b97d241 100644
--- a/android/guava/src/com/google/common/collect/ImmutableEnumMap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableEnumMap.java
@@ -19,7 +19,10 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMap.IteratorBasedImmutableMap;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.EnumMap;
import javax.annotation.CheckForNull;
@@ -96,13 +99,20 @@ final class ImmutableEnumMap<K extends Enum<K>, V> extends IteratorBasedImmutabl
// All callers of the constructor are restricted to <K extends Enum<K>>.
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new EnumSerializedForm<>(delegate);
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use EnumSerializedForm");
+ }
+
/*
* This class is used to serialize ImmutableEnumMap instances.
*/
+ @J2ktIncompatible // serialization
private static class EnumSerializedForm<K extends Enum<K>, V> implements Serializable {
final EnumMap<K, V> delegate;
diff --git a/android/guava/src/com/google/common/collect/ImmutableEnumSet.java b/android/guava/src/com/google/common/collect/ImmutableEnumSet.java
index 90787e5d6..2f042f85f 100644
--- a/android/guava/src/com/google/common/collect/ImmutableEnumSet.java
+++ b/android/guava/src/com/google/common/collect/ImmutableEnumSet.java
@@ -17,7 +17,10 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.EnumSet;
@@ -32,15 +35,14 @@ import javax.annotation.CheckForNull;
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
- @SuppressWarnings("rawtypes") // necessary to compile against Java 8
- static ImmutableSet asImmutable(EnumSet set) {
+ static <E extends Enum<E>> ImmutableSet<E> asImmutable(EnumSet<E> set) {
switch (set.size()) {
case 0:
return ImmutableSet.of();
case 1:
return ImmutableSet.of(Iterables.getOnlyElement(set));
default:
- return new ImmutableEnumSet(set);
+ return new ImmutableEnumSet<E>(set);
}
}
@@ -122,13 +124,20 @@ final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
// All callers of the constructor are restricted to <E extends Enum<E>>.
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new EnumSerializedForm<E>(delegate);
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
+ @J2ktIncompatible // serialization
private static class EnumSerializedForm<E extends Enum<E>> implements Serializable {
final EnumSet<E> delegate;
diff --git a/android/guava/src/com/google/common/collect/ImmutableList.java b/android/guava/src/com/google/common/collect/ImmutableList.java
index e336424f6..f201a437e 100644
--- a/android/guava/src/com/google/common/collect/ImmutableList.java
+++ b/android/guava/src/com/google/common/collect/ImmutableList.java
@@ -25,8 +25,8 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import static com.google.common.collect.RegularImmutableList.EMPTY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.InlineMe;
@@ -232,8 +232,8 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
*
* <p>Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)}
* returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while
- * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one element
- * (the given list itself).
+ * {@code ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one
+ * element (the given list itself).
*
* <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
* collection that is currently being modified by another thread.
@@ -655,6 +655,7 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
* Serializes ImmutableLists as their logical contents. This ensures that
* implementation types do not leak into the serialized representation.
*/
+ @J2ktIncompatible // serialization
static class SerializedForm implements Serializable {
final Object[] elements;
@@ -669,11 +670,13 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
private static final long serialVersionUID = 0;
}
+ @J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm(toArray());
}
@@ -698,7 +701,6 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
*
* @since 23.1
*/
- @Beta
public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new ImmutableList.Builder<E>(expectedSize);
diff --git a/android/guava/src/com/google/common/collect/ImmutableListMultimap.java b/android/guava/src/com/google/common/collect/ImmutableListMultimap.java
index 20408db80..fbc8ce2f5 100644
--- a/android/guava/src/com/google/common/collect/ImmutableListMultimap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableListMultimap.java
@@ -16,9 +16,9 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
@@ -32,7 +32,6 @@ import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.CheckForNull;
-import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link ListMultimap} whose contents will never change, with many other important properties
@@ -168,7 +167,6 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -271,7 +269,6 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableListMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return new Builder<K, V>().putAll(entries).build();
@@ -280,7 +277,7 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
/** Creates an ImmutableListMultimap from an asMap.entrySet. */
static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
- @Nullable Comparator<? super V> valueComparator) {
+ @CheckForNull Comparator<? super V> valueComparator) {
if (mapEntries.isEmpty()) {
return of();
}
@@ -382,12 +379,14 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
* values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int keyCount = stream.readInt();
@@ -424,5 +423,6 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
}
@GwtIncompatible // Not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableMap.java b/android/guava/src/com/google/common/collect/ImmutableMap.java
index 1746ae0b4..94484a0d5 100644
--- a/android/guava/src/com/google/common/collect/ImmutableMap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableMap.java
@@ -22,14 +22,16 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.WeakOuter;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Arrays;
@@ -333,7 +335,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
*
* @since 23.1
*/
- @Beta
public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<>(expectedSize);
@@ -467,7 +468,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
if (entries instanceof Collection) {
ensureCapacity(size + ((Collection<?>) entries).size());
@@ -489,7 +489,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
checkState(this.valueComparator == null, "valueComparator was already set");
this.valueComparator = checkNotNull(valueComparator, "valueComparator");
@@ -695,7 +694,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* @throws IllegalArgumentException if two entries have the same key
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
int initialCapacity =
@@ -1046,6 +1044,7 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* reconstructed using public factory methods. This ensures that the implementation types remain
* as implementation details.
*/
+ @J2ktIncompatible // serialization
static class SerializedForm<K, V> implements Serializable {
// This object retains references to collections returned by keySet() and value(). This saves
// bytes when the both the map and its keySet or value collection are written to the same
@@ -1125,7 +1124,13 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* method. Publicly-accessible subclasses must override this method and should return a subclass
* of SerializedForm whose readResolve() method returns objects of the subclass type.
*/
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableMapEntrySet.java b/android/guava/src/com/google/common/collect/ImmutableMapEntrySet.java
index 7ae6422e2..3732e2dfe 100644
--- a/android/guava/src/com/google/common/collect/ImmutableMapEntrySet.java
+++ b/android/guava/src/com/google/common/collect/ImmutableMapEntrySet.java
@@ -18,6 +18,9 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Map.Entry;
import javax.annotation.CheckForNull;
@@ -103,12 +106,20 @@ abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new EntrySetSerializedForm<>(map());
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use EntrySetSerializedForm");
+ }
+
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
private static class EntrySetSerializedForm<K, V> implements Serializable {
final ImmutableMap<K, V> map;
diff --git a/android/guava/src/com/google/common/collect/ImmutableMapKeySet.java b/android/guava/src/com/google/common/collect/ImmutableMapKeySet.java
index 9bd1d4338..056a35141 100644
--- a/android/guava/src/com/google/common/collect/ImmutableMapKeySet.java
+++ b/android/guava/src/com/google/common/collect/ImmutableMapKeySet.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
@@ -68,6 +69,7 @@ final class ImmutableMapKeySet<K, V> extends IndexedImmutableSet<K> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private static class KeySetSerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
diff --git a/android/guava/src/com/google/common/collect/ImmutableMapValues.java b/android/guava/src/com/google/common/collect/ImmutableMapValues.java
index 8b7284d1e..ba868d1b9 100644
--- a/android/guava/src/com/google/common/collect/ImmutableMapValues.java
+++ b/android/guava/src/com/google/common/collect/ImmutableMapValues.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
import javax.annotation.CheckForNull;
@@ -97,6 +98,7 @@ final class ImmutableMapValues<K, V> extends ImmutableCollection<V> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
diff --git a/android/guava/src/com/google/common/collect/ImmutableMultimap.java b/android/guava/src/com/google/common/collect/ImmutableMultimap.java
index fa1f3a4c2..e4ad391f5 100644
--- a/android/guava/src/com/google/common/collect/ImmutableMultimap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableMultimap.java
@@ -21,14 +21,16 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.Maps.immutableEntry;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
@@ -191,7 +193,6 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
for (Entry<? extends K, ? extends V> entry : entries) {
put(entry);
@@ -329,7 +330,6 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return ImmutableListMultimap.copyOf(entries);
@@ -342,6 +342,7 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
// holder class makes sure they are not initialized unless an instance is
// deserialized.
@GwtIncompatible // java serialization is not supported
+ @J2ktIncompatible
static class FieldSettersHolder {
static final Serialization.FieldSetter<ImmutableMultimap> MAP_FIELD_SETTER =
Serialization.getFieldSetter(ImmutableMultimap.class, "map");
@@ -658,13 +659,21 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
}
@GwtIncompatible
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new KeysSerializedForm(ImmutableMultimap.this);
}
+
+ @GwtIncompatible
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use KeysSerializedForm");
+ }
}
@GwtIncompatible
+ @J2ktIncompatible
private static final class KeysSerializedForm implements Serializable {
final ImmutableMultimap<?, ?> multimap;
@@ -748,8 +757,10 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
return true;
}
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableMultiset.java b/android/guava/src/com/google/common/collect/ImmutableMultiset.java
index ab281d4b3..ecb8ae45b 100644
--- a/android/guava/src/com/google/common/collect/ImmutableMultiset.java
+++ b/android/guava/src/com/google/common/collect/ImmutableMultiset.java
@@ -21,10 +21,13 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -360,15 +363,23 @@ public abstract class ImmutableMultiset<E> extends ImmutableMultisetGwtSerializa
}
@GwtIncompatible
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
}
- private static final long serialVersionUID = 0;
+ @GwtIncompatible
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use EntrySetSerializedForm");
+ }
+
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
@GwtIncompatible
+ @J2ktIncompatible
static class EntrySetSerializedForm<E> implements Serializable {
final ImmutableMultiset<E> multiset;
@@ -382,9 +393,16 @@ public abstract class ImmutableMultiset<E> extends ImmutableMultisetGwtSerializa
}
@GwtIncompatible
+ @J2ktIncompatible
@Override
abstract Object writeReplace();
+ @GwtIncompatible
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
diff --git a/android/guava/src/com/google/common/collect/ImmutableRangeMap.java b/android/guava/src/com/google/common/collect/ImmutableRangeMap.java
index 8a4779619..710c8916e 100644
--- a/android/guava/src/com/google/common/collect/ImmutableRangeMap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableRangeMap.java
@@ -18,13 +18,15 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
@@ -40,7 +42,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K, V>, Serializable {
@@ -241,7 +242,7 @@ public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
- public final void putAll(RangeMap<K, V> rangeMap) {
+ public final void putAll(RangeMap<K, ? extends V> rangeMap) {
throw new UnsupportedOperationException();
}
@@ -406,5 +407,10 @@ public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K
return new SerializedForm<>(asMapOfRanges());
}
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableRangeSet.java b/android/guava/src/com/google/common/collect/ImmutableRangeSet.java
index a0eb5b5ef..844c1c1dc 100644
--- a/android/guava/src/com/google/common/collect/ImmutableRangeSet.java
+++ b/android/guava/src/com/google/common/collect/ImmutableRangeSet.java
@@ -22,14 +22,16 @@ import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER
import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
@@ -45,7 +47,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ImmutableRangeSet<C extends Comparable> extends AbstractRangeSet<C>
@@ -504,7 +505,7 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
* such a set can be performed efficiently, but others (such as {@link Set#hashCode} or {@link
* Collections#frequency}) can cause major performance problems.
*
- * <p>The returned set's {@link Object#toString} method returns a short-hand form of the set's
+ * <p>The returned set's {@link Object#toString} method returns a shorthand form of the set's
* contents, such as {@code "[1..100]}"}.
*
* @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if
@@ -541,7 +542,7 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
this.domain = domain;
}
- @CheckForNull private transient Integer size;
+ @LazyInit @CheckForNull private transient Integer size;
@Override
public int size() {
@@ -677,9 +678,15 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new AsSetSerializedForm<C>(ranges, domain);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
private static class AsSetSerializedForm<C extends Comparable> implements Serializable {
@@ -826,7 +833,13 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
}
}
+ @J2ktIncompatible // java.io.ObjectInputStream
Object writeReplace() {
return new SerializedForm<C>(ranges);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableSet.java b/android/guava/src/com/google/common/collect/ImmutableSet.java
index 1ff54e205..6d9f167bc 100644
--- a/android/guava/src/com/google/common/collect/ImmutableSet.java
+++ b/android/guava/src/com/google/common/collect/ImmutableSet.java
@@ -22,13 +22,15 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.ObjectArrays.checkElementNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -365,6 +367,7 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
* static factories. This is necessary to ensure that the existence of a
* particular implementation type is an implementation detail.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm implements Serializable {
final Object[] elements;
@@ -380,10 +383,16 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm(toArray());
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
@@ -404,7 +413,6 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
*
* @since 23.1
*/
- @Beta
public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<E>(expectedSize);
diff --git a/android/guava/src/com/google/common/collect/ImmutableSetMultimap.java b/android/guava/src/com/google/common/collect/ImmutableSetMultimap.java
index 1f655e27a..354a7c55f 100644
--- a/android/guava/src/com/google/common/collect/ImmutableSetMultimap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableSetMultimap.java
@@ -18,9 +18,9 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
@@ -193,7 +193,6 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -316,7 +315,6 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableSetMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return new Builder<K, V>().putAll(entries).build();
@@ -496,6 +494,7 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
* values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(valueComparator());
@@ -510,12 +509,14 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
}
@GwtIncompatible // java serialization
+ @J2ktIncompatible
private static final class SetFieldSettersHolder {
static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
// Serialization type safety is at the caller's mercy.
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
@@ -560,5 +561,6 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
}
@GwtIncompatible // not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableSortedMap.java b/android/guava/src/com/google/common/collect/ImmutableSortedMap.java
index 709504eb2..15c384eb7 100644
--- a/android/guava/src/com/google/common/collect/ImmutableSortedMap.java
+++ b/android/guava/src/com/google/common/collect/ImmutableSortedMap.java
@@ -22,10 +22,12 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.Maps.keyOrNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Comparator;
@@ -356,7 +358,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @throws IllegalArgumentException if any two keys are equal according to the comparator
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
// Hack around K not being a subtype of Comparable.
@@ -374,7 +375,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @throws IllegalArgumentException if any two keys are equal according to the comparator
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries,
Comparator<? super K> comparator) {
@@ -488,14 +488,11 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
entryArray,
0,
size,
- new Comparator<@Nullable Entry<K, V>>() {
- @Override
- public int compare(@CheckForNull Entry<K, V> e1, @CheckForNull Entry<K, V> e2) {
- // requireNonNull is safe because the first `size` elements have been filled in.
- requireNonNull(e1);
- requireNonNull(e2);
- return comparator.compare(e1.getKey(), e2.getKey());
- }
+ (e1, e2) -> {
+ // requireNonNull is safe because the first `size` elements have been filled in.
+ requireNonNull(e1);
+ requireNonNull(e2);
+ return comparator.compare(e1.getKey(), e2.getKey());
});
// requireNonNull is safe because the first `size` elements have been filled in.
Entry<K, V> firstEntry = requireNonNull(entryArray[0]);
@@ -547,7 +544,7 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* their natural ordering.
*/
public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
- return new Builder<>(Ordering.natural().reverse());
+ return new Builder<>(Ordering.<K>natural().reverse());
}
/**
@@ -652,7 +649,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -666,7 +662,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @deprecated Unsupported by ImmutableSortedMap.Builder.
*/
@CanIgnoreReturnValue
- @Beta
@Override
@Deprecated
@DoNotCall("Always throws UnsupportedOperationException")
@@ -1088,16 +1083,18 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
@Override
public ImmutableSortedMap<K, V> descendingMap() {
- // TODO(kevinb): the descendingMap is never actually cached at all. Either it should be or the
- // code below simplified.
+ // TODO(kevinb): The descendingMap is never actually cached at all. Either:
+ //
+ // - Cache it, and annotate the field with @LazyInit.
+ // - Simplify the code below, and consider eliminating the field (b/287198172), which is also
+ // set by one of the constructors.
ImmutableSortedMap<K, V> result = descendingMap;
if (result == null) {
if (isEmpty()) {
- return result = emptyMap(Ordering.from(comparator()).reverse());
+ return emptyMap(Ordering.from(comparator()).reverse());
} else {
- return result =
- new ImmutableSortedMap<>(
- (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this);
+ return new ImmutableSortedMap<>(
+ (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this);
}
}
return result;
@@ -1118,6 +1115,7 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* are reconstructed using public factory methods. This ensures that the implementation types
* remain as implementation details.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
private final Comparator<? super K> comparator;
@@ -1135,10 +1133,16 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
diff --git a/android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java b/android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
index 2889a50cc..ba6cb4313 100644
--- a/android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
+++ b/android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
@@ -18,11 +18,14 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -369,7 +372,7 @@ public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultiset
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>.
*/
public static <E extends Comparable<?>> Builder<E> reverseOrder() {
- return new Builder<E>(Ordering.natural().reverse());
+ return new Builder<E>(Ordering.<E>natural().reverse());
}
/**
@@ -638,6 +641,7 @@ public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultiset
}
}
+ @J2ktIncompatible // serialization
private static final class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final E[] elements;
@@ -668,7 +672,13 @@ public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultiset
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<E>(this);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableSortedSet.java b/android/guava/src/com/google/common/collect/ImmutableSortedSet.java
index a21227deb..cf814d712 100644
--- a/android/guava/src/com/google/common/collect/ImmutableSortedSet.java
+++ b/android/guava/src/com/google/common/collect/ImmutableSortedSet.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
@@ -627,21 +628,21 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
@Override
@CheckForNull
public E lower(E e) {
- return Iterators.getNext(headSet(e, false).descendingIterator(), null);
+ return Iterators.<@Nullable E>getNext(headSet(e, false).descendingIterator(), null);
}
/** @since 12.0 */
@Override
@CheckForNull
public E floor(E e) {
- return Iterators.getNext(headSet(e, true).descendingIterator(), null);
+ return Iterators.<@Nullable E>getNext(headSet(e, true).descendingIterator(), null);
}
/** @since 12.0 */
@Override
@CheckForNull
public E ceiling(E e) {
- return Iterables.getFirst(tailSet(e, true), null);
+ return Iterables.<@Nullable E>getFirst(tailSet(e, true), null);
}
/** @since 12.0 */
@@ -649,7 +650,7 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
@Override
@CheckForNull
public E higher(E e) {
- return Iterables.getFirst(tailSet(e, false), null);
+ return Iterables.<@Nullable E>getFirst(tailSet(e, false), null);
}
@Override
@@ -734,6 +735,7 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
* only. This is necessary to ensure that the existence of a particular
* implementation type is an implementation detail.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final Object[] elements;
@@ -751,11 +753,13 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
private static final long serialVersionUID = 0;
}
+ @J2ktIncompatible // serialization
private void readObject(ObjectInputStream unused) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<E>(comparator, toArray());
}
diff --git a/android/guava/src/com/google/common/collect/ImmutableTable.java b/android/guava/src/com/google/common/collect/ImmutableTable.java
index 224df09c5..9c45e361f 100644
--- a/android/guava/src/com/google/common/collect/ImmutableTable.java
+++ b/android/guava/src/com/google/common/collect/ImmutableTable.java
@@ -19,10 +19,14 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
@@ -453,4 +457,12 @@ public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V>
final Object writeReplace() {
return createSerializedForm();
}
+
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
+ private static final long serialVersionUID = 0xdecaf;
}
diff --git a/android/guava/src/com/google/common/collect/Interner.java b/android/guava/src/com/google/common/collect/Interner.java
index bfc2035f1..8b48fcded 100644
--- a/android/guava/src/com/google/common/collect/Interner.java
+++ b/android/guava/src/com/google/common/collect/Interner.java
@@ -17,7 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
/**
@@ -32,6 +32,7 @@ import com.google.errorprone.annotations.DoNotMock;
* @since 3.0
*/
@DoNotMock("Use Interners.new*Interner")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface Interner<E> {
@@ -47,6 +48,5 @@ public interface Interner<E> {
*
* @throws NullPointerException if {@code sample} is null
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Consider removing this?
E intern(E sample);
}
diff --git a/android/guava/src/com/google/common/collect/Interners.java b/android/guava/src/com/google/common/collect/Interners.java
index 10ae27463..449806b43 100644
--- a/android/guava/src/com/google/common/collect/Interners.java
+++ b/android/guava/src/com/google/common/collect/Interners.java
@@ -17,6 +17,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
@@ -30,6 +31,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 3.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Interners {
diff --git a/android/guava/src/com/google/common/collect/Iterables.java b/android/guava/src/com/google/common/collect/Iterables.java
index 08f8d45a1..5fc18f8ae 100644
--- a/android/guava/src/com/google/common/collect/Iterables.java
+++ b/android/guava/src/com/google/common/collect/Iterables.java
@@ -20,7 +20,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkRemove;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
@@ -37,6 +36,7 @@ import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -324,12 +324,8 @@ public final class Iterables {
* @return a newly-allocated array into which all the elements of the iterable have been copied
*/
@GwtIncompatible // Array.newInstance(Class, int)
- /*
- * If we could express Class<@Nonnull T>, we could generalize the type parameter to <T extends
- * @Nullable Object>, and then we could accept an Iterable<? extends T> and return a plain T[]
- * instead of a @Nullable T[].
- */
- public static <T> @Nullable T[] toArray(Iterable<? extends @Nullable T> iterable, Class<T> type) {
+ public static <T extends @Nullable Object> T[] toArray(
+ Iterable<? extends T> iterable, Class<@NonNull T> type) {
return toArray(iterable, ObjectArrays.newArray(type, 0));
}
@@ -987,10 +983,13 @@ public final class Iterables {
* Returns a view of the supplied iterable that wraps each generated {@link Iterator} through
* {@link Iterators#consumingIterator(Iterator)}.
*
- * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will get entries from
- * {@link Queue#remove()} since {@link Queue}'s iteration order is undefined. Calling {@link
- * Iterator#hasNext()} on a generated iterator from the returned iterable may cause an item to be
- * immediately dequeued for return on a subsequent call to {@link Iterator#next()}.
+ * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will instead use {@link
+ * Queue#isEmpty} and {@link Queue#remove()}, since {@link Queue}'s iteration order is undefined.
+ * Calling {@link Iterator#hasNext()} on a generated iterator from the returned iterable may cause
+ * an item to be immediately dequeued for return on a subsequent call to {@link Iterator#next()}.
+ *
+ * <p>Whether the input {@code iterable} is a {@link Queue} or not, the returned {@code Iterable}
+ * is not thread-safe.
*
* @param iterable the iterable to wrap
* @return a view of the supplied iterable that wraps each generated iterator through {@link
@@ -1050,7 +1049,6 @@ public final class Iterables {
*
* @since 11.0
*/
- @Beta
public static <T extends @Nullable Object> Iterable<T> mergeSorted(
final Iterable<? extends Iterable<? extends T>> iterables,
final Comparator<? super T> comparator) {
@@ -1061,21 +1059,9 @@ public final class Iterables {
@Override
public Iterator<T> iterator() {
return Iterators.mergeSorted(
- Iterables.transform(iterables, Iterables.<T>toIterator()), comparator);
+ Iterables.transform(iterables, Iterable::iterator), comparator);
}
};
return new UnmodifiableIterable<>(iterable);
}
-
- // TODO(user): Is this the best place for this? Move to fluent functions?
- // Useful as a public method?
- static <T extends @Nullable Object>
- Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() {
- return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
- @Override
- public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
- return iterable.iterator();
- }
- };
- }
}
diff --git a/android/guava/src/com/google/common/collect/Iterators.java b/android/guava/src/com/google/common/collect/Iterators.java
index 2f9fd3b4a..0699202fe 100644
--- a/android/guava/src/com/google/common/collect/Iterators.java
+++ b/android/guava/src/com/google/common/collect/Iterators.java
@@ -24,7 +24,6 @@ import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
@@ -48,6 +47,7 @@ import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -345,10 +345,10 @@ public final class Iterators {
* @return a newly-allocated array into which all the elements of the iterator have been copied
*/
@GwtIncompatible // Array.newInstance(Class, int)
- // For discussion of this signature, see the corresponding overload of *Iterables*.toArray.
- public static <T> @Nullable T[] toArray(Iterator<? extends @Nullable T> iterator, Class<T> type) {
- List<@Nullable T> list = Lists.newArrayList(iterator);
- return Iterables.toArray(list, type);
+ public static <T extends @Nullable Object> T[] toArray(
+ Iterator<? extends T> iterator, Class<@NonNull T> type) {
+ List<T> list = Lists.newArrayList(iterator);
+ return Iterables.<T>toArray(list, type);
}
/**
@@ -988,7 +988,8 @@ public final class Iterators {
* {@code iterator} as it is returned.
*
* <p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator
- * will fail on the first call to {@code next}.
+ * will fail on the first call to {@code next}. The returned {@link Iterator} is also not
+ * thread-safe.
*
* @param iterator the iterator to remove and return elements from
* @return an iterator that removes and returns elements from the supplied iterator
@@ -1294,7 +1295,6 @@ public final class Iterators {
*
* @since 11.0
*/
- @Beta
public static <T extends @Nullable Object> UnmodifiableIterator<T> mergeSorted(
Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) {
checkNotNull(iterators, "iterators");
diff --git a/android/guava/src/com/google/common/collect/LinkedHashMultimap.java b/android/guava/src/com/google/common/collect/LinkedHashMultimap.java
index 11cddc383..0d9dc0694 100644
--- a/android/guava/src/com/google/common/collect/LinkedHashMultimap.java
+++ b/android/guava/src/com/google/common/collect/LinkedHashMultimap.java
@@ -22,6 +22,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -168,8 +169,8 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
* always call succeedsIn*() to initialize them immediately thereafter.
*
* The exception is the *InValueSet fields of multimapHeaderEntry, which are never set. (That
- * works out fine as long as we continue to be careful not to try delete them or iterate past
- * them.)
+ * works out fine as long as we continue to be careful not to try to delete them or iterate
+ * past them.)
*
* We could consider "lying" and omitting @CheckNotNull from all these fields. Normally, I'm not
* a fan of that: What if we someday implement (presumably to be enabled during tests only)
@@ -183,7 +184,7 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
* hopefully could avoid implementing Entry or ValueSetLink at all. (But note that that approach
* requires us to define extra classes -- unfortunate under Android.) *Then* we could consider
* lying about the fields below on the grounds that we always initialize them just after the
- * constructor -- an example of the kind of lying that our hypotheticaly bytecode rewriter would
+ * constructor -- an example of the kind of lying that our hypothetical bytecode rewriter would
* already have to deal with, thanks to DI frameworks that perform field and method injection,
* frameworks like Android that define post-construct hooks like Activity.onCreate, etc.
*/
@@ -592,6 +593,7 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
* and the entries in order
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(keySet().size());
@@ -606,6 +608,7 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
multimapHeaderEntry = ValueEntry.newHeader();
@@ -634,5 +637,6 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 1;
}
diff --git a/android/guava/src/com/google/common/collect/LinkedListMultimap.java b/android/guava/src/com/google/common/collect/LinkedListMultimap.java
index 338c54742..74ac4c1f3 100644
--- a/android/guava/src/com/google/common/collect/LinkedListMultimap.java
+++ b/android/guava/src/com/google/common/collect/LinkedListMultimap.java
@@ -23,6 +23,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
@@ -211,7 +212,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
/**
* Adds a new node for the specified key-value pair before the specified {@code nextSibling}
* element, or at the end of the list if {@code nextSibling} is null. Note: if {@code nextSibling}
- * is specified, it MUST be for an node for the same {@code key}!
+ * is specified, it MUST be for a node for the same {@code key}!
*/
@CanIgnoreReturnValue
private Node<K, V> addNode(
@@ -676,7 +677,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
*/
@CanIgnoreReturnValue
@Override
- public List<V> removeAll(@Nullable Object key) {
+ public List<V> removeAll(@CheckForNull Object key) {
/*
* Safe because all we do is remove values for the key, not add them. (If we wanted to make sure
* to call getCopy and removeAllNodes only with a true K, then we could check containsKey first.
@@ -853,6 +854,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
* from the entries() ordering
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
@@ -863,6 +865,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyToKeyList = CompactLinkedHashMap.create();
@@ -877,5 +880,6 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/Lists.java b/android/guava/src/com/google/common/collect/Lists.java
index 34fc2258c..047575b57 100644
--- a/android/guava/src/com/google/common/collect/Lists.java
+++ b/android/guava/src/com/google/common/collect/Lists.java
@@ -25,9 +25,9 @@ import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
@@ -250,6 +250,7 @@ public final class Lists {
* @return a new, empty {@code CopyOnWriteArrayList}
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArrayList
public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
return new CopyOnWriteArrayList<>();
@@ -262,6 +263,7 @@ public final class Lists {
* @return a new {@code CopyOnWriteArrayList} containing those elements
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArrayList
public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
Iterable<? extends E> elements) {
@@ -337,7 +339,7 @@ public final class Lists {
return (index == 0) ? first : rest[index - 1];
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
/** @see Lists#asList(Object, Object, Object[]) */
@@ -373,7 +375,7 @@ public final class Lists {
}
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
/**
@@ -553,8 +555,8 @@ public final class Lists {
* can be overkill. That's why we forward this call directly to the backing list.
*/
@Override
- public void clear() {
- fromList.clear();
+ protected void removeRange(int fromIndex, int toIndex) {
+ fromList.subList(fromIndex, toIndex).clear();
}
@Override
@@ -594,9 +596,13 @@ public final class Lists {
this.function = checkNotNull(function);
}
+ /**
+ * The default implementation inherited is based on iteration and removal of each element which
+ * can be overkill. That's why we forward this call directly to the backing list.
+ */
@Override
- public void clear() {
- fromList.clear();
+ protected void removeRange(int fromIndex, int toIndex) {
+ fromList.subList(fromIndex, toIndex).clear();
}
@Override
@@ -620,6 +626,8 @@ public final class Lists {
};
}
+ // TODO: cpovirk - Why override `isEmpty` here but not in TransformingSequentialList?
+
@Override
public boolean isEmpty() {
return fromList.isEmpty();
@@ -714,7 +722,6 @@ public final class Lists {
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
- @Beta
public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
@@ -1090,7 +1097,7 @@ public final class Lists {
return backingList.listIterator(index);
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
};
} else {
wrapper =
@@ -1100,7 +1107,7 @@ public final class Lists {
return backingList.listIterator(index);
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
diff --git a/android/guava/src/com/google/common/collect/MapMaker.java b/android/guava/src/com/google/common/collect/MapMaker.java
index a2612c1bd..4fb4ec824 100644
--- a/android/guava/src/com/google/common/collect/MapMaker.java
+++ b/android/guava/src/com/google/common/collect/MapMaker.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Equivalence;
import com.google.common.base.MoreObjects;
@@ -85,6 +86,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 2.0
*/
+@J2ktIncompatible
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class MapMaker {
diff --git a/android/guava/src/com/google/common/collect/MapMakerInternalMap.java b/android/guava/src/com/google/common/collect/MapMakerInternalMap.java
index bdef10ebc..c64d81eb3 100644
--- a/android/guava/src/com/google/common/collect/MapMakerInternalMap.java
+++ b/android/guava/src/com/google/common/collect/MapMakerInternalMap.java
@@ -18,15 +18,18 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.collect.MapMaker.Dummy;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
+import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@@ -64,6 +67,7 @@ import javax.annotation.CheckForNull;
* @author Doug Lea ({@code ConcurrentHashMap})
*/
// TODO(kak): Consider removing @CanIgnoreReturnValue from this class.
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings({
"GuardedBy", // TODO(b/35466881): Fix or suppress.
@@ -130,8 +134,6 @@ class MapMakerInternalMap<
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
- static final long CLEANUP_EXECUTOR_DELAY_SECS = 60;
-
// Fields
/**
@@ -193,7 +195,7 @@ class MapMakerInternalMap<
}
for (int i = 0; i < this.segments.length; ++i) {
- this.segments[i] = createSegment(segmentSize, MapMaker.UNSET_INT);
+ this.segments[i] = createSegment(segmentSize);
}
}
@@ -290,7 +292,7 @@ class MapMakerInternalMap<
Strength valueStrength();
/** Returns a freshly created segment, typed at the {@code S} type. */
- S newSegment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity, int maxSegmentSize);
+ S newSegment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity);
/**
* Returns a freshly created entry, typed at the {@code E} type, for the given {@code segment}.
@@ -343,27 +345,26 @@ class MapMakerInternalMap<
implements InternalEntry<K, V, E> {
final K key;
final int hash;
- @CheckForNull final E next;
- AbstractStrongKeyEntry(K key, int hash, @CheckForNull E next) {
+ AbstractStrongKeyEntry(K key, int hash) {
this.key = key;
this.hash = hash;
- this.next = next;
}
@Override
- public K getKey() {
- return this.key;
+ public final K getKey() {
+ return key;
}
@Override
- public int getHash() {
+ public final int getHash() {
return hash;
}
@Override
+ @CheckForNull
public E getNext() {
- return next;
+ return null;
}
}
@@ -375,12 +376,6 @@ class MapMakerInternalMap<
interface WeakValueEntry<K, V, E extends InternalEntry<K, V, E>> extends InternalEntry<K, V, E> {
/** Gets the weak value reference held by entry. */
WeakValueReference<K, V, E> getValueReference();
-
- /**
- * Clears the weak value reference held by the entry. Should be used when the entry's value is
- * overwritten.
- */
- void clearValue();
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
@@ -390,30 +385,34 @@ class MapMakerInternalMap<
}
/** Concrete implementation of {@link InternalEntry} for strong keys and strong values. */
- static final class StrongKeyStrongValueEntry<K, V>
+ static class StrongKeyStrongValueEntry<K, V>
extends AbstractStrongKeyEntry<K, V, StrongKeyStrongValueEntry<K, V>>
implements StrongValueEntry<K, V, StrongKeyStrongValueEntry<K, V>> {
@CheckForNull private volatile V value = null;
- StrongKeyStrongValueEntry(K key, int hash, @CheckForNull StrongKeyStrongValueEntry<K, V> next) {
- super(key, hash, next);
+ private StrongKeyStrongValueEntry(K key, int hash) {
+ super(key, hash);
}
@Override
@CheckForNull
- public V getValue() {
+ public final V getValue() {
return value;
}
- void setValue(V value) {
- this.value = value;
- }
+ private static final class LinkedStrongKeyStrongValueEntry<K, V>
+ extends StrongKeyStrongValueEntry<K, V> {
+ private final StrongKeyStrongValueEntry<K, V> next;
+
+ LinkedStrongKeyStrongValueEntry(K key, int hash, StrongKeyStrongValueEntry<K, V> next) {
+ super(key, hash);
+ this.next = next;
+ }
- StrongKeyStrongValueEntry<K, V> copy(StrongKeyStrongValueEntry<K, V> newNext) {
- StrongKeyStrongValueEntry<K, V> newEntry =
- new StrongKeyStrongValueEntry<>(this.key, this.hash, newNext);
- newEntry.value = this.value;
- return newEntry;
+ @Override
+ public StrongKeyStrongValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for strong keys and strong values. */
@@ -442,9 +441,8 @@ class MapMakerInternalMap<
MapMakerInternalMap<
K, V, StrongKeyStrongValueEntry<K, V>, StrongKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new StrongKeyStrongValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new StrongKeyStrongValueSegment<>(map, initialCapacity);
}
@Override
@@ -452,7 +450,10 @@ class MapMakerInternalMap<
StrongKeyStrongValueSegment<K, V> segment,
StrongKeyStrongValueEntry<K, V> entry,
@CheckForNull StrongKeyStrongValueEntry<K, V> newNext) {
- return entry.copy(newNext);
+ StrongKeyStrongValueEntry<K, V> newEntry =
+ newEntry(segment, entry.key, entry.hash, newNext);
+ newEntry.value = entry.value;
+ return newEntry;
}
@Override
@@ -460,7 +461,7 @@ class MapMakerInternalMap<
StrongKeyStrongValueSegment<K, V> segment,
StrongKeyStrongValueEntry<K, V> entry,
V value) {
- entry.setValue(value);
+ entry.value = value;
}
@Override
@@ -469,48 +470,48 @@ class MapMakerInternalMap<
K key,
int hash,
@CheckForNull StrongKeyStrongValueEntry<K, V> next) {
- return new StrongKeyStrongValueEntry<>(key, hash, next);
+ return next == null
+ ? new StrongKeyStrongValueEntry<>(key, hash)
+ : new LinkedStrongKeyStrongValueEntry<>(key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for strong keys and weak values. */
- static final class StrongKeyWeakValueEntry<K, V>
+ static class StrongKeyWeakValueEntry<K, V>
extends AbstractStrongKeyEntry<K, V, StrongKeyWeakValueEntry<K, V>>
implements WeakValueEntry<K, V, StrongKeyWeakValueEntry<K, V>> {
private volatile WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> valueReference =
unsetWeakValueReference();
- StrongKeyWeakValueEntry(K key, int hash, @CheckForNull StrongKeyWeakValueEntry<K, V> next) {
- super(key, hash, next);
+ private StrongKeyWeakValueEntry(K key, int hash) {
+ super(key, hash);
}
@Override
- public V getValue() {
+ @CheckForNull
+ public final V getValue() {
return valueReference.get();
}
@Override
- public void clearValue() {
- valueReference.clear();
+ public final WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> getValueReference() {
+ return valueReference;
}
- void setValue(V value, ReferenceQueue<V> queueForValues) {
- WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> previous = this.valueReference;
- this.valueReference = new WeakValueReferenceImpl<>(queueForValues, value, this);
- previous.clear();
- }
+ private static final class LinkedStrongKeyWeakValueEntry<K, V>
+ extends StrongKeyWeakValueEntry<K, V> {
+ private final StrongKeyWeakValueEntry<K, V> next;
- StrongKeyWeakValueEntry<K, V> copy(
- ReferenceQueue<V> queueForValues, StrongKeyWeakValueEntry<K, V> newNext) {
- StrongKeyWeakValueEntry<K, V> newEntry = new StrongKeyWeakValueEntry<>(key, hash, newNext);
- newEntry.valueReference = valueReference.copyFor(queueForValues, newEntry);
- return newEntry;
- }
+ LinkedStrongKeyWeakValueEntry(K key, int hash, StrongKeyWeakValueEntry<K, V> next) {
+ super(key, hash);
+ this.next = next;
+ }
- @Override
- public WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> getValueReference() {
- return valueReference;
+ @Override
+ public StrongKeyWeakValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for strong keys and weak values. */
@@ -538,12 +539,12 @@ class MapMakerInternalMap<
public StrongKeyWeakValueSegment<K, V> newSegment(
MapMakerInternalMap<K, V, StrongKeyWeakValueEntry<K, V>, StrongKeyWeakValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new StrongKeyWeakValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new StrongKeyWeakValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public StrongKeyWeakValueEntry<K, V> copy(
StrongKeyWeakValueSegment<K, V> segment,
StrongKeyWeakValueEntry<K, V> entry,
@@ -551,13 +552,17 @@ class MapMakerInternalMap<
if (Segment.isCollected(entry)) {
return null;
}
- return entry.copy(segment.queueForValues, newNext);
+ StrongKeyWeakValueEntry<K, V> newEntry = newEntry(segment, entry.key, entry.hash, newNext);
+ newEntry.valueReference = entry.valueReference.copyFor(segment.queueForValues, newEntry);
+ return newEntry;
}
@Override
public void setValue(
StrongKeyWeakValueSegment<K, V> segment, StrongKeyWeakValueEntry<K, V> entry, V value) {
- entry.setValue(value, segment.queueForValues);
+ WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> previous = entry.valueReference;
+ entry.valueReference = new WeakValueReferenceImpl<>(segment.queueForValues, value, entry);
+ previous.clear();
}
@Override
@@ -566,28 +571,40 @@ class MapMakerInternalMap<
K key,
int hash,
@CheckForNull StrongKeyWeakValueEntry<K, V> next) {
- return new StrongKeyWeakValueEntry<>(key, hash, next);
+ return next == null
+ ? new StrongKeyWeakValueEntry<>(key, hash)
+ : new LinkedStrongKeyWeakValueEntry<>(key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for strong keys and {@link Dummy} values. */
- static final class StrongKeyDummyValueEntry<K>
+ static class StrongKeyDummyValueEntry<K>
extends AbstractStrongKeyEntry<K, Dummy, StrongKeyDummyValueEntry<K>>
implements StrongValueEntry<K, Dummy, StrongKeyDummyValueEntry<K>> {
- StrongKeyDummyValueEntry(K key, int hash, @CheckForNull StrongKeyDummyValueEntry<K> next) {
- super(key, hash, next);
+
+ private StrongKeyDummyValueEntry(K key, int hash) {
+ super(key, hash);
}
@Override
- public Dummy getValue() {
+ public final Dummy getValue() {
return Dummy.VALUE;
}
- void setValue(Dummy value) {}
+ private static final class LinkedStrongKeyDummyValueEntry<K>
+ extends StrongKeyDummyValueEntry<K> {
+ private final StrongKeyDummyValueEntry<K> next;
- StrongKeyDummyValueEntry<K> copy(StrongKeyDummyValueEntry<K> newNext) {
- return new StrongKeyDummyValueEntry<K>(this.key, this.hash, newNext);
+ LinkedStrongKeyDummyValueEntry(K key, int hash, StrongKeyDummyValueEntry<K> next) {
+ super(key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public StrongKeyDummyValueEntry<K> getNext() {
+ return next;
+ }
}
/**
@@ -618,9 +635,8 @@ class MapMakerInternalMap<
public StrongKeyDummyValueSegment<K> newSegment(
MapMakerInternalMap<K, Dummy, StrongKeyDummyValueEntry<K>, StrongKeyDummyValueSegment<K>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new StrongKeyDummyValueSegment<K>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new StrongKeyDummyValueSegment<K>(map, initialCapacity);
}
@Override
@@ -628,7 +644,7 @@ class MapMakerInternalMap<
StrongKeyDummyValueSegment<K> segment,
StrongKeyDummyValueEntry<K> entry,
@CheckForNull StrongKeyDummyValueEntry<K> newNext) {
- return entry.copy(newNext);
+ return newEntry(segment, entry.key, entry.hash, newNext);
}
@Override
@@ -641,7 +657,9 @@ class MapMakerInternalMap<
K key,
int hash,
@CheckForNull StrongKeyDummyValueEntry<K> next) {
- return new StrongKeyDummyValueEntry<K>(key, hash, next);
+ return next == null
+ ? new StrongKeyDummyValueEntry<K>(key, hash)
+ : new LinkedStrongKeyDummyValueEntry<>(key, hash, next);
}
}
}
@@ -650,49 +668,56 @@ class MapMakerInternalMap<
abstract static class AbstractWeakKeyEntry<K, V, E extends InternalEntry<K, V, E>>
extends WeakReference<K> implements InternalEntry<K, V, E> {
final int hash;
- @CheckForNull final E next;
- AbstractWeakKeyEntry(ReferenceQueue<K> queue, K key, int hash, @CheckForNull E next) {
+ AbstractWeakKeyEntry(ReferenceQueue<K> queue, K key, int hash) {
super(key, queue);
this.hash = hash;
- this.next = next;
}
@Override
- public K getKey() {
+ public final K getKey() {
return get();
}
@Override
- public int getHash() {
+ public final int getHash() {
return hash;
}
@Override
+ @CheckForNull
public E getNext() {
- return next;
+ return null;
}
}
/** Concrete implementation of {@link InternalEntry} for weak keys and {@link Dummy} values. */
- static final class WeakKeyDummyValueEntry<K>
+ static class WeakKeyDummyValueEntry<K>
extends AbstractWeakKeyEntry<K, Dummy, WeakKeyDummyValueEntry<K>>
implements StrongValueEntry<K, Dummy, WeakKeyDummyValueEntry<K>> {
- WeakKeyDummyValueEntry(
- ReferenceQueue<K> queue, K key, int hash, @CheckForNull WeakKeyDummyValueEntry<K> next) {
- super(queue, key, hash, next);
+
+ private WeakKeyDummyValueEntry(ReferenceQueue<K> queue, K key, int hash) {
+ super(queue, key, hash);
}
@Override
- public Dummy getValue() {
+ public final Dummy getValue() {
return Dummy.VALUE;
}
- void setValue(Dummy value) {}
+ private static final class LinkedWeakKeyDummyValueEntry<K> extends WeakKeyDummyValueEntry<K> {
+ private final WeakKeyDummyValueEntry<K> next;
+
+ private LinkedWeakKeyDummyValueEntry(
+ ReferenceQueue<K> queue, K key, int hash, WeakKeyDummyValueEntry<K> next) {
+ super(queue, key, hash);
+ this.next = next;
+ }
- WeakKeyDummyValueEntry<K> copy(
- ReferenceQueue<K> queueForKeys, WeakKeyDummyValueEntry<K> newNext) {
- return new WeakKeyDummyValueEntry<K>(queueForKeys, getKey(), this.hash, newNext);
+ @Override
+ public WeakKeyDummyValueEntry<K> getNext() {
+ return next;
+ }
}
/**
@@ -722,21 +747,22 @@ class MapMakerInternalMap<
@Override
public WeakKeyDummyValueSegment<K> newSegment(
MapMakerInternalMap<K, Dummy, WeakKeyDummyValueEntry<K>, WeakKeyDummyValueSegment<K>> map,
- int initialCapacity,
- int maxSegmentSize) {
- return new WeakKeyDummyValueSegment<K>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new WeakKeyDummyValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public WeakKeyDummyValueEntry<K> copy(
WeakKeyDummyValueSegment<K> segment,
WeakKeyDummyValueEntry<K> entry,
@CheckForNull WeakKeyDummyValueEntry<K> newNext) {
- if (entry.getKey() == null) {
+ K key = entry.getKey();
+ if (key == null) {
// key collected
return null;
}
- return entry.copy(segment.queueForKeys, newNext);
+ return newEntry(segment, key, entry.hash, newNext);
}
@Override
@@ -749,41 +775,43 @@ class MapMakerInternalMap<
K key,
int hash,
@CheckForNull WeakKeyDummyValueEntry<K> next) {
- return new WeakKeyDummyValueEntry<K>(segment.queueForKeys, key, hash, next);
+ return next == null
+ ? new WeakKeyDummyValueEntry<>(segment.queueForKeys, key, hash)
+ : new LinkedWeakKeyDummyValueEntry<>(segment.queueForKeys, key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for weak keys and strong values. */
- static final class WeakKeyStrongValueEntry<K, V>
+ static class WeakKeyStrongValueEntry<K, V>
extends AbstractWeakKeyEntry<K, V, WeakKeyStrongValueEntry<K, V>>
implements StrongValueEntry<K, V, WeakKeyStrongValueEntry<K, V>> {
@CheckForNull private volatile V value = null;
- WeakKeyStrongValueEntry(
- ReferenceQueue<K> queue,
- K key,
- int hash,
- @CheckForNull WeakKeyStrongValueEntry<K, V> next) {
- super(queue, key, hash, next);
+ private WeakKeyStrongValueEntry(ReferenceQueue<K> queue, K key, int hash) {
+ super(queue, key, hash);
}
@Override
@CheckForNull
- public V getValue() {
+ public final V getValue() {
return value;
}
- void setValue(V value) {
- this.value = value;
- }
+ private static final class LinkedWeakKeyStrongValueEntry<K, V>
+ extends WeakKeyStrongValueEntry<K, V> {
+ private final WeakKeyStrongValueEntry<K, V> next;
- WeakKeyStrongValueEntry<K, V> copy(
- ReferenceQueue<K> queueForKeys, WeakKeyStrongValueEntry<K, V> newNext) {
- WeakKeyStrongValueEntry<K, V> newEntry =
- new WeakKeyStrongValueEntry<>(queueForKeys, getKey(), this.hash, newNext);
- newEntry.setValue(value);
- return newEntry;
+ private LinkedWeakKeyStrongValueEntry(
+ ReferenceQueue<K> queue, K key, int hash, WeakKeyStrongValueEntry<K, V> next) {
+ super(queue, key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public WeakKeyStrongValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for weak keys and strong values. */
@@ -811,27 +839,30 @@ class MapMakerInternalMap<
public WeakKeyStrongValueSegment<K, V> newSegment(
MapMakerInternalMap<K, V, WeakKeyStrongValueEntry<K, V>, WeakKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new WeakKeyStrongValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new WeakKeyStrongValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public WeakKeyStrongValueEntry<K, V> copy(
WeakKeyStrongValueSegment<K, V> segment,
WeakKeyStrongValueEntry<K, V> entry,
@CheckForNull WeakKeyStrongValueEntry<K, V> newNext) {
- if (entry.getKey() == null) {
+ K key = entry.getKey();
+ if (key == null) {
// key collected
return null;
}
- return entry.copy(segment.queueForKeys, newNext);
+ WeakKeyStrongValueEntry<K, V> newEntry = newEntry(segment, key, entry.hash, newNext);
+ newEntry.value = entry.value;
+ return newEntry;
}
@Override
public void setValue(
WeakKeyStrongValueSegment<K, V> segment, WeakKeyStrongValueEntry<K, V> entry, V value) {
- entry.setValue(value);
+ entry.value = value;
}
@Override
@@ -840,52 +871,48 @@ class MapMakerInternalMap<
K key,
int hash,
@CheckForNull WeakKeyStrongValueEntry<K, V> next) {
- return new WeakKeyStrongValueEntry<>(segment.queueForKeys, key, hash, next);
+ return next == null
+ ? new WeakKeyStrongValueEntry<>(segment.queueForKeys, key, hash)
+ : new LinkedWeakKeyStrongValueEntry<>(segment.queueForKeys, key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for weak keys and weak values. */
- static final class WeakKeyWeakValueEntry<K, V>
+ static class WeakKeyWeakValueEntry<K, V>
extends AbstractWeakKeyEntry<K, V, WeakKeyWeakValueEntry<K, V>>
implements WeakValueEntry<K, V, WeakKeyWeakValueEntry<K, V>> {
private volatile WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> valueReference =
unsetWeakValueReference();
- WeakKeyWeakValueEntry(
- ReferenceQueue<K> queue, K key, int hash, @CheckForNull WeakKeyWeakValueEntry<K, V> next) {
- super(queue, key, hash, next);
+ WeakKeyWeakValueEntry(ReferenceQueue<K> queue, K key, int hash) {
+ super(queue, key, hash);
}
@Override
- public V getValue() {
+ public final V getValue() {
return valueReference.get();
}
- WeakKeyWeakValueEntry<K, V> copy(
- ReferenceQueue<K> queueForKeys,
- ReferenceQueue<V> queueForValues,
- WeakKeyWeakValueEntry<K, V> newNext) {
- WeakKeyWeakValueEntry<K, V> newEntry =
- new WeakKeyWeakValueEntry<>(queueForKeys, getKey(), this.hash, newNext);
- newEntry.valueReference = valueReference.copyFor(queueForValues, newEntry);
- return newEntry;
- }
-
@Override
- public void clearValue() {
- valueReference.clear();
+ public final WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> getValueReference() {
+ return valueReference;
}
- void setValue(V value, ReferenceQueue<V> queueForValues) {
- WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> previous = this.valueReference;
- this.valueReference = new WeakValueReferenceImpl<>(queueForValues, value, this);
- previous.clear();
- }
+ private static final class LinkedWeakKeyWeakValueEntry<K, V>
+ extends WeakKeyWeakValueEntry<K, V> {
+ private final WeakKeyWeakValueEntry<K, V> next;
- @Override
- public WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> getValueReference() {
- return valueReference;
+ LinkedWeakKeyWeakValueEntry(
+ ReferenceQueue<K> queue, K key, int hash, WeakKeyWeakValueEntry<K, V> next) {
+ super(queue, key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public WeakKeyWeakValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for weak keys and weak values. */
@@ -912,30 +939,35 @@ class MapMakerInternalMap<
@Override
public WeakKeyWeakValueSegment<K, V> newSegment(
MapMakerInternalMap<K, V, WeakKeyWeakValueEntry<K, V>, WeakKeyWeakValueSegment<K, V>> map,
- int initialCapacity,
- int maxSegmentSize) {
- return new WeakKeyWeakValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new WeakKeyWeakValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public WeakKeyWeakValueEntry<K, V> copy(
WeakKeyWeakValueSegment<K, V> segment,
WeakKeyWeakValueEntry<K, V> entry,
@CheckForNull WeakKeyWeakValueEntry<K, V> newNext) {
- if (entry.getKey() == null) {
+ K key = entry.getKey();
+ if (key == null) {
// key collected
return null;
}
if (Segment.isCollected(entry)) {
return null;
}
- return entry.copy(segment.queueForKeys, segment.queueForValues, newNext);
+ WeakKeyWeakValueEntry<K, V> newEntry = newEntry(segment, key, entry.hash, newNext);
+ newEntry.valueReference = entry.valueReference.copyFor(segment.queueForValues, newEntry);
+ return newEntry;
}
@Override
public void setValue(
WeakKeyWeakValueSegment<K, V> segment, WeakKeyWeakValueEntry<K, V> entry, V value) {
- entry.setValue(value, segment.queueForValues);
+ WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> previous = entry.valueReference;
+ entry.valueReference = new WeakValueReferenceImpl<>(segment.queueForValues, value, entry);
+ previous.clear();
}
@Override
@@ -944,7 +976,9 @@ class MapMakerInternalMap<
K key,
int hash,
@CheckForNull WeakKeyWeakValueEntry<K, V> next) {
- return new WeakKeyWeakValueEntry<>(segment.queueForKeys, key, hash, next);
+ return next == null
+ ? new WeakKeyWeakValueEntry<>(segment.queueForKeys, key, hash)
+ : new LinkedWeakKeyWeakValueEntry<>(segment.queueForKeys, key, hash, next);
}
}
}
@@ -966,7 +1000,7 @@ class MapMakerInternalMap<
/**
* Returns a freshly created {@link WeakValueReference} for the given {@code entry} (and on the
- * given {@code queue} with the same value as this {@link WeakValueReference}.
+ * given {@code queue}) with the same value as this {@link WeakValueReference}.
*/
WeakValueReference<K, V, E> copyFor(ReferenceQueue<V> queue, E entry);
}
@@ -1003,11 +1037,12 @@ class MapMakerInternalMap<
}
/**
- * A singleton {@link WeakValueReference} used to denote an unset value in a entry with weak
+ * A singleton {@link WeakValueReference} used to denote an unset value in an entry with weak
* values.
*/
static final WeakValueReference<Object, Object, DummyInternalEntry> UNSET_WEAK_VALUE_REFERENCE =
new WeakValueReference<Object, Object, DummyInternalEntry>() {
+ @CheckForNull
@Override
public DummyInternalEntry getEntry() {
return null;
@@ -1016,6 +1051,7 @@ class MapMakerInternalMap<
@Override
public void clear() {}
+ @CheckForNull
@Override
public Object get() {
return null;
@@ -1115,14 +1151,15 @@ class MapMakerInternalMap<
return segments[(hash >>> segmentShift) & segmentMask];
}
- Segment<K, V, E, S> createSegment(int initialCapacity, int maxSegmentSize) {
- return entryHelper.newSegment(this, initialCapacity, maxSegmentSize);
+ Segment<K, V, E, S> createSegment(int initialCapacity) {
+ return entryHelper.newSegment(this, initialCapacity);
}
/**
* Gets the value from an entry. Returns {@code null} if the entry is invalid, partially-collected
* or computing.
*/
+ @CheckForNull
V getLiveValue(E entry) {
if (entry.getKey() == null) {
return null;
@@ -1199,18 +1236,14 @@ class MapMakerInternalMap<
/** The per-segment table. */
@CheckForNull volatile AtomicReferenceArray<E> table;
- /** The maximum size of this map. MapMaker.UNSET_INT if there is no maximum. */
- final int maxSegmentSize;
-
/**
* A counter of the number of reads since the last write, used to drain queues on a small
* fraction of read operations.
*/
final AtomicInteger readCount = new AtomicInteger();
- Segment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity, int maxSegmentSize) {
+ Segment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity) {
this.map = map;
- this.maxSegmentSize = maxSegmentSize;
initTable(newEntryArray(initialCapacity));
}
@@ -1235,6 +1268,7 @@ class MapMakerInternalMap<
}
/** Returns a copy of the given {@code entry}. */
+ @CheckForNull
E copyEntry(E original, E newNext) {
return this.map.entryHelper.copy(self(), original, newNext);
}
@@ -1245,10 +1279,6 @@ class MapMakerInternalMap<
void initTable(AtomicReferenceArray<E> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
- if (this.threshold == maxSegmentSize) {
- // prevent spurious expansion before eviction
- this.threshold++;
- }
this.table = newTable;
}
@@ -1259,7 +1289,7 @@ class MapMakerInternalMap<
* implementation type.
*
* <p>This method is provided as a convenience for tests. Otherwise they'd need to be
- * knowledgable about all the implementation details of our type system trickery.
+ * knowledgeable about all the implementation details of our type system trickery.
*/
abstract E castForTesting(InternalEntry<K, V, ?> entry);
@@ -1326,6 +1356,7 @@ class MapMakerInternalMap<
}
/** Unsafely removes the given entry from the given chain in this segment's hash table. */
+ @CheckForNull
E removeFromChainForTesting(InternalEntry<K, V, ?> first, InternalEntry<K, V, ?> entry) {
return removeFromChain(castForTesting(first), castForTesting(entry));
}
@@ -1384,6 +1415,7 @@ class MapMakerInternalMap<
}
/** Returns first entry of bin for given hash. */
+ @CheckForNull
E getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<E> table = this.table;
@@ -1392,6 +1424,7 @@ class MapMakerInternalMap<
// Specialized implementations of map methods
+ @CheckForNull
E getEntry(Object key, int hash) {
if (count != 0) { // read-volatile
for (E e = getFirst(hash); e != null; e = e.getNext()) {
@@ -1414,10 +1447,12 @@ class MapMakerInternalMap<
return null;
}
+ @CheckForNull
E getLiveEntry(Object key, int hash) {
return getEntry(key, hash);
}
+ @CheckForNull
V get(Object key, int hash) {
try {
E e = getLiveEntry(key, hash);
@@ -1477,6 +1512,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
@@ -1650,6 +1686,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
V replace(K key, int hash, V newValue) {
lock();
try {
@@ -1691,6 +1728,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
@CanIgnoreReturnValue
V remove(Object key, int hash) {
lock();
@@ -1805,6 +1843,7 @@ class MapMakerInternalMap<
* @return the new first entry for the table
*/
@GuardedBy("this")
+ @CheckForNull
E removeFromChain(E first, E entry) {
int newCount = count;
E newFirst = entry.getNext();
@@ -2006,9 +2045,8 @@ class MapMakerInternalMap<
MapMakerInternalMap<
K, V, StrongKeyStrongValueEntry<K, V>, StrongKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2018,7 +2056,9 @@ class MapMakerInternalMap<
@SuppressWarnings("unchecked")
@Override
- public StrongKeyStrongValueEntry<K, V> castForTesting(InternalEntry<K, V, ?> entry) {
+ @CheckForNull
+ public StrongKeyStrongValueEntry<K, V> castForTesting(
+ @CheckForNull InternalEntry<K, V, ?> entry) {
return (StrongKeyStrongValueEntry<K, V>) entry;
}
}
@@ -2031,9 +2071,8 @@ class MapMakerInternalMap<
StrongKeyWeakValueSegment(
MapMakerInternalMap<K, V, StrongKeyWeakValueEntry<K, V>, StrongKeyWeakValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2048,7 +2087,9 @@ class MapMakerInternalMap<
@SuppressWarnings("unchecked")
@Override
- public StrongKeyWeakValueEntry<K, V> castForTesting(InternalEntry<K, V, ?> entry) {
+ @CheckForNull
+ public StrongKeyWeakValueEntry<K, V> castForTesting(
+ @CheckForNull InternalEntry<K, V, ?> entry) {
return (StrongKeyWeakValueEntry<K, V>) entry;
}
@@ -2094,9 +2135,8 @@ class MapMakerInternalMap<
StrongKeyDummyValueSegment(
MapMakerInternalMap<K, Dummy, StrongKeyDummyValueEntry<K>, StrongKeyDummyValueSegment<K>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2119,9 +2159,8 @@ class MapMakerInternalMap<
WeakKeyStrongValueSegment(
MapMakerInternalMap<K, V, WeakKeyStrongValueEntry<K, V>, WeakKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2159,9 +2198,8 @@ class MapMakerInternalMap<
WeakKeyWeakValueSegment(
MapMakerInternalMap<K, V, WeakKeyWeakValueEntry<K, V>, WeakKeyWeakValueSegment<K, V>> map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2181,7 +2219,8 @@ class MapMakerInternalMap<
@SuppressWarnings("unchecked")
@Override
- public WeakKeyWeakValueEntry<K, V> castForTesting(InternalEntry<K, V, ?> entry) {
+ @CheckForNull
+ public WeakKeyWeakValueEntry<K, V> castForTesting(@CheckForNull InternalEntry<K, V, ?> entry) {
return (WeakKeyWeakValueEntry<K, V>) entry;
}
@@ -2229,9 +2268,8 @@ class MapMakerInternalMap<
WeakKeyDummyValueSegment(
MapMakerInternalMap<K, Dummy, WeakKeyDummyValueEntry<K>, WeakKeyDummyValueSegment<K>> map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2338,6 +2376,7 @@ class MapMakerInternalMap<
return Ints.saturatedCast(sum);
}
+ @CheckForNull
@Override
public V get(@CheckForNull Object key) {
if (key == null) {
@@ -2351,6 +2390,7 @@ class MapMakerInternalMap<
* Returns the internal entry for the specified key. The entry may be computing or partially
* collected. Does not impact recency ordering.
*/
+ @CheckForNull
E getEntry(@CheckForNull Object key) {
if (key == null) {
return null;
@@ -2406,6 +2446,7 @@ class MapMakerInternalMap<
return false;
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V put(K key, V value) {
@@ -2415,6 +2456,7 @@ class MapMakerInternalMap<
return segmentFor(hash).put(key, hash, value, false);
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V putIfAbsent(K key, V value) {
@@ -2431,6 +2473,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V remove(@CheckForNull Object key) {
@@ -2463,6 +2506,7 @@ class MapMakerInternalMap<
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V replace(K key, V value) {
@@ -2479,7 +2523,7 @@ class MapMakerInternalMap<
}
}
- @CheckForNull transient Set<K> keySet;
+ @LazyInit @CheckForNull transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -2487,7 +2531,7 @@ class MapMakerInternalMap<
return (ks != null) ? ks : (keySet = new KeySet());
}
- @CheckForNull transient Collection<V> values;
+ @LazyInit @CheckForNull transient Collection<V> values;
@Override
public Collection<V> values() {
@@ -2495,7 +2539,7 @@ class MapMakerInternalMap<
return (vs != null) ? vs : (values = new Values());
}
- @CheckForNull transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -2845,6 +2889,11 @@ class MapMakerInternalMap<
this);
}
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializationProxy");
+ }
+
/**
* The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a
* circular dependency is present, so the proxy must be able to behave as the map itself.
@@ -2891,6 +2940,7 @@ class MapMakerInternalMap<
}
@SuppressWarnings("deprecation") // serialization of deprecated feature
+ @J2ktIncompatible // java.io.ObjectInputStream
MapMaker readMapMaker(ObjectInputStream in) throws IOException {
int size = in.readInt();
return new MapMaker()
@@ -2902,6 +2952,7 @@ class MapMakerInternalMap<
}
@SuppressWarnings("unchecked")
+ @J2ktIncompatible // java.io.ObjectInputStream
void readEntries(ObjectInputStream in) throws IOException, ClassNotFoundException {
while (true) {
K key = (K) in.readObject();
@@ -2937,6 +2988,7 @@ class MapMakerInternalMap<
writeMapTo(out);
}
+ @J2ktIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MapMaker mapMaker = readMapMaker(in);
diff --git a/android/guava/src/com/google/common/collect/Maps.java b/android/guava/src/com/google/common/collect/Maps.java
index 76e69abb7..9a3852047 100644
--- a/android/guava/src/com/google/common/collect/Maps.java
+++ b/android/guava/src/com/google/common/collect/Maps.java
@@ -22,11 +22,12 @@ import static com.google.common.base.Predicates.compose;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
+import static java.util.Collections.singletonMap;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
@@ -37,6 +38,7 @@ import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
@@ -64,6 +66,7 @@ import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -146,6 +149,7 @@ public final class Maps {
* @since 14.0
*/
@GwtCompatible(serializable = true)
+ @J2ktIncompatible
public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
Map<K, ? extends V> map) {
if (map instanceof ImmutableEnumMap) {
@@ -161,9 +165,8 @@ public final class Maps {
K key1 = entry1.getKey();
V value1 = entry1.getValue();
checkEntryNotNull(key1, value1);
- Class<K> clazz = key1.getDeclaringClass();
- EnumMap<K, V> enumMap = new EnumMap<>(clazz);
- enumMap.put(key1, value1);
+ // Do something that works for j2cl, where we can't call getDeclaredClass():
+ EnumMap<K, V> enumMap = new EnumMap<>(singletonMap(key1, value1));
while (entryItr.hasNext()) {
Entry<K, ? extends V> entry = entryItr.next();
K key = entry.getKey();
@@ -237,10 +240,19 @@ public final class Maps {
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
- // This is the calculation used in JDK8 to resize when a putAll
- // happens; it seems to be the most conservative calculation we
- // can make. 0.75 is the default load factor.
- return (int) ((float) expectedSize / 0.75F + 1.0F);
+ // This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap
+ // ends up being used to compute a "threshold" size, beyond which the internal table
+ // will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where
+ // loadFactor is 0.75 by default. So with the calculation here we ensure that the
+ // threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code
+ // path when the first operation on the new map is putAll(otherMap). There, prior to
+ // https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug
+ // meant that sometimes a too-large threshold is calculated. However, this new threshold is
+ // independent of the initial capacity, except that it won't be lower than the threshold
+ // computed from that capacity. Because the internal table is only allocated on the first
+ // write, we won't see copying because of the new threshold. So it is always OK to use the
+ // calculation here.
+ return (int) Math.ceil(expectedSize / 0.75);
}
return Integer.MAX_VALUE; // any large value
}
@@ -422,28 +434,15 @@ public final class Maps {
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
- @SuppressWarnings("unchecked")
public static <K extends @Nullable Object, V extends @Nullable Object>
MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
+ @SuppressWarnings("unchecked")
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
return difference(sortedLeft, right);
}
- /*
- * This cast is safe: The Equivalence-accepting overload of difference() (which we call below)
- * has a weird signature because Equivalence is itself a little weird. Still, we know that
- * Equivalence.equals() can handle all inputs, and we know that the resulting MapDifference will
- * contain only Ks and Vs (as opposed to possibly containing @Nullable objects even when K and V
- * are *not* @Nullable).
- *
- * An alternative to suppressing the warning would be to inline the body of the other
- * difference() method into this one.
- */
- @SuppressWarnings("nullness")
- MapDifference<K, V> result =
- (MapDifference<K, V>) difference(left, right, Equivalence.equals());
- return result;
+ return difference(left, right, Equivalence.equals());
}
/**
@@ -460,36 +459,11 @@ public final class Maps {
* @return the difference between the two maps
* @since 10.0
*/
- /*
- * This method should really be annotated to accept maps with @Nullable value types. Fortunately,
- * no existing Google callers appear to pass null values (much less pass null values *and* run a
- * nullness checker).
- *
- * Still, if we decide that we want to make that work, we'd need to introduce a new type parameter
- * for the Equivalence input type:
- *
- * <E, K extends @Nullable Object, V extends @Nullable E> ... difference(..., Equivalence<E> ...)
- *
- * Maybe we should, even though it will break source compatibility.
- *
- * Alternatively, this is a case in which it would be useful to be able to express Equivalence<?
- * super @Nonnull T>).
- *
- * As things stand now, though, we have to either:
- *
- * - require non-null inputs so that we can guarantee non-null outputs
- *
- * - accept nullable inputs but force users to cope with nullable outputs
- *
- * And the non-null option is far more useful to existing users.
- *
- * (Vaguely related: Another thing we could consider is an overload that accepts a BiPredicate:
- * https://github.com/google/guava/issues/3913)
- */
- public static <K extends @Nullable Object, V> MapDifference<K, V> difference(
- Map<? extends K, ? extends V> left,
- Map<? extends K, ? extends V> right,
- Equivalence<? super V> valueEquivalence) {
+ public static <K extends @Nullable Object, V extends @Nullable Object>
+ MapDifference<K, V> difference(
+ Map<? extends K, ? extends V> left,
+ Map<? extends K, ? extends V> right,
+ Equivalence<? super @NonNull V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newLinkedHashMap();
@@ -529,26 +503,14 @@ public final class Maps {
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator);
- /*
- * V is a possibly nullable type, but we decided to declare Equivalence with a type parameter
- * that is restricted to non-nullable types. Still, this code is safe: We made that decision
- * about Equivalence not because Equivalence is null-hostile but because *every* Equivalence can
- * handle null inputs -- and thus it would be meaningless for the type system to distinguish
- * between "an Equivalence for nullable Foo" and "an Equivalence for non-nullable Foo."
- *
- * (And the unchecked cast is safe because Equivalence is contravariant.)
- */
- @SuppressWarnings({"nullness", "unchecked"})
- Equivalence<V> equalsEquivalence = (Equivalence<V>) Equivalence.equals();
-
- doDifference(left, right, equalsEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
+ doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K extends @Nullable Object, V extends @Nullable Object> void doDifference(
Map<? extends K, ? extends V> left,
Map<? extends K, ? extends V> right,
- Equivalence<? super V> valueEquivalence,
+ Equivalence<? super @NonNull V> valueEquivalence,
Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight,
Map<K, V> onBoth,
@@ -1253,14 +1215,26 @@ public final class Maps {
* ...
* ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue);
*
- * Map<String, Color> colorForName =
- * uniqueIndex(allColors, toStringFunction());
+ * ImmutableMap<String, Color> colorForName =
+ * uniqueIndex(allColors, c -> c.toString());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterable, Function) Multimaps.index}.
*
+ * <p><b>Note:</b> on Java 8 and later, it is usually better to use streams. For example:
+ *
+ * <pre>{@code
+ * import static com.google.common.collect.ImmutableMap.toImmutableMap;
+ * ...
+ * ImmutableMap<String, Color> colorForName =
+ * allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c));
+ * }</pre>
+ *
+ * <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys
+ * and values in the map are.
+ *
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
@@ -1273,7 +1247,12 @@ public final class Maps {
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
- // TODO(lowasser): consider presizing the builder if values is a Collection
+ if (values instanceof Collection) {
+ return uniqueIndex(
+ values.iterator(),
+ keyFunction,
+ ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size()));
+ }
return uniqueIndex(values.iterator(), keyFunction);
}
@@ -1309,8 +1288,12 @@ public final class Maps {
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
+ return uniqueIndex(values, keyFunction, ImmutableMap.builder());
+ }
+
+ private static <K, V> ImmutableMap<K, V> uniqueIndex(
+ Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) {
checkNotNull(keyFunction);
- ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
@@ -1334,6 +1317,7 @@ public final class Maps {
* @throws ClassCastException if any key in {@code properties} is not a {@code String}
* @throws NullPointerException if any key or value in {@code properties} is null
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.Properties
public static ImmutableMap<String, String> fromProperties(Properties properties) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
@@ -1405,7 +1389,7 @@ public final class Maps {
/**
* Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation
- * throws an {@link UnsupportedOperationException}. This also has the side-effect of redefining
+ * throws an {@link UnsupportedOperationException}. This also has the side effect of redefining
* {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation
* of equals.
*
@@ -1446,7 +1430,7 @@ public final class Maps {
};
}
- /** @see Multimaps#unmodifiableEntries */
+ /** The implementation of {@link Multimaps#unmodifiableEntries}. */
static class UnmodifiableEntries<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
@@ -1468,15 +1452,14 @@ public final class Maps {
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override
- public Object[] toArray() {
+ public @Nullable Object[] toArray() {
/*
- * standardToArray returns `@Nullable Object[]` rather than `Object[]` but only because it can
+ * standardToArray returns `@Nullable Object[]` rather than `Object[]` but because it can
* be used with collections that may contain null. This collection never contains nulls, so we
- * can treat it as a plain `Object[]`.
+ * could return `Object[]`. But this class is private and J2KT cannot change return types in
+ * overrides, so we declare `@Nullable Object[]` as the return type.
*/
- @SuppressWarnings("nullness")
- Object[] result = standardToArray();
- return result;
+ return standardToArray();
}
@Override
@@ -1486,7 +1469,7 @@ public final class Maps {
}
}
- /** @see Maps#unmodifiableEntrySet(Set) */
+ /** The implementation of {@link Maps#unmodifiableEntrySet(Set)}. */
static class UnmodifiableEntrySet<K extends @Nullable Object, V extends @Nullable Object>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
@@ -1616,13 +1599,15 @@ public final class Maps {
return new UnmodifiableBiMap<>(bimap, null);
}
- /** @see Maps#unmodifiableBiMap(BiMap) */
+ /**
+ * @see Maps#unmodifiableBiMap(BiMap)
+ */
private static class UnmodifiableBiMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
- @RetainedWith @CheckForNull BiMap<V, K> inverse;
- @CheckForNull transient Set<V> values;
+ @LazyInit @RetainedWith @CheckForNull BiMap<V, K> inverse;
+ @LazyInit @CheckForNull transient Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @CheckForNull BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
@@ -1975,6 +1960,7 @@ public final class Maps {
* @throws NullPointerException if the key or value is null and this transformer does not accept
* null arguments
*/
+ @ParametricNullness
V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value);
}
@@ -3465,7 +3451,7 @@ public final class Maps {
throw new UnsupportedOperationException();
}
- @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
+ @LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
@Override
public NavigableMap<K, V> descendingMap() {
@@ -3595,7 +3581,7 @@ public final class Maps {
*/
abstract Set<Entry<K, V>> createEntrySet();
- @CheckForNull private transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -3603,7 +3589,7 @@ public final class Maps {
return (result == null) ? entrySet = createEntrySet() : result;
}
- @CheckForNull private transient Set<K> keySet;
+ @LazyInit @CheckForNull private transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -3615,7 +3601,7 @@ public final class Maps {
return new KeySet<>(this);
}
- @CheckForNull private transient Collection<V> values;
+ @LazyInit @CheckForNull private transient Collection<V> values;
@Override
public Collection<V> values() {
@@ -4144,7 +4130,7 @@ public final class Maps {
return forward();
}
- @CheckForNull private transient Comparator<? super K> comparator;
+ @LazyInit @CheckForNull private transient Comparator<? super K> comparator;
@SuppressWarnings("unchecked")
@Override
@@ -4254,7 +4240,7 @@ public final class Maps {
return forward();
}
- @CheckForNull private transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -4285,7 +4271,7 @@ public final class Maps {
return navigableKeySet();
}
- @CheckForNull private transient NavigableSet<K> navigableKeySet;
+ @LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet;
@Override
public NavigableSet<K> navigableKeySet() {
@@ -4369,7 +4355,6 @@ public final class Maps {
*
* @since 20.0
*/
- @Beta
@GwtIncompatible // NavigableMap
public static <K extends Comparable<? super K>, V extends @Nullable Object>
NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) {
diff --git a/android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java b/android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
index 181b3fbb5..877d6bc0b 100644
--- a/android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
+++ b/android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
@@ -23,8 +23,8 @@ import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -98,7 +98,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Torbjorn Gannholm
* @since 8.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
@@ -108,7 +107,7 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
* initial contents, and an initial expected size of 11.
*/
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() {
- return new Builder<Comparable>(Ordering.natural()).create();
+ return new Builder<Comparable<E>>(Ordering.natural()).create();
}
/**
@@ -162,7 +161,6 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
* Queue<Integer>} but not a {@code Queue<Object>}).
* @since 8.0
*/
- @Beta
public static final class Builder<B> {
/*
* TODO(kevinb): when the dust settles, see if we still need this or can
@@ -518,14 +516,17 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
}
/**
- * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap: a min-heap and a
+ * Each instance of MinMaxPriorityQueue encapsulates two instances of Heap: a min-heap and a
* max-heap. Conceptually, these might each have their own array for storage, but for efficiency's
* sake they are stored interleaved on alternate heap levels in the same array (MMPQ.queue).
*/
@WeakOuter
private class Heap {
final Ordering<E> ordering;
- @Weak Heap otherHeap; // always initialized immediately after construction
+
+ @SuppressWarnings("nullness:initialization.field.uninitialized")
+ @Weak
+ Heap otherHeap; // always initialized immediately after construction
Heap(Ordering<E> ordering) {
this.ordering = ordering;
@@ -644,17 +645,18 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
int parentIndex = getParentIndex(index);
E parentElement = elementData(parentIndex);
if (parentIndex != 0) {
- // This is a guard for the case of the childless uncle.
- // Since the end of the array is actually the middle of the heap,
- // a smaller childless uncle can become a child of x when we
- // bubble up alternate levels, violating the invariant.
+ /*
+ * This is a guard for the case of the childless aunt node. Since the end of the array is
+ * actually the middle of the heap, a smaller childless aunt node can become a child of x
+ * when we bubble up alternate levels, violating the invariant.
+ */
int grandparentIndex = getParentIndex(parentIndex);
- int uncleIndex = getRightChildIndex(grandparentIndex);
- if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
- E uncleElement = elementData(uncleIndex);
- if (ordering.compare(uncleElement, parentElement) < 0) {
- parentIndex = uncleIndex;
- parentElement = uncleElement;
+ int auntIndex = getRightChildIndex(grandparentIndex);
+ if (auntIndex != parentIndex && getLeftChildIndex(auntIndex) >= size) {
+ E auntElement = elementData(auntIndex);
+ if (ordering.compare(auntElement, parentElement) < 0) {
+ parentIndex = auntIndex;
+ parentElement = auntElement;
}
}
}
@@ -667,26 +669,30 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
return index;
}
+ // About the term "aunt node": it's better to leave gender out of it, but for this the English
+ // language has nothing for us. Except for the whimsical neologism "pibling" (!) which we
+ // obviously could not expect to increase anyone's understanding of the code.
+
/**
* Swap {@code actualLastElement} with the conceptually correct last element of the heap.
* Returns the index that {@code actualLastElement} now resides in.
*
* <p>Since the last element of the array is actually in the middle of the sorted structure, a
- * childless uncle node could be smaller, which would corrupt the invariant if this element
- * becomes the new parent of the uncle. In that case, we first switch the last element with its
- * uncle, before returning.
+ * childless aunt node could be smaller, which would corrupt the invariant if this element
+ * becomes the new parent of the aunt node. In that case, we first switch the last element with
+ * its aunt node, before returning.
*/
int swapWithConceptuallyLastElement(E actualLastElement) {
int parentIndex = getParentIndex(size);
if (parentIndex != 0) {
int grandparentIndex = getParentIndex(parentIndex);
- int uncleIndex = getRightChildIndex(grandparentIndex);
- if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
- E uncleElement = elementData(uncleIndex);
- if (ordering.compare(uncleElement, actualLastElement) < 0) {
- queue[uncleIndex] = actualLastElement;
- queue[size] = uncleElement;
- return uncleIndex;
+ int auntIndex = getRightChildIndex(grandparentIndex);
+ if (auntIndex != parentIndex && getLeftChildIndex(auntIndex) >= size) {
+ E auntElement = elementData(auntIndex);
+ if (ordering.compare(auntElement, actualLastElement) < 0) {
+ queue[auntIndex] = actualLastElement;
+ queue[size] = auntElement;
+ return auntIndex;
}
}
}
@@ -911,6 +917,7 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
}
@Override
+ @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation
public Object[] toArray() {
Object[] copyTo = new Object[size];
System.arraycopy(queue, 0, copyTo, 0, size);
diff --git a/android/guava/src/com/google/common/collect/Multimap.java b/android/guava/src/com/google/common/collect/Multimap.java
index 41aed97f1..75a8193a9 100644
--- a/android/guava/src/com/google/common/collect/Multimap.java
+++ b/android/guava/src/com/google/common/collect/Multimap.java
@@ -132,13 +132,16 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* <h3>Implementations</h3>
*
- * <p>As always, prefer the immutable implementations, {@link ImmutableListMultimap} and {@link
- * ImmutableSetMultimap}. General-purpose mutable implementations are listed above under "All Known
- * Implementing Classes". You can also create a <i>custom</i> multimap, backed by any {@code Map}
- * and {@link Collection} types, using the {@link Multimaps#newMultimap Multimaps.newMultimap}
- * family of methods. Finally, another popular way to obtain a multimap is using {@link
- * Multimaps#index Multimaps.index}. See the {@link Multimaps} class for these and other static
- * utilities related to multimaps.
+ * <ul>
+ * <li>{@link ImmutableListMultimap}
+ * <li>{@link ImmutableSetMultimap}
+ * <li>Configure your own mutable multimap with {@link MultimapBuilder}
+ * <li>{@link LinkedListMultimap} (for one unusual kind of mutable {@code Multimap})
+ * </ul>
+ *
+ * Guava contains a number of other multimap implementations, such as {@link ArrayListMultimap}. In
+ * new code, we recommend using {@link MultimapBuilder} instead: It provides better control of how
+ * keys and values are stored.
*
* <h3>Other Notes</h3>
*
diff --git a/android/guava/src/com/google/common/collect/MultimapBuilder.java b/android/guava/src/com/google/common/collect/MultimapBuilder.java
index 3d6278aae..8218da6b4 100644
--- a/android/guava/src/com/google/common/collect/MultimapBuilder.java
+++ b/android/guava/src/com/google/common/collect/MultimapBuilder.java
@@ -37,17 +37,14 @@ import java.util.TreeSet;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
- * A builder for a multimap implementation that allows customization of the backing map and value
- * collection implementations used in a particular multimap.
- *
- * <p>This can be used to easily configure multimap data structure implementations not provided
- * explicitly in {@code com.google.common.collect}, for example:
+ * An immutable builder for {@link Multimap} instances, letting you independently select the desired
+ * behaviors (for example, ordering) of the backing map and value-collections. Example:
*
* <pre>{@code
- * ListMultimap<String, Integer> treeListMultimap =
- * MultimapBuilder.treeKeys().arrayListValues().build();
- * SetMultimap<Integer, MyEnum> hashEnumMultimap =
- * MultimapBuilder.hashKeys().enumSetValues(MyEnum.class).build();
+ * ListMultimap<UserId, ErrorResponse> errorsByUser =
+ * MultimapBuilder.linkedHashKeys().arrayListValues().build();
+ * SortedSetMultimap<String, Method> methodsForName =
+ * MultimapBuilder.treeKeys().treeSetValues(this::compareMethods).build();
* }</pre>
*
* <p>{@code MultimapBuilder} instances are immutable. Invoking a configuration method has no effect
diff --git a/android/guava/src/com/google/common/collect/Multimaps.java b/android/guava/src/com/google/common/collect/Multimaps.java
index 9976b4a66..ea4148801 100644
--- a/android/guava/src/com/google/common/collect/Multimaps.java
+++ b/android/guava/src/com/google/common/collect/Multimaps.java
@@ -22,9 +22,9 @@ import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
@@ -171,8 +171,11 @@ public final class Multimaps {
// can't use Serialization writeMultimap and populateMultimap methods since
// there's no way to generate the empty backing map.
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -180,6 +183,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -189,6 +193,7 @@ public final class Multimaps {
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -252,8 +257,11 @@ public final class Multimaps {
return factory.get();
}
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -261,6 +269,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -270,6 +279,7 @@ public final class Multimaps {
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -355,8 +365,11 @@ public final class Multimaps {
}
}
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -364,6 +377,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -373,6 +387,7 @@ public final class Multimaps {
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -444,8 +459,11 @@ public final class Multimaps {
return valueComparator;
}
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -453,6 +471,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -463,6 +482,7 @@ public final class Multimaps {
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -585,13 +605,7 @@ public final class Multimaps {
map =
Collections.unmodifiableMap(
Maps.transformValues(
- delegate.asMap(),
- new Function<Collection<V>, Collection<V>>() {
- @Override
- public Collection<V> apply(Collection<V> collection) {
- return unmodifiableValueCollection(collection);
- }
- }));
+ delegate.asMap(), collection -> unmodifiableValueCollection(collection)));
}
return result;
}
@@ -942,7 +956,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
@SuppressWarnings("unchecked")
// safe by specification of ListMultimap.asMap()
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, List<V>> asMap(
@@ -956,7 +969,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
@SuppressWarnings("unchecked")
// safe by specification of SetMultimap.asMap()
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, Set<V>> asMap(
@@ -970,7 +982,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
@SuppressWarnings("unchecked")
// safe by specification of SortedSetMultimap.asMap()
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, SortedSet<V>> asMap(
@@ -984,7 +995,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
public static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, Collection<V>> asMap(Multimap<K, V> multimap) {
return multimap.asMap();
@@ -1401,14 +1411,7 @@ public final class Multimaps {
@Override
Map<K, Collection<V2>> createAsMap() {
- return Maps.transformEntries(
- fromMultimap.asMap(),
- new EntryTransformer<K, Collection<V1>, Collection<V2>>() {
- @Override
- public Collection<V2> transformEntry(@ParametricNullness K key, Collection<V1> value) {
- return transform(key, value);
- }
- });
+ return Maps.transformEntries(fromMultimap.asMap(), (key, value) -> transform(key, value));
}
@Override
@@ -1779,14 +1782,7 @@ public final class Multimaps {
@Override
public Iterator<Entry<K, Collection<V>>> iterator() {
- return Maps.asMapEntryIterator(
- multimap.keySet(),
- new Function<K, Collection<V>>() {
- @Override
- public Collection<V> apply(@ParametricNullness K key) {
- return multimap.get(key);
- }
- });
+ return Maps.asMapEntryIterator(multimap.keySet(), key -> multimap.get(key));
}
@Override
diff --git a/android/guava/src/com/google/common/collect/Multiset.java b/android/guava/src/com/google/common/collect/Multiset.java
index f60046fa4..a504a363f 100644
--- a/android/guava/src/com/google/common/collect/Multiset.java
+++ b/android/guava/src/com/google/common/collect/Multiset.java
@@ -66,8 +66,17 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* element (in a way that affects its {@link Object#equals} behavior) while it is contained in a
* multiset. Undefined behavior and bugs will result.
*
- * <p>Common implementations include {@link ImmutableMultiset}, {@link HashMultiset}, and {@link
- * ConcurrentHashMultiset}.
+ * <h3>Implementations</h3>
+ *
+ * <ul>
+ * <li>{@link ImmutableMultiset}
+ * <li>{@link ImmutableSortedMultiset}
+ * <li>{@link HashMultiset}
+ * <li>{@link LinkedHashMultiset}
+ * <li>{@link TreeMultiset}
+ * <li>{@link EnumMultiset}
+ * <li>{@link ConcurrentHashMultiset}
+ * </ul>
*
* <p>If your values may be zero, negative, or outside the range of an int, you may wish to use
* {@link com.google.common.util.concurrent.AtomicLongMap} instead. Note, however, that unlike
diff --git a/android/guava/src/com/google/common/collect/Multisets.java b/android/guava/src/com/google/common/collect/Multisets.java
index a9bcb0428..8bcc639ab 100644
--- a/android/guava/src/com/google/common/collect/Multisets.java
+++ b/android/guava/src/com/google/common/collect/Multisets.java
@@ -22,7 +22,6 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
@@ -31,6 +30,7 @@ import com.google.common.collect.Multiset.Entry;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -105,7 +105,7 @@ public final class Multisets {
return (Multiset<E>) delegate;
}
- @CheckForNull transient Set<E> elementSet;
+ @LazyInit @CheckForNull transient Set<E> elementSet;
Set<E> createElementSet() {
return Collections.<E>unmodifiableSet(delegate.elementSet());
@@ -117,7 +117,7 @@ public final class Multisets {
return (es == null) ? elementSet = createElementSet() : es;
}
- @CheckForNull transient Set<Multiset.Entry<E>> entrySet;
+ @LazyInit @CheckForNull transient Set<Multiset.Entry<E>> entrySet;
@SuppressWarnings("unchecked")
@Override
@@ -199,7 +199,6 @@ public final class Multisets {
* @return an unmodifiable view of the multiset
* @since 11.0
*/
- @Beta
public static <E extends @Nullable Object> SortedMultiset<E> unmodifiableSortedMultiset(
SortedMultiset<E> sortedMultiset) {
// it's in its own file so it can be emulated for GWT
@@ -274,7 +273,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> filter(
Multiset<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredMultiset) {
@@ -381,7 +379,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> union(
final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
checkNotNull(multiset1);
@@ -511,7 +508,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> sum(
final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
checkNotNull(multiset1);
@@ -589,7 +585,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> difference(
final Multiset<E> multiset1, final Multiset<?> multiset2) {
checkNotNull(multiset1);
@@ -1138,12 +1133,11 @@ public final class Multisets {
}
/**
- * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is
- * highest count first, with ties broken by the iteration order of the original multiset.
+ * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts
+ * the highest count first, with ties broken by the iteration order of the original multiset.
*
* @since 11.0
*/
- @Beta
public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray(new Entry[0]);
Arrays.sort(entries, DecreasingCount.INSTANCE);
diff --git a/android/guava/src/com/google/common/collect/MutableClassToInstanceMap.java b/android/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
index 2fcf0d664..ea5199561 100644
--- a/android/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
+++ b/android/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
@@ -19,8 +19,11 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
@@ -28,6 +31,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -38,24 +42,23 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
* ClassToInstanceMap}</a>.
*
- * <p>This implementation <i>does</i> support null values, despite how it is annotated; see
- * discussion at {@link ClassToInstanceMap}.
- *
* @author Kevin Bourrillion
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings("serial") // using writeReplace instead of standard serialization
@ElementTypesAreNonnullByDefault
-public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B>
+public final class MutableClassToInstanceMap<B extends @Nullable Object>
+ extends ForwardingMap<Class<? extends @NonNull B>, B>
implements ClassToInstanceMap<B>, Serializable {
/**
* Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link HashMap} using the
* default initial capacity and load factor.
*/
- public static <B> MutableClassToInstanceMap<B> create() {
- return new MutableClassToInstanceMap<B>(new HashMap<Class<? extends B>, B>());
+ public static <B extends @Nullable Object> MutableClassToInstanceMap<B> create() {
+ return new MutableClassToInstanceMap<B>(new HashMap<Class<? extends @NonNull B>, B>());
}
/**
@@ -63,50 +66,59 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
* backingMap}. The caller surrenders control of the backing map, and thus should not allow any
* direct references to it to remain accessible.
*/
- public static <B> MutableClassToInstanceMap<B> create(Map<Class<? extends B>, B> backingMap) {
+ public static <B extends @Nullable Object> MutableClassToInstanceMap<B> create(
+ Map<Class<? extends @NonNull B>, B> backingMap) {
return new MutableClassToInstanceMap<B>(backingMap);
}
- private final Map<Class<? extends B>, B> delegate;
+ private final Map<Class<? extends @NonNull B>, B> delegate;
- private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) {
+ private MutableClassToInstanceMap(Map<Class<? extends @NonNull B>, B> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
- protected Map<Class<? extends B>, B> delegate() {
+ protected Map<Class<? extends @NonNull B>, B> delegate() {
return delegate;
}
- static <B> Entry<Class<? extends B>, B> checkedEntry(final Entry<Class<? extends B>, B> entry) {
- return new ForwardingMapEntry<Class<? extends B>, B>() {
+ /**
+ * Wraps the {@code setValue} implementation of an {@code Entry} to enforce the class constraint.
+ */
+ private static <B extends @Nullable Object> Entry<Class<? extends @NonNull B>, B> checkedEntry(
+ final Entry<Class<? extends @NonNull B>, B> entry) {
+ return new ForwardingMapEntry<Class<? extends @NonNull B>, B>() {
@Override
- protected Entry<Class<? extends B>, B> delegate() {
+ protected Entry<Class<? extends @NonNull B>, B> delegate() {
return entry;
}
@Override
- public B setValue(B value) {
- return super.setValue(cast(getKey(), value));
+ @ParametricNullness
+ public B setValue(@ParametricNullness B value) {
+ cast(getKey(), value);
+ return super.setValue(value);
}
};
}
@Override
- public Set<Entry<Class<? extends B>, B>> entrySet() {
- return new ForwardingSet<Entry<Class<? extends B>, B>>() {
+ public Set<Entry<Class<? extends @NonNull B>, B>> entrySet() {
+ return new ForwardingSet<Entry<Class<? extends @NonNull B>, B>>() {
@Override
- protected Set<Entry<Class<? extends B>, B>> delegate() {
+ protected Set<Entry<Class<? extends @NonNull B>, B>> delegate() {
return MutableClassToInstanceMap.this.delegate().entrySet();
}
@Override
- public Iterator<Entry<Class<? extends B>, B>> iterator() {
- return new TransformedIterator<Entry<Class<? extends B>, B>, Entry<Class<? extends B>, B>>(
+ public Iterator<Entry<Class<? extends @NonNull B>, B>> iterator() {
+ return new TransformedIterator<
+ Entry<Class<? extends @NonNull B>, B>, Entry<Class<? extends @NonNull B>, B>>(
delegate().iterator()) {
@Override
- Entry<Class<? extends B>, B> transform(Entry<Class<? extends B>, B> from) {
+ Entry<Class<? extends @NonNull B>, B> transform(
+ Entry<Class<? extends @NonNull B>, B> from) {
return checkedEntry(from);
}
};
@@ -136,14 +148,15 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
@Override
@CanIgnoreReturnValue
@CheckForNull
- public B put(Class<? extends B> key, B value) {
- return super.put(key, cast(key, value));
+ public B put(Class<? extends @NonNull B> key, @ParametricNullness B value) {
+ cast(key, value);
+ return super.put(key, value);
}
@Override
- public void putAll(Map<? extends Class<? extends B>, ? extends B> map) {
- Map<Class<? extends B>, B> copy = new LinkedHashMap<>(map);
- for (Entry<? extends Class<? extends B>, B> entry : copy.entrySet()) {
+ public void putAll(Map<? extends Class<? extends @NonNull B>, ? extends B> map) {
+ Map<Class<? extends @NonNull B>, B> copy = new LinkedHashMap<>(map);
+ for (Entry<? extends Class<? extends @NonNull B>, B> entry : copy.entrySet()) {
cast(entry.getKey(), entry.getValue());
}
super.putAll(copy);
@@ -152,19 +165,19 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
@CanIgnoreReturnValue
@Override
@CheckForNull
- public <T extends B> T putInstance(Class<T> type, T value) {
+ public <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value) {
return cast(type, put(type, value));
}
@Override
@CheckForNull
- public <T extends B> T getInstance(Class<T> type) {
+ public <T extends @NonNull B> T getInstance(Class<T> type) {
return cast(type, get(type));
}
@CanIgnoreReturnValue
@CheckForNull
- private static <B, T extends B> T cast(Class<T> type, @CheckForNull B value) {
+ private static <T> T cast(Class<T> type, @CheckForNull Object value) {
return Primitives.wrap(type).cast(value);
}
@@ -172,11 +185,15 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
return new SerializedForm(delegate());
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/** Serialized form of the map, to avoid serializing the constraint. */
- private static final class SerializedForm<B> implements Serializable {
- private final Map<Class<? extends B>, B> backingMap;
+ private static final class SerializedForm<B extends @Nullable Object> implements Serializable {
+ private final Map<Class<? extends @NonNull B>, B> backingMap;
- SerializedForm(Map<Class<? extends B>, B> backingMap) {
+ SerializedForm(Map<Class<? extends @NonNull B>, B> backingMap) {
this.backingMap = backingMap;
}
diff --git a/android/guava/src/com/google/common/collect/NaturalOrdering.java b/android/guava/src/com/google/common/collect/NaturalOrdering.java
index 8cb8aef9a..dae531270 100644
--- a/android/guava/src/com/google/common/collect/NaturalOrdering.java
+++ b/android/guava/src/com/google/common/collect/NaturalOrdering.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -30,8 +31,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
final class NaturalOrdering extends Ordering<Comparable<?>> implements Serializable {
static final NaturalOrdering INSTANCE = new NaturalOrdering();
- @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsFirst;
- @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsLast;
+ // TODO: b/287198172 - Consider eagerly initializing these (but think about serialization).
+ @LazyInit @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsFirst;
+ @LazyInit @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsLast;
@Override
public int compare(Comparable<?> left, Comparable<?> right) {
diff --git a/android/guava/src/com/google/common/collect/NullsFirstOrdering.java b/android/guava/src/com/google/common/collect/NullsFirstOrdering.java
index ce8be2fa3..c451ea8c0 100644
--- a/android/guava/src/com/google/common/collect/NullsFirstOrdering.java
+++ b/android/guava/src/com/google/common/collect/NullsFirstOrdering.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** An ordering that treats {@code null} as less than all other values. */
@@ -50,18 +51,18 @@ final class NullsFirstOrdering<T extends @Nullable Object> extends Ordering<@Nul
@SuppressWarnings("nullness") // should be safe, but not sure if we can avoid the warning
public <S extends @Nullable T> Ordering<S> reverse() {
// ordering.reverse() might be optimized, so let it do its thing
- return ordering.reverse().nullsLast();
+ return ordering.<T>reverse().<@NonNull S>nullsLast();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override
- public <S extends T> Ordering<@Nullable S> nullsFirst() {
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsFirst() {
return (Ordering<@Nullable S>) this;
}
@Override
- public <S extends T> Ordering<@Nullable S> nullsLast() {
- return ordering.<S>nullsLast();
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsLast() {
+ return ordering.<@NonNull S>nullsLast();
}
@Override
diff --git a/android/guava/src/com/google/common/collect/NullsLastOrdering.java b/android/guava/src/com/google/common/collect/NullsLastOrdering.java
index 6f8f74cdd..88917852e 100644
--- a/android/guava/src/com/google/common/collect/NullsLastOrdering.java
+++ b/android/guava/src/com/google/common/collect/NullsLastOrdering.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** An ordering that treats {@code null} as greater than all other values. */
@@ -50,17 +51,17 @@ final class NullsLastOrdering<T extends @Nullable Object> extends Ordering<@Null
@SuppressWarnings("nullness") // should be safe, but not sure if we can avoid the warning
public <S extends @Nullable T> Ordering<S> reverse() {
// ordering.reverse() might be optimized, so let it do its thing
- return ordering.reverse().nullsFirst();
+ return ordering.<T>reverse().<@NonNull S>nullsFirst();
}
@Override
- public <S extends T> Ordering<@Nullable S> nullsFirst() {
- return ordering.<S>nullsFirst();
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsFirst() {
+ return ordering.<@NonNull S>nullsFirst();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override
- public <S extends T> Ordering<@Nullable S> nullsLast() {
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsLast() {
return (Ordering<@Nullable S>) this;
}
diff --git a/android/guava/src/com/google/common/collect/ObjectArrays.java b/android/guava/src/com/google/common/collect/ObjectArrays.java
index 0f928e170..309572afd 100644
--- a/android/guava/src/com/google/common/collect/ObjectArrays.java
+++ b/android/guava/src/com/google/common/collect/ObjectArrays.java
@@ -25,6 +25,7 @@ import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -35,6 +36,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
+@SuppressWarnings("AvoidObjectArrays")
public final class ObjectArrays {
private ObjectArrays() {}
@@ -47,7 +49,7 @@ public final class ObjectArrays {
*/
@GwtIncompatible // Array.newInstance(Class, int)
@SuppressWarnings("unchecked")
- public static <T> T[] newArray(Class<T> type, int length) {
+ public static <T extends @Nullable Object> T[] newArray(Class<@NonNull T> type, int length) {
return (T[]) Array.newInstance(type, length);
}
@@ -69,7 +71,8 @@ public final class ObjectArrays {
* @param type the component type of the returned array
*/
@GwtIncompatible // Array.newInstance(Class, int)
- public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
+ public static <T extends @Nullable Object> T[] concat(
+ T[] first, T[] second, Class<@NonNull T> type) {
T[] result = newArray(type, first.length + second.length);
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
diff --git a/android/guava/src/com/google/common/collect/Ordering.java b/android/guava/src/com/google/common/collect/Ordering.java
index 025f95fb7..86318aa44 100644
--- a/android/guava/src/com/google/common/collect/Ordering.java
+++ b/android/guava/src/com/google/common/collect/Ordering.java
@@ -20,9 +20,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -39,6 +39,7 @@ import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -172,6 +173,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* to pass it in here. Instead, simply subclass {@code Ordering} and implement its {@code compare}
* method directly.
*
+ * <p>The returned object is serializable if {@code comparator} is serializable.
+ *
* <p><b>Java 8 users:</b> this class is now obsolete as explained in the class documentation, so
* there is no need to use this method.
*
@@ -313,14 +316,17 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* @since 2.0
*/
// TODO(kevinb): copy to Comparators, etc.
+ @J2ktIncompatible // MapMaker
public static Ordering<@Nullable Object> arbitrary() {
return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
}
+ @J2ktIncompatible // MapMaker
private static class ArbitraryOrderingHolder {
static final Ordering<@Nullable Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
}
+ @J2ktIncompatible // MapMaker
@VisibleForTesting
static class ArbitraryOrdering extends Ordering<@Nullable Object> {
@@ -411,6 +417,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* Returns an ordering that treats {@code null} as less than all other values and uses {@code
* this} to compare non-null values.
*
+ * <p>The returned object is serializable if this object is serializable.
+ *
* <p><b>Java 8 users:</b> Use {@code Comparator.nullsFirst(thisComparator)} instead.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
@@ -424,6 +432,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* Returns an ordering that treats {@code null} as greater than all other values and uses this
* ordering to compare non-null values.
*
+ * <p>The returned object is serializable if this object is serializable.
+ *
* <p><b>Java 8 users:</b> Use {@code Comparator.nullsLast(thisComparator)} instead.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
@@ -464,6 +474,9 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p>An ordering produced by this method, or a chain of calls to this method, is equivalent to
* one created using {@link Ordering#compound(Iterable)} on the same component comparators.
*
+ * <p>The returned object is serializable if this object and {@code secondaryComparator} are both
+ * serializable.
+ *
* <p><b>Java 8 users:</b> Use {@code thisComparator.thenComparing(secondaryComparator)} instead.
* Depending on what {@code secondaryComparator} is, one of the other overloads of {@code
* thenComparing} may be even more useful.
@@ -482,6 +495,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p>The returned ordering is equivalent to that produced using {@code
* Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
*
+ * <p>The returned object is serializable if each of the {@code comparators} is serializable.
+ *
* <p><b>Warning:</b> Supplying an argument with undefined iteration order, such as a {@link
* HashSet}, will produce non-deterministic results.
*
@@ -530,7 +545,6 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
// Regular instance methods
- @CanIgnoreReturnValue // TODO(kak): Consider removing this
@Override
public abstract int compare(@ParametricNullness T left, @ParametricNullness T right);
@@ -567,7 +581,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p><b>Java 8 users:</b> If {@code iterable} is a {@link Collection}, use {@code
* Collections.min(collection, thisComparator)} instead. Otherwise, use {@code
* Streams.stream(iterable).min(thisComparator).get()} instead. Note that these alternatives do
- * not guarantee which tied minimum element is returned)
+ * not guarantee which tied minimum element is returned.
*
* @param iterable the iterable whose minimum element is to be determined
* @throws NoSuchElementException if {@code iterable} is empty
@@ -658,7 +672,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p><b>Java 8 users:</b> If {@code iterable} is a {@link Collection}, use {@code
* Collections.max(collection, thisComparator)} instead. Otherwise, use {@code
* Streams.stream(iterable).max(thisComparator).get()} instead. Note that these alternatives do
- * not guarantee which tied maximum element is returned)
+ * not guarantee which tied maximum element is returned.
*
* @param iterable the iterable whose maximum element is to be determined
* @throws NoSuchElementException if {@code iterable} is empty
@@ -809,7 +823,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
// TODO(kevinb): see if delegation is hurting performance noticeably
// TODO(kevinb): if we change this implementation, add full unit tests.
- return reverse().leastOf(iterable, k);
+ return this.<E>reverse().leastOf(iterable, k);
}
/**
@@ -829,7 +843,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* @since 14.0
*/
public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) {
- return reverse().leastOf(iterator, k);
+ return this.<E>reverse().leastOf(iterator, k);
}
/**
@@ -871,8 +885,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* @since 3.0
*/
// TODO(kevinb): rerun benchmarks including new options
- @SuppressWarnings("nullness") // unsafe, but there's not much we can do about it now
- public <E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) {
+ public <E extends @NonNull T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) {
return ImmutableList.sortedCopyOf(this, elements);
}
diff --git a/android/guava/src/com/google/common/collect/ParametricNullness.java b/android/guava/src/com/google/common/collect/ParametricNullness.java
index 94b1bcd3a..207c05262 100644
--- a/android/guava/src/com/google/common/collect/ParametricNullness.java
+++ b/android/guava/src/com/google/common/collect/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/collect/Platform.java b/android/guava/src/com/google/common/collect/Platform.java
index 0b18e1ff3..f09f6d446 100644
--- a/android/guava/src/com/google/common/collect/Platform.java
+++ b/android/guava/src/com/google/common/collect/Platform.java
@@ -17,7 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
-import java.lang.reflect.Array;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
@@ -89,13 +89,8 @@ final class Platform {
* ObjectArrays, which is the main caller of this method.)
*/
static <T extends @Nullable Object> T[] newArray(T[] reference, int length) {
- Class<?> type = reference.getClass().getComponentType();
-
- // the cast is safe because
- // result.getClass() == reference.getClass().getComponentType()
- @SuppressWarnings("unchecked")
- T[] result = (T[]) Array.newInstance(type, length);
- return result;
+ T[] empty = reference.length == 0 ? reference : Arrays.copyOf(reference, 0);
+ return Arrays.copyOf(empty, length);
}
/** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */
@@ -117,10 +112,15 @@ final class Platform {
* GWT). This is sometimes acceptable, when only server-side code could generate enough volume
* that reclamation becomes important.
*/
+ @J2ktIncompatible
static MapMaker tryWeakKeys(MapMaker mapMaker) {
return mapMaker.weakKeys();
}
+ static <E extends Enum<E>> Class<E> getDeclaringClassOrObjectForJ2cl(E e) {
+ return e.getDeclaringClass();
+ }
+
static int reduceIterationsIfGwt(int iterations) {
return iterations;
}
@@ -129,7 +129,5 @@ final class Platform {
return exponent;
}
- static void checkGwtRpcEnabled() {}
-
private Platform() {}
}
diff --git a/android/guava/src/com/google/common/collect/Queues.java b/android/guava/src/com/google/common/collect/Queues.java
index 6a4dbd227..859120693 100644
--- a/android/guava/src/com/google/common/collect/Queues.java
+++ b/android/guava/src/com/google/common/collect/Queues.java
@@ -14,9 +14,9 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayDeque;
@@ -52,6 +52,7 @@ public final class Queues {
* Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity and nonfair access
* policy.
*/
+ @J2ktIncompatible
@GwtIncompatible // ArrayBlockingQueue
public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) {
return new ArrayBlockingQueue<E>(capacity);
@@ -86,6 +87,7 @@ public final class Queues {
// ConcurrentLinkedQueue
/** Creates an empty {@code ConcurrentLinkedQueue}. */
+ @J2ktIncompatible
@GwtIncompatible // ConcurrentLinkedQueue
public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() {
return new ConcurrentLinkedQueue<E>();
@@ -95,6 +97,7 @@ public final class Queues {
* Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, in
* the order they are returned by the iterable's iterator.
*/
+ @J2ktIncompatible
@GwtIncompatible // ConcurrentLinkedQueue
public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue(
Iterable<? extends E> elements) {
@@ -113,6 +116,7 @@ public final class Queues {
*
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingDeque
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() {
return new LinkedBlockingDeque<E>();
@@ -124,6 +128,7 @@ public final class Queues {
* @throws IllegalArgumentException if {@code capacity} is less than 1
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingDeque
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) {
return new LinkedBlockingDeque<E>(capacity);
@@ -136,6 +141,7 @@ public final class Queues {
*
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingDeque
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
@@ -149,6 +155,7 @@ public final class Queues {
// LinkedBlockingQueue
/** Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingQueue
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() {
return new LinkedBlockingQueue<E>();
@@ -159,6 +166,7 @@ public final class Queues {
*
* @throws IllegalArgumentException if {@code capacity} is less than 1
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingQueue
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) {
return new LinkedBlockingQueue<E>(capacity);
@@ -172,6 +180,7 @@ public final class Queues {
* @param elements the elements that the queue should contain, in order
* @return a new {@code LinkedBlockingQueue} containing those elements
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingQueue
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
@@ -193,6 +202,7 @@ public final class Queues {
* @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
* in 15.0)
*/
+ @J2ktIncompatible
@GwtIncompatible // PriorityBlockingQueue
public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() {
return new PriorityBlockingQueue<E>();
@@ -207,6 +217,7 @@ public final class Queues {
* @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
* in 15.0)
*/
+ @J2ktIncompatible
@GwtIncompatible // PriorityBlockingQueue
public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(
Iterable<? extends E> elements) {
@@ -253,6 +264,7 @@ public final class Queues {
// SynchronousQueue
/** Creates an empty {@code SynchronousQueue} with nonfair access policy. */
+ @J2ktIncompatible
@GwtIncompatible // SynchronousQueue
public static <E> SynchronousQueue<E> newSynchronousQueue() {
return new SynchronousQueue<E>();
@@ -270,8 +282,8 @@ public final class Queues {
* @return the number of elements transferred
* @throws InterruptedException if interrupted while waiting
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // BlockingQueue
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <E> int drain(
@@ -318,8 +330,8 @@ public final class Queues {
* @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
* @return the number of elements transferred
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // BlockingQueue
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <E> int drainUninterruptibly(
diff --git a/android/guava/src/com/google/common/collect/Range.java b/android/guava/src/com/google/common/collect/Range.java
index 2a5d464dc..fa6607dd8 100644
--- a/android/guava/src/com/google/common/collect/Range.java
+++ b/android/guava/src/com/google/common/collect/Range.java
@@ -23,6 +23,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
+import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
@@ -105,6 +106,7 @@ import javax.annotation.CheckForNull;
* <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}.
* Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having
* property <i>P</i>. See, for example, the definition of {@link #intersection intersection}.
+ * <li>A {@code Range} is serializable if it has no bounds, or if each bound is serializable.
* </ul>
*
* <h3>Further reading</h3>
@@ -118,6 +120,7 @@ import javax.annotation.CheckForNull;
*/
@GwtCompatible
@SuppressWarnings("rawtypes")
+@Immutable(containerOf = "C")
@ElementTypesAreNonnullByDefault
public final class Range<C extends Comparable> extends RangeGwtSerializationDependencies
implements Predicate<C>, Serializable {
@@ -333,7 +336,7 @@ public final class Range<C extends Comparable> extends RangeGwtSerializationDepe
if (values instanceof SortedSet) {
SortedSet<C> set = (SortedSet<C>) values;
Comparator<?> comparator = set.comparator();
- if (Ordering.natural().equals(comparator) || comparator == null) {
+ if (Ordering.<C>natural().equals(comparator) || comparator == null) {
return closed(set.first(), set.last());
}
}
@@ -342,8 +345,8 @@ public final class Range<C extends Comparable> extends RangeGwtSerializationDepe
C max = min;
while (valueIterator.hasNext()) {
C value = checkNotNull(valueIterator.next());
- min = Ordering.natural().min(min, value);
- max = Ordering.natural().max(max, value);
+ min = Ordering.<C>natural().min(min, value);
+ max = Ordering.<C>natural().max(max, value);
}
return closed(min, max);
}
diff --git a/android/guava/src/com/google/common/collect/RangeMap.java b/android/guava/src/com/google/common/collect/RangeMap.java
index 14adb00c1..4eab7e49e 100644
--- a/android/guava/src/com/google/common/collect/RangeMap.java
+++ b/android/guava/src/com/google/common/collect/RangeMap.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Collection;
@@ -35,7 +34,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@DoNotMock("Use ImmutableRangeMap or TreeRangeMap")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
@@ -101,7 +99,7 @@ public interface RangeMap<K extends Comparable, V> {
void putCoalescing(Range<K> range, V value);
/** Puts all the associations from {@code rangeMap} into this range map (optional operation). */
- void putAll(RangeMap<K, V> rangeMap);
+ void putAll(RangeMap<K, ? extends V> rangeMap);
/** Removes all associations from this range map (optional operation). */
void clear();
diff --git a/android/guava/src/com/google/common/collect/RangeSet.java b/android/guava/src/com/google/common/collect/RangeSet.java
index 8d61cf351..7c74366df 100644
--- a/android/guava/src/com/google/common/collect/RangeSet.java
+++ b/android/guava/src/com/google/common/collect/RangeSet.java
@@ -14,7 +14,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.util.NoSuchElementException;
@@ -49,7 +48,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@DoNotMock("Use ImmutableRangeSet or TreeRangeSet")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
diff --git a/android/guava/src/com/google/common/collect/RegularContiguousSet.java b/android/guava/src/com/google/common/collect/RegularContiguousSet.java
index 787606eb1..9c2e5a26f 100644
--- a/android/guava/src/com/google/common/collect/RegularContiguousSet.java
+++ b/android/guava/src/com/google/common/collect/RegularContiguousSet.java
@@ -22,6 +22,9 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import javax.annotation.CheckForNull;
@@ -181,8 +184,8 @@ final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C>
if (other.isEmpty()) {
return other;
} else {
- C lowerEndpoint = Ordering.natural().max(this.first(), other.first());
- C upperEndpoint = Ordering.natural().min(this.last(), other.last());
+ C lowerEndpoint = Ordering.<C>natural().max(this.first(), other.first());
+ C upperEndpoint = Ordering.<C>natural().min(this.last(), other.last());
return (lowerEndpoint.compareTo(upperEndpoint) <= 0)
? ContiguousSet.create(Range.closed(lowerEndpoint, upperEndpoint), domain)
: new EmptyContiguousSet<C>(domain);
@@ -221,6 +224,7 @@ final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C>
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private static final class SerializedForm<C extends Comparable> implements Serializable {
final Range<C> range;
final DiscreteDomain<C> domain;
@@ -236,10 +240,17 @@ final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C>
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm<>(range, domain);
}
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/RegularImmutableMap.java b/android/guava/src/com/google/common/collect/RegularImmutableMap.java
index fc8082c7b..d6d214b65 100644
--- a/android/guava/src/com/google/common/collect/RegularImmutableMap.java
+++ b/android/guava/src/com/google/common/collect/RegularImmutableMap.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.AbstractMap;
import java.util.Arrays;
@@ -549,5 +550,6 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/Serialization.java b/android/guava/src/com/google/common/collect/Serialization.java
index 4ab53f2d7..e12e84cd2 100644
--- a/android/guava/src/com/google/common/collect/Serialization.java
+++ b/android/guava/src/com/google/common/collect/Serialization.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -34,6 +35,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jared Levy
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
final class Serialization {
private Serialization() {}
diff --git a/android/guava/src/com/google/common/collect/Sets.java b/android/guava/src/com/google/common/collect/Sets.java
index 994863099..1f433f4b6 100644
--- a/android/guava/src/com/google/common/collect/Sets.java
+++ b/android/guava/src/com/google/common/collect/Sets.java
@@ -20,15 +20,16 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
@@ -50,6 +51,7 @@ import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -425,6 +427,7 @@ public final class Sets {
* @return a new, empty {@code CopyOnWriteArraySet}
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
return new CopyOnWriteArraySet<E>();
@@ -437,6 +440,7 @@ public final class Sets {
* @return a new {@code CopyOnWriteArraySet} containing those elements
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
Iterable<? extends E> elements) {
@@ -462,6 +466,8 @@ public final class Sets {
* @throws IllegalArgumentException if {@code collection} is not an {@code EnumSet} instance and
* contains no elements
*/
+ @J2ktIncompatible
+ @GwtIncompatible
public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) {
if (collection instanceof EnumSet) {
return EnumSet.complementOf((EnumSet<E>) collection);
@@ -482,6 +488,7 @@ public final class Sets {
* @return a new, modifiable {@code EnumSet} initially containing all the values of the enum not
* present in the given collection
*/
+ @GwtIncompatible
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection, Class<E> type) {
checkNotNull(collection);
@@ -490,6 +497,7 @@ public final class Sets {
: makeComplementByHand(collection, type);
}
+ @GwtIncompatible
private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
Collection<E> collection, Class<E> type) {
EnumSet<E> result = EnumSet.allOf(type);
@@ -553,8 +561,8 @@ public final class Sets {
* that is inconsistent with {@link Object#equals(Object)}.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't fix it now.
- public ImmutableSet<E> immutableCopy() {
- return ImmutableSet.copyOf(this);
+ public ImmutableSet<@NonNull E> immutableCopy() {
+ return ImmutableSet.copyOf((SetView<@NonNull E>) this);
}
/**
@@ -732,9 +740,13 @@ public final class Sets {
}
@Override
- @SuppressWarnings("nullness") // see supertype
- public ImmutableSet<E> immutableCopy() {
- return new ImmutableSet.Builder<E>().addAll(set1).addAll(set2).build();
+ @SuppressWarnings({"nullness", "unchecked"}) // see supertype
+ public ImmutableSet<@NonNull E> immutableCopy() {
+ ImmutableSet.Builder<@NonNull E> builder =
+ new ImmutableSet.Builder<@NonNull E>()
+ .addAll((Iterable<@NonNull E>) set1)
+ .addAll((Iterable<@NonNull E>) set2);
+ return (ImmutableSet<@NonNull E>) builder.build();
}
};
}
@@ -1589,7 +1601,6 @@ public final class Sets {
* @throws NullPointerException if {@code set} is or contains {@code null}
* @since 23.0
*/
- @Beta
public static <E> Set<Set<E>> combinations(Set<E> set, final int size) {
final ImmutableMap<E, Integer> index = Maps.indexMap(set);
checkNonnegative(size, "size");
@@ -1727,6 +1738,8 @@ public final class Sets {
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
+ * <p><b>Java 8 users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}.
+ *
* @param set the navigable set for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable set
* @since 12.0
@@ -1790,7 +1803,7 @@ public final class Sets {
throw new UnsupportedOperationException();
}
- @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
+ @LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
@Override
public NavigableSet<E> descendingSet() {
@@ -1871,6 +1884,8 @@ public final class Sets {
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
+ * <p><b>Java 8 users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}.
+ *
* @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set.
* @return a synchronized view of the specified navigable set.
* @since 13.0
@@ -2068,7 +2083,6 @@ public final class Sets {
*
* @since 20.0
*/
- @Beta
@GwtIncompatible // NavigableSet
public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
NavigableSet<K> set, Range<K> range) {
diff --git a/android/guava/src/com/google/common/collect/SortedLists.java b/android/guava/src/com/google/common/collect/SortedLists.java
index 0ebaab20f..245d01821 100644
--- a/android/guava/src/com/google/common/collect/SortedLists.java
+++ b/android/guava/src/com/google/common/collect/SortedLists.java
@@ -16,7 +16,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.Collections;
@@ -35,7 +34,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
*/
@GwtCompatible
-@Beta
@ElementTypesAreNonnullByDefault
final class SortedLists {
private SortedLists() {}
diff --git a/android/guava/src/com/google/common/collect/SortedMultiset.java b/android/guava/src/com/google/common/collect/SortedMultiset.java
index 7cc512d8e..87969b52c 100644
--- a/android/guava/src/com/google/common/collect/SortedMultiset.java
+++ b/android/guava/src/com/google/common/collect/SortedMultiset.java
@@ -92,8 +92,8 @@ public interface SortedMultiset<E extends @Nullable Object>
/**
* {@inheritDoc}
*
- * <p>The {@code entrySet}'s iterator returns entries in ascending element order according to the
- * this multiset's comparator.
+ * <p>The {@code entrySet}'s iterator returns entries in ascending element order according to this
+ * multiset's comparator.
*/
@Override
Set<Entry<E>> entrySet();
diff --git a/android/guava/src/com/google/common/collect/StandardTable.java b/android/guava/src/com/google/common/collect/StandardTable.java
index 4c1ffe184..e039877a9 100644
--- a/android/guava/src/com/google/common/collect/StandardTable.java
+++ b/android/guava/src/com/google/common/collect/StandardTable.java
@@ -34,6 +34,7 @@ import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.common.collect.Maps.ViewCachingAbstractMap;
import com.google.common.collect.Sets.ImprovedAbstractSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.Collection;
@@ -649,7 +650,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
return rowMap().keySet();
}
- @CheckForNull private transient Set<C> columnKeySet;
+ @LazyInit @CheckForNull private transient Set<C> columnKeySet;
/**
* {@inheritDoc}
@@ -780,7 +781,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
return super.values();
}
- @CheckForNull private transient Map<R, Map<C, V>> rowMap;
+ @LazyInit @CheckForNull private transient Map<R, Map<C, V>> rowMap;
@Override
public Map<R, Map<C, V>> rowMap() {
@@ -862,7 +863,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
}
}
- @CheckForNull private transient ColumnMap columnMap;
+ @LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, V>> columnMap() {
@@ -957,7 +958,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
public boolean removeAll(Collection<?> c) {
/*
* We can't inherit the normal implementation (which calls
- * Sets.removeAllImpl(Set, *Collection*) because, under some
+ * Sets.removeAllImpl(Set, *Collection*)) because, under some
* circumstances, it attempts to call columnKeySet().iterator().remove,
* which is unsupported.
*/
diff --git a/android/guava/src/com/google/common/collect/Synchronized.java b/android/guava/src/com/google/common/collect/Synchronized.java
index 42bf6114c..a53a1f5af 100644
--- a/android/guava/src/com/google/common/collect/Synchronized.java
+++ b/android/guava/src/com/google/common/collect/Synchronized.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.j2objc.annotations.RetainedWith;
import java.io.IOException;
@@ -96,6 +97,7 @@ final class Synchronized {
// following writeObject() handles the SynchronizedObject members.
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
synchronized (mutex) {
stream.defaultWriteObject();
@@ -103,6 +105,7 @@ final class Synchronized {
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -459,7 +462,7 @@ final class Synchronized {
}
@Override
- public int add(E e, int n) {
+ public int add(@ParametricNullness E e, int n) {
synchronized (mutex) {
return delegate().add(e, n);
}
@@ -473,14 +476,14 @@ final class Synchronized {
}
@Override
- public int setCount(E element, int count) {
+ public int setCount(@ParametricNullness E element, int count) {
synchronized (mutex) {
return delegate().setCount(element, count);
}
}
@Override
- public boolean setCount(E element, int oldCount, int newCount) {
+ public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) {
synchronized (mutex) {
return delegate().setCount(element, oldCount, newCount);
}
@@ -588,21 +591,21 @@ final class Synchronized {
}
@Override
- public Collection<V> get(K key) {
+ public Collection<V> get(@ParametricNullness K key) {
synchronized (mutex) {
return typePreservingCollection(delegate().get(key), mutex);
}
}
@Override
- public boolean put(K key, V value) {
+ public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
- public boolean putAll(K key, Iterable<? extends V> values) {
+ public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().putAll(key, values);
}
@@ -616,7 +619,7 @@ final class Synchronized {
}
@Override
- public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
+ public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
@@ -922,16 +925,15 @@ final class Synchronized {
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override
- public Object[] toArray() {
+ public @Nullable Object[] toArray() {
synchronized (mutex) {
/*
* toArrayImpl returns `@Nullable Object[]` rather than `Object[]` but only because it can
* be used with collections that may contain null. This collection never contains nulls, so
- * we can treat it as a plain `Object[]`.
+ * we could return `Object[]`. But this class is private and J2KT cannot change return types
+ * in overrides, so we declare `@Nullable Object[]` as the return type.
*/
- @SuppressWarnings("nullness")
- Object[] result = (Object[]) ObjectArrays.toArrayImpl(delegate());
- return result;
+ return ObjectArrays.toArrayImpl(delegate());
}
}
@@ -1229,7 +1231,7 @@ final class Synchronized {
@Override
@CheckForNull
- public V forcePut(K key, V value) {
+ public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
synchronized (mutex) {
return delegate().forcePut(key, value);
}
@@ -1989,7 +1991,10 @@ final class Synchronized {
@Override
@CheckForNull
- public V put(R rowKey, C columnKey, V value) {
+ public V put(
+ @ParametricNullness R rowKey,
+ @ParametricNullness C columnKey,
+ @ParametricNullness V value) {
synchronized (mutex) {
return delegate().put(rowKey, columnKey, value);
}
@@ -2011,14 +2016,14 @@ final class Synchronized {
}
@Override
- public Map<C, V> row(R rowKey) {
+ public Map<C, V> row(@ParametricNullness R rowKey) {
synchronized (mutex) {
return map(delegate().row(rowKey), mutex);
}
}
@Override
- public Map<R, V> column(C columnKey) {
+ public Map<R, V> column(@ParametricNullness C columnKey) {
synchronized (mutex) {
return map(delegate().column(columnKey), mutex);
}
diff --git a/android/guava/src/com/google/common/collect/Table.java b/android/guava/src/com/google/common/collect/Table.java
index 3c9e7ec7a..05ceb1af8 100644
--- a/android/guava/src/com/google/common/collect/Table.java
+++ b/android/guava/src/com/google/common/collect/Table.java
@@ -45,6 +45,16 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* not be modifiable. When modification isn't supported, those methods will throw an {@link
* UnsupportedOperationException}.
*
+ * <h3>Implementations</h3>
+ *
+ * <ul>
+ * <li>{@link ImmutableTable}
+ * <li>{@link HashBasedTable}
+ * <li>{@link TreeBasedTable}
+ * <li>{@link ArrayTable}
+ * <li>{@link Tables#newCustomTable Tables.newCustomTable}
+ * </ul>
+ *
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>.
*
diff --git a/android/guava/src/com/google/common/collect/TableCollectors.java b/android/guava/src/com/google/common/collect/TableCollectors.java
new file mode 100644
index 000000000..9e71d80ab
--- /dev/null
+++ b/android/guava/src/com/google/common/collect/TableCollectors.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2009 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 static com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.collect.Tables.AbstractCell;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.BinaryOperator;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/** Collectors utilities for {@code common.collect.Table} internals. */
+@GwtCompatible
+@ElementTypesAreNonnullByDefault
+@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
+@IgnoreJRERequirement // used only from APIs with Java 8 types in them
+// (not used publicly by guava-android as of this writing, but we include it in the jar as a test)
+final class TableCollectors {
+
+ static <T extends @Nullable Object, R, C, V>
+ Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
+ Function<? super T, ? extends R> rowFunction,
+ Function<? super T, ? extends C> columnFunction,
+ Function<? super T, ? extends V> valueFunction) {
+ checkNotNull(rowFunction, "rowFunction");
+ checkNotNull(columnFunction, "columnFunction");
+ checkNotNull(valueFunction, "valueFunction");
+ return Collector.of(
+ (Supplier<ImmutableTable.Builder<R, C, V>>) ImmutableTable.Builder::new,
+ (builder, t) ->
+ builder.put(rowFunction.apply(t), columnFunction.apply(t), valueFunction.apply(t)),
+ ImmutableTable.Builder::combine,
+ ImmutableTable.Builder::build);
+ }
+
+ static <T extends @Nullable Object, R, C, V>
+ Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
+ Function<? super T, ? extends R> rowFunction,
+ Function<? super T, ? extends C> columnFunction,
+ Function<? super T, ? extends V> valueFunction,
+ BinaryOperator<V> mergeFunction) {
+
+ checkNotNull(rowFunction, "rowFunction");
+ checkNotNull(columnFunction, "columnFunction");
+ checkNotNull(valueFunction, "valueFunction");
+ checkNotNull(mergeFunction, "mergeFunction");
+
+ /*
+ * No mutable Table exactly matches the insertion order behavior of ImmutableTable.Builder, but
+ * the Builder can't efficiently support merging of duplicate values. Getting around this
+ * requires some work.
+ */
+
+ return Collector.of(
+ ImmutableTableCollectorState<R, C, V>::new,
+ (state, input) ->
+ state.put(
+ rowFunction.apply(input),
+ columnFunction.apply(input),
+ valueFunction.apply(input),
+ mergeFunction),
+ (s1, s2) -> s1.combine(s2, mergeFunction),
+ state -> state.toTable());
+ }
+
+ static <
+ T extends @Nullable Object,
+ R extends @Nullable Object,
+ C extends @Nullable Object,
+ V extends @Nullable Object,
+ I extends Table<R, C, V>>
+ Collector<T, ?, I> toTable(
+ java.util.function.Function<? super T, ? extends R> rowFunction,
+ java.util.function.Function<? super T, ? extends C> columnFunction,
+ java.util.function.Function<? super T, ? extends V> valueFunction,
+ java.util.function.Supplier<I> tableSupplier) {
+ return toTable(
+ rowFunction,
+ columnFunction,
+ valueFunction,
+ (v1, v2) -> {
+ throw new IllegalStateException("Conflicting values " + v1 + " and " + v2);
+ },
+ tableSupplier);
+ }
+
+ static <
+ T extends @Nullable Object,
+ R extends @Nullable Object,
+ C extends @Nullable Object,
+ V extends @Nullable Object,
+ I extends Table<R, C, V>>
+ Collector<T, ?, I> toTable(
+ java.util.function.Function<? super T, ? extends R> rowFunction,
+ java.util.function.Function<? super T, ? extends C> columnFunction,
+ java.util.function.Function<? super T, ? extends V> valueFunction,
+ BinaryOperator<V> mergeFunction,
+ java.util.function.Supplier<I> tableSupplier) {
+ checkNotNull(rowFunction);
+ checkNotNull(columnFunction);
+ checkNotNull(valueFunction);
+ checkNotNull(mergeFunction);
+ checkNotNull(tableSupplier);
+ return Collector.of(
+ tableSupplier,
+ (table, input) ->
+ mergeTables(
+ table,
+ rowFunction.apply(input),
+ columnFunction.apply(input),
+ valueFunction.apply(input),
+ mergeFunction),
+ (table1, table2) -> {
+ for (Table.Cell<R, C, V> cell2 : table2.cellSet()) {
+ mergeTables(
+ table1, cell2.getRowKey(), cell2.getColumnKey(), cell2.getValue(), mergeFunction);
+ }
+ return table1;
+ });
+ }
+
+ private static final class ImmutableTableCollectorState<R, C, V> {
+ final List<MutableCell<R, C, V>> insertionOrder = new ArrayList<>();
+ final Table<R, C, MutableCell<R, C, V>> table = HashBasedTable.create();
+
+ void put(R row, C column, V value, BinaryOperator<V> merger) {
+ MutableCell<R, C, V> oldCell = table.get(row, column);
+ if (oldCell == null) {
+ MutableCell<R, C, V> cell = new MutableCell<>(row, column, value);
+ insertionOrder.add(cell);
+ table.put(row, column, cell);
+ } else {
+ oldCell.merge(value, merger);
+ }
+ }
+
+ ImmutableTableCollectorState<R, C, V> combine(
+ ImmutableTableCollectorState<R, C, V> other, BinaryOperator<V> merger) {
+ for (MutableCell<R, C, V> cell : other.insertionOrder) {
+ put(cell.getRowKey(), cell.getColumnKey(), cell.getValue(), merger);
+ }
+ return this;
+ }
+
+ ImmutableTable<R, C, V> toTable() {
+ return ImmutableTable.copyOf(insertionOrder);
+ }
+ }
+
+ @IgnoreJRERequirement // see enclosing class (whose annotation Animal Sniffer ignores here...)
+ private static final class MutableCell<R, C, V> extends AbstractCell<R, C, V> {
+ private final R row;
+ private final C column;
+ private V value;
+
+ MutableCell(R row, C column, V value) {
+ this.row = checkNotNull(row, "row");
+ this.column = checkNotNull(column, "column");
+ this.value = checkNotNull(value, "value");
+ }
+
+ @Override
+ public R getRowKey() {
+ return row;
+ }
+
+ @Override
+ public C getColumnKey() {
+ return column;
+ }
+
+ @Override
+ public V getValue() {
+ return value;
+ }
+
+ void merge(V value, BinaryOperator<V> mergeFunction) {
+ checkNotNull(value, "value");
+ this.value = checkNotNull(mergeFunction.apply(this.value, value), "mergeFunction.apply");
+ }
+ }
+
+ private static <
+ R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
+ void mergeTables(
+ Table<R, C, V> table,
+ @ParametricNullness R row,
+ @ParametricNullness C column,
+ @ParametricNullness V value,
+ BinaryOperator<V> mergeFunction) {
+ checkNotNull(value);
+ V oldValue = table.get(row, column);
+ if (oldValue == null) {
+ table.put(row, column, value);
+ } else {
+ V newValue = mergeFunction.apply(oldValue, value);
+ if (newValue == null) {
+ table.remove(row, column);
+ } else {
+ table.put(row, column, newValue);
+ }
+ }
+ }
+
+ private TableCollectors() {}
+}
diff --git a/android/guava/src/com/google/common/collect/Tables.java b/android/guava/src/com/google/common/collect/Tables.java
index ab67fae9f..513404de1 100644
--- a/android/guava/src/com/google/common/collect/Tables.java
+++ b/android/guava/src/com/google/common/collect/Tables.java
@@ -20,7 +20,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
@@ -257,7 +256,7 @@ public final class Tables {
}
// Will cast TRANSPOSE_CELL to a type that always succeeds
- private static final Function<Cell<?, ?, ?>, Cell<?, ?, ?>> TRANSPOSE_CELL =
+ private static final Function TRANSPOSE_CELL =
new Function<Cell<?, ?, ?>, Cell<?, ?, ?>>() {
@Override
public Cell<?, ?, ?> apply(Cell<?, ?, ?> cell) {
@@ -268,7 +267,8 @@ public final class Tables {
@SuppressWarnings("unchecked")
@Override
Iterator<Cell<C, R, V>> cellIterator() {
- return Iterators.transform(original.cellSet().iterator(), (Function) TRANSPOSE_CELL);
+ return Iterators.transform(
+ original.cellSet().iterator(), (Function<Cell<R, C, V>, Cell<C, R, V>>) TRANSPOSE_CELL);
}
}
@@ -310,7 +310,6 @@ public final class Tables {
* @throws IllegalArgumentException if {@code backingMap} is not empty
* @since 10.0
*/
- @Beta
public static <R, C, V> Table<R, C, V> newCustomTable(
Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
checkArgument(backingMap.isEmpty());
@@ -340,7 +339,6 @@ public final class Tables {
*
* @since 10.0
*/
- @Beta
public static <
R extends @Nullable Object,
C extends @Nullable Object,
@@ -593,7 +591,6 @@ public final class Tables {
* @return an unmodifiable view of the specified table
* @since 11.0
*/
- @Beta
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
RowSortedTable<R, C, V> unmodifiableRowSortedTable(
RowSortedTable<R, ? extends C, ? extends V> table) {
diff --git a/android/guava/src/com/google/common/collect/TopKSelector.java b/android/guava/src/com/google/common/collect/TopKSelector.java
index 32959630b..9cc916e43 100644
--- a/android/guava/src/com/google/common/collect/TopKSelector.java
+++ b/android/guava/src/com/google/common/collect/TopKSelector.java
@@ -273,7 +273,9 @@ final class TopKSelector<
bufferSize = k;
threshold = buffer[k - 1];
}
+ // Up to bufferSize, all elements of buffer are real Ts (not null unless T includes null)
+ T[] topK = Arrays.copyOf(castBuffer, bufferSize);
// we have to support null elements, so no ImmutableList for us
- return Collections.unmodifiableList(Arrays.asList(Arrays.copyOf(buffer, bufferSize)));
+ return Collections.unmodifiableList(Arrays.asList(topK));
}
}
diff --git a/android/guava/src/com/google/common/collect/TreeMultimap.java b/android/guava/src/com/google/common/collect/TreeMultimap.java
index dd0c2f833..e449caa30 100644
--- a/android/guava/src/com/google/common/collect/TreeMultimap.java
+++ b/android/guava/src/com/google/common/collect/TreeMultimap.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -141,7 +142,7 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
@Override
Collection<V> createCollection(@ParametricNullness K key) {
if (key == null) {
- keyComparator().compare(key, key);
+ int unused = keyComparator().compare(key, key);
}
return super.createCollection(key);
}
@@ -201,6 +202,7 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
* distinct key: the key, number of values for that key, and key values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyComparator());
@@ -209,6 +211,7 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -219,5 +222,6 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/android/guava/src/com/google/common/collect/TreeMultiset.java b/android/guava/src/com/google/common/collect/TreeMultiset.java
index bcaa10881..f3367ef9a 100644
--- a/android/guava/src/com/google/common/collect/TreeMultiset.java
+++ b/android/guava/src/com/google/common/collect/TreeMultiset.java
@@ -24,6 +24,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -262,7 +263,7 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
- comparator().compare(element, element);
+ int unused = comparator().compare(element, element);
AvlNode<E> newRoot = new AvlNode<E>(element, occurrences);
successor(header, newRoot, header);
rootReference.checkAndSet(root, newRoot);
@@ -1061,6 +1062,7 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
* @serialData the comparator, the number of distinct elements, the first element, its count, the
* second element, its count, and so on
*/
+ @J2ktIncompatible
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
@@ -1068,6 +1070,7 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
Serialization.writeMultiset(this, stream);
}
+ @J2ktIncompatible
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -1086,5 +1089,6 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 1;
}
diff --git a/android/guava/src/com/google/common/collect/TreeRangeMap.java b/android/guava/src/com/google/common/collect/TreeRangeMap.java
index 0ce8e8955..0797f8964 100644
--- a/android/guava/src/com/google/common/collect/TreeRangeMap.java
+++ b/android/guava/src/com/google/common/collect/TreeRangeMap.java
@@ -23,7 +23,6 @@ import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
@@ -49,7 +48,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
@@ -167,8 +165,8 @@ public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K,
}
@Override
- public void putAll(RangeMap<K, V> rangeMap) {
- for (Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) {
+ public void putAll(RangeMap<K, ? extends V> rangeMap) {
+ for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@@ -341,7 +339,7 @@ public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K,
}
@Override
- public void putAll(RangeMap<Comparable<?>, Object> rangeMap) {
+ public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
@@ -447,7 +445,7 @@ public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K,
}
@Override
- public void putAll(RangeMap<K, V> rangeMap) {
+ public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
diff --git a/android/guava/src/com/google/common/collect/TreeRangeSet.java b/android/guava/src/com/google/common/collect/TreeRangeSet.java
index 7ba71139e..415e80ffb 100644
--- a/android/guava/src/com/google/common/collect/TreeRangeSet.java
+++ b/android/guava/src/com/google/common/collect/TreeRangeSet.java
@@ -17,10 +17,10 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
@@ -38,7 +38,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible // uses NavigableMap
@ElementTypesAreNonnullByDefault
public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
@@ -77,8 +76,8 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
this.rangesByLowerBound = rangesByLowerCut;
}
- @CheckForNull private transient Set<Range<C>> asRanges;
- @CheckForNull private transient Set<Range<C>> asDescendingSetOfRanges;
+ @LazyInit @CheckForNull private transient Set<Range<C>> asRanges;
+ @LazyInit @CheckForNull private transient Set<Range<C>> asDescendingSetOfRanges;
@Override
public Set<Range<C>> asRanges() {
@@ -274,7 +273,7 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
}
}
- @CheckForNull private transient RangeSet<C> complement;
+ @LazyInit @CheckForNull private transient RangeSet<C> complement;
@Override
public RangeSet<C> complement() {
@@ -802,7 +801,7 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
.iterator();
}
Cut<Cut<C>> upperBoundOnLowerBounds =
- Ordering.natural()
+ Ordering.<Cut<Cut<C>>>natural()
.min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound));
return new AbstractIterator<Entry<Cut<C>, Range<C>>>() {
@Override
@@ -828,7 +827,7 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
return Iterators.emptyIterator();
}
Cut<Cut<C>> upperBoundOnLowerBounds =
- Ordering.natural()
+ Ordering.<Cut<Cut<C>>>natural()
.min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound));
Iterator<Range<C>> completeRangeItr =
rangesByLowerBound
diff --git a/android/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java b/android/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
index 31f3c7197..c7e1d4c33 100644
--- a/android/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
+++ b/android/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multisets.UnmodifiableMultiset;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.util.Comparator;
import java.util.NavigableSet;
import javax.annotation.CheckForNull;
@@ -58,7 +59,7 @@ final class UnmodifiableSortedMultiset<E extends @Nullable Object> extends Unmod
return (NavigableSet<E>) super.elementSet();
}
- @CheckForNull private transient UnmodifiableSortedMultiset<E> descendingMultiset;
+ @LazyInit @CheckForNull private transient UnmodifiableSortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
diff --git a/android/guava/src/com/google/common/collect/package-info.java b/android/guava/src/com/google/common/collect/package-info.java
index d46e65fd3..ad169a685 100644
--- a/android/guava/src/com/google/common/collect/package-info.java
+++ b/android/guava/src/com/google/common/collect/package-info.java
@@ -15,201 +15,108 @@
*/
/**
- * This package contains generic collection interfaces and implementations, and other utilities for
- * working with collections. It is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Collection interfaces and implementations, and other utilities for collections. This package is a
+ * part of the open-source <a href="https://github.com/google/guava">Guava</a> library.
*
- * <h2>Collection Types</h2>
+ * <p>The classes in this package include:
+ *
+ * <h2>Immutable collections</h2>
+ *
+ * These are collections whose contents will never change. They also offer a few additional
+ * guarantees (see {@link ImmutableCollection} for details). Implementations are available for both
+ * the JDK collection types and the Guava collection types (listed below).
+ *
+ * <h2>Collection types</h2>
*
* <dl>
- * <dt>{@link com.google.common.collect.BiMap}
+ * <dt>{@link Multimap}
+ * <dd>A new type, which is similar to {@link java.util.Map}, but may contain multiple entries
+ * with the same key. Some behaviors of {@link Multimap} are left unspecified and are provided
+ * only by the subtypes mentioned below.
+ * <dt>{@link ListMultimap}
+ * <dd>An extension of {@link Multimap} which permits duplicate entries, supports random access of
+ * values for a particular key, and has <i>partially order-dependent equality</i> as defined
+ * by {@link ListMultimap#equals(Object)}. {@code ListMultimap} takes its name from the fact
+ * that the {@linkplain ListMultimap#get collection of values} associated with a given key
+ * fulfills the {@link java.util.List} contract.
+ * <dt>{@link SetMultimap}
+ * <dd>An extension of {@link Multimap} which has order-independent equality and does not allow
+ * duplicate entries; that is, while a key may appear twice in a {@code SetMultimap}, each
+ * must map to a different value. {@code SetMultimap} takes its name from the fact that the
+ * {@linkplain SetMultimap#get collection of values} associated with a given key fulfills the
+ * {@link java.util.Set} contract.
+ * <dt>{@link SortedSetMultimap}
+ * <dd>An extension of {@link SetMultimap} for which the {@linkplain SortedSetMultimap#get
+ * collection values} associated with a given key is a {@link java.util.SortedSet}.
+ * <dt>{@link BiMap}
* <dd>An extension of {@link java.util.Map} that guarantees the uniqueness of its values as well
* as that of its keys. This is sometimes called an "invertible map," since the restriction on
- * values enables it to support an {@linkplain com.google.common.collect.BiMap#inverse inverse
- * view} -- which is another instance of {@code BiMap}.
- * <dt>{@link com.google.common.collect.Multiset}
+ * values enables it to support an {@linkplain BiMap#inverse inverse view} -- which is another
+ * instance of {@code BiMap}.
+ * <dt>{@link Table}
+ * <dd>A new type, which is similar to {@link java.util.Map}, but which indexes its values by an
+ * ordered pair of keys, a row key and column key.
+ * <dt>{@link Multiset}
* <dd>An extension of {@link java.util.Collection} that may contain duplicate values like a
* {@link java.util.List}, yet has order-independent equality like a {@link java.util.Set}.
* One typical use for a multiset is to represent a histogram.
- * <dt>{@link com.google.common.collect.Multimap}
- * <dd>A new type, which is similar to {@link java.util.Map}, but may contain multiple entries
- * with the same key. Some behaviors of {@link com.google.common.collect.Multimap} are left
- * unspecified and are provided only by the subtypes mentioned below.
- * <dt>{@link com.google.common.collect.ListMultimap}
- * <dd>An extension of {@link com.google.common.collect.Multimap} which permits duplicate entries,
- * supports random access of values for a particular key, and has <i>partially order-dependent
- * equality</i> as defined by {@link com.google.common.collect.ListMultimap#equals(Object)}.
- * {@code ListMultimap} takes its name from the fact that the {@linkplain
- * com.google.common.collect.ListMultimap#get collection of values} associated with a given
- * key fulfills the {@link java.util.List} contract.
- * <dt>{@link com.google.common.collect.SetMultimap}
- * <dd>An extension of {@link com.google.common.collect.Multimap} which has order-independent
- * equality and does not allow duplicate entries; that is, while a key may appear twice in a
- * {@code SetMultimap}, each must map to a different value. {@code SetMultimap} takes its name
- * from the fact that the {@linkplain com.google.common.collect.SetMultimap#get collection of
- * values} associated with a given key fulfills the {@link java.util.Set} contract.
- * <dt>{@link com.google.common.collect.SortedSetMultimap}
- * <dd>An extension of {@link com.google.common.collect.SetMultimap} for which the {@linkplain
- * com.google.common.collect.SortedSetMultimap#get collection values} associated with a given
- * key is a {@link java.util.SortedSet}.
- * <dt>{@link com.google.common.collect.Table}
- * <dd>A new type, which is similar to {@link java.util.Map}, but which indexes its values by an
- * ordered pair of keys, a row key and column key.
- * <dt>{@link com.google.common.collect.ClassToInstanceMap}
+ * <dt>{@link ClassToInstanceMap}
* <dd>An extension of {@link java.util.Map} that associates a raw type with an instance of that
* type.
* </dl>
*
- * <h2>Collection Implementations</h2>
- *
- * <h3>of {@link java.util.List}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableList}
- * </ul>
- *
- * <h3>of {@link java.util.Set}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableSet}
- * <li>{@link com.google.common.collect.ImmutableSortedSet}
- * <li>{@link com.google.common.collect.ContiguousSet} (see {@code Range})
- * </ul>
- *
- * <h3>of {@link java.util.Map}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableMap}
- * <li>{@link com.google.common.collect.ImmutableSortedMap}
- * <li>{@link com.google.common.collect.MapMaker}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.BiMap}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableBiMap}
- * <li>{@link com.google.common.collect.HashBiMap}
- * <li>{@link com.google.common.collect.EnumBiMap}
- * <li>{@link com.google.common.collect.EnumHashBiMap}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.Multiset}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableMultiset}
- * <li>{@link com.google.common.collect.ImmutableSortedMultiset}
- * <li>{@link com.google.common.collect.HashMultiset}
- * <li>{@link com.google.common.collect.LinkedHashMultiset}
- * <li>{@link com.google.common.collect.TreeMultiset}
- * <li>{@link com.google.common.collect.EnumMultiset}
- * <li>{@link com.google.common.collect.ConcurrentHashMultiset}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.Multimap}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableMultimap}
- * <li>{@link com.google.common.collect.ImmutableListMultimap}
- * <li>{@link com.google.common.collect.ImmutableSetMultimap}
- * <li>{@link com.google.common.collect.ArrayListMultimap}
- * <li>{@link com.google.common.collect.HashMultimap}
- * <li>{@link com.google.common.collect.TreeMultimap}
- * <li>{@link com.google.common.collect.LinkedHashMultimap}
- * <li>{@link com.google.common.collect.LinkedListMultimap}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.Table}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableTable}
- * <li>{@link com.google.common.collect.ArrayTable}
- * <li>{@link com.google.common.collect.HashBasedTable}
- * <li>{@link com.google.common.collect.TreeBasedTable}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.ClassToInstanceMap}</h3>
+ * <h2>Ranges</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.ImmutableClassToInstanceMap}
- * <li>{@link com.google.common.collect.MutableClassToInstanceMap}
+ * <li>{@link Range}
+ * <li>{@link RangeMap}
+ * <li>{@link RangeSet}
+ * <li>{@link DiscreteDomain}
+ * <li>{@link ContiguousSet}
* </ul>
*
* <h2>Classes of static utility methods</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.Collections2}
- * <li>{@link com.google.common.collect.Iterators}
- * <li>{@link com.google.common.collect.Iterables}
- * <li>{@link com.google.common.collect.Lists}
- * <li>{@link com.google.common.collect.Maps}
- * <li>{@link com.google.common.collect.Queues}
- * <li>{@link com.google.common.collect.Sets}
- * <li>{@link com.google.common.collect.Multisets}
- * <li>{@link com.google.common.collect.Multimaps}
- * <li>{@link com.google.common.collect.Tables}
- * <li>{@link com.google.common.collect.ObjectArrays}
- * </ul>
- *
- * <h2>Comparison</h2>
- *
- * <ul>
- * <li>{@link com.google.common.collect.Ordering}
- * <li>{@link com.google.common.collect.ComparisonChain}
+ * <li>{@link Collections2}
+ * <li>{@link Comparators}
+ * <li>{@link Iterables}
+ * <li>{@link Iterators}
+ * <li>{@link Lists}
+ * <li>{@link Maps}
+ * <li>{@link MoreCollectors}
+ * <li>{@link Multimaps}
+ * <li>{@link Multisets}
+ * <li>{@link ObjectArrays}
+ * <li>{@link Queues}
+ * <li>{@link Sets}
+ * <li>{@link Streams}
+ * <li>{@link Tables}
* </ul>
*
* <h2>Abstract implementations</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.AbstractIterator}
- * <li>{@link com.google.common.collect.AbstractSequentialIterator}
- * <li>{@link com.google.common.collect.ImmutableCollection}
- * <li>{@link com.google.common.collect.UnmodifiableIterator}
- * <li>{@link com.google.common.collect.UnmodifiableListIterator}
+ * <li>{@link AbstractIterator}
+ * <li>{@link AbstractSequentialIterator}
+ * <li>{@link UnmodifiableIterator}
+ * <li>{@link UnmodifiableListIterator}
* </ul>
*
- * <h2>Ranges</h2>
+ * <h2>Forwarding collections</h2>
*
- * <ul>
- * <li>{@link com.google.common.collect.Range}
- * <li>{@link com.google.common.collect.RangeMap}
- * <li>{@link com.google.common.collect.DiscreteDomain}
- * <li>{@link com.google.common.collect.ContiguousSet}
- * </ul>
+ * We provide implementations of collections that forward all method calls to a delegate collection
+ * by default. Subclasses can override one or more methods to implement the decorator pattern. For
+ * an example, see {@link ForwardingCollection}.
*
* <h2>Other</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.Interner}, {@link com.google.common.collect.Interners}
- * <li>{@link com.google.common.collect.MapDifference}, {@link
- * com.google.common.collect.SortedMapDifference}
- * <li>{@link com.google.common.collect.MinMaxPriorityQueue}
- * <li>{@link com.google.common.collect.PeekingIterator}
- * </ul>
- *
- * <h2>Forwarding collections</h2>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ForwardingCollection}
- * <li>{@link com.google.common.collect.ForwardingConcurrentMap}
- * <li>{@link com.google.common.collect.ForwardingIterator}
- * <li>{@link com.google.common.collect.ForwardingList}
- * <li>{@link com.google.common.collect.ForwardingListIterator}
- * <li>{@link com.google.common.collect.ForwardingListMultimap}
- * <li>{@link com.google.common.collect.ForwardingMap}
- * <li>{@link com.google.common.collect.ForwardingMapEntry}
- * <li>{@link com.google.common.collect.ForwardingMultimap}
- * <li>{@link com.google.common.collect.ForwardingMultiset}
- * <li>{@link com.google.common.collect.ForwardingNavigableMap}
- * <li>{@link com.google.common.collect.ForwardingNavigableSet}
- * <li>{@link com.google.common.collect.ForwardingObject}
- * <li>{@link com.google.common.collect.ForwardingQueue}
- * <li>{@link com.google.common.collect.ForwardingSet}
- * <li>{@link com.google.common.collect.ForwardingSetMultimap}
- * <li>{@link com.google.common.collect.ForwardingSortedMap}
- * <li>{@link com.google.common.collect.ForwardingSortedMultiset}
- * <li>{@link com.google.common.collect.ForwardingSortedSet}
- * <li>{@link com.google.common.collect.ForwardingSortedSetMultimap}
- * <li>{@link com.google.common.collect.ForwardingTable}
+ * <li>{@link EvictingQueue}
+ * <li>{@link Interner}, {@link Interners}
+ * <li>{@link MapMaker}
+ * <li>{@link MinMaxPriorityQueue}
+ * <li>{@link PeekingIterator}
* </ul>
*/
@CheckReturnValue
diff --git a/android/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java b/android/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
index 355faaa10..81badfb08 100644
--- a/android/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
+++ b/android/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
@@ -128,7 +128,7 @@ public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper {
this.safeMinChar = Character.MAX_VALUE;
this.safeMaxChar = 0;
} else {
- // The safe range is non empty and contains values below the surrogate
+ // The safe range is non-empty and contains values below the surrogate
// range but may extend above it. We may need to clip the maximum value.
this.safeMinChar = (char) safeMin;
this.safeMaxChar = (char) Math.min(safeMax, Character.MIN_HIGH_SURROGATE - 1);
diff --git a/android/guava/src/com/google/common/escape/Escapers.java b/android/guava/src/com/google/common/escape/Escapers.java
index acfb82ce2..b7dcfa6b3 100644
--- a/android/guava/src/com/google/common/escape/Escapers.java
+++ b/android/guava/src/com/google/common/escape/Escapers.java
@@ -186,7 +186,7 @@ public final class Escapers {
return wrap((CharEscaper) escaper);
}
// In practice this shouldn't happen because it would be very odd not to
- // extend either CharEscaper or UnicodeEscaper for non trivial cases.
+ // extend either CharEscaper or UnicodeEscaper for non-trivial cases.
throw new IllegalArgumentException(
"Cannot create a UnicodeEscaper from: " + escaper.getClass().getName());
}
diff --git a/android/guava/src/com/google/common/escape/ParametricNullness.java b/android/guava/src/com/google/common/escape/ParametricNullness.java
index d9412065f..f964ca4a4 100644
--- a/android/guava/src/com/google/common/escape/ParametricNullness.java
+++ b/android/guava/src/com/google/common/escape/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/escape/package-info.java b/android/guava/src/com/google/common/escape/package-info.java
index 8cd29e6f8..4c525386e 100644
--- a/android/guava/src/com/google/common/escape/package-info.java
+++ b/android/guava/src/com/google/common/escape/package-info.java
@@ -14,14 +14,14 @@
/**
* Interfaces, utilities, and simple implementations of escapers and encoders. The primary type is
- * {@link com.google.common.escape.Escaper}.
+ * {@link Escaper}.
*
* <p>Additional escapers implementations are found in the applicable packages: {@link
* com.google.common.html.HtmlEscapers} in {@code com.google.common.html}, {@link
* com.google.common.xml.XmlEscapers} in {@code com.google.common.xml}, and {@link
* com.google.common.net.UrlEscapers} in {@code com.google.common.net}.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/android/guava/src/com/google/common/eventbus/Dispatcher.java b/android/guava/src/com/google/common/eventbus/Dispatcher.java
index ff1ae2a19..412bb789e 100644
--- a/android/guava/src/com/google/common/eventbus/Dispatcher.java
+++ b/android/guava/src/com/google/common/eventbus/Dispatcher.java
@@ -133,7 +133,7 @@ abstract class Dispatcher {
// This dispatcher matches the original dispatch behavior of AsyncEventBus.
//
// We can't really make any guarantees about the overall dispatch order for this dispatcher in
- // a multithreaded environment for a couple reasons:
+ // a multithreaded environment for a couple of reasons:
//
// 1. Subscribers to events posted on different threads can be interleaved with each other
// freely. (A event on one thread, B event on another could yield any of
diff --git a/android/guava/src/com/google/common/eventbus/ParametricNullness.java b/android/guava/src/com/google/common/eventbus/ParametricNullness.java
index ac91392f7..47c7d8d4d 100644
--- a/android/guava/src/com/google/common/eventbus/ParametricNullness.java
+++ b/android/guava/src/com/google/common/eventbus/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/eventbus/package-info.java b/android/guava/src/com/google/common/eventbus/package-info.java
index fa7faa4ab..bd675415c 100644
--- a/android/guava/src/com/google/common/eventbus/package-info.java
+++ b/android/guava/src/com/google/common/eventbus/package-info.java
@@ -13,241 +13,11 @@
*/
/**
- * The EventBus allows publish-subscribe-style communication between components without requiring
- * the components to explicitly register with one another (and thus be aware of each other). It is
- * designed exclusively to replace traditional Java in-process event distribution using explicit
- * registration. It is <em>not</em> a general-purpose publish-subscribe system, nor is it intended
- * for interprocess communication.
+ * <a href="https://guava.dev/EventBus">Discouraged</a> in favor of dependency injection and
+ * concurrency frameworks, EventBus allows publish-subscribe-style communication.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/EventBusExplained">{@code EventBus}</a>.
- *
- * <h2>One-Minute Guide</h2>
- *
- * <p>Converting an existing EventListener-based system to use the EventBus is easy.
- *
- * <h3>For Listeners</h3>
- *
- * <p>To listen for a specific flavor of event (say, a CustomerChangeEvent)...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> implement an interface defined with the
- * event &mdash; such as CustomerChangeEventListener.
- * <li><strong>...with EventBus:</strong> create a method that accepts CustomerChangeEvent as its
- * sole argument, and mark it with the {@link com.google.common.eventbus.Subscribe}
- * annotation.
- * </ul>
- *
- * <p>To register your listener methods with the event producers...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> pass your object to each producer's {@code
- * registerCustomerChangeEventListener} method. These methods are rarely defined in common
- * interfaces, so in addition to knowing every possible producer, you must also know its type.
- * <li><strong>...with EventBus:</strong> pass your object to the {@link
- * com.google.common.eventbus.EventBus#register(Object)} method on an EventBus. You'll need to
- * make sure that your object shares an EventBus instance with the event producers.
- * </ul>
- *
- * <p>To listen for a common event supertype (such as EventObject or Object)...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> not easy.
- * <li><strong>...with EventBus:</strong> events are automatically dispatched to listeners of any
- * supertype, allowing listeners for interface types or "wildcard listeners" for Object.
- * </ul>
- *
- * <p>To listen for and detect events that were dispatched without listeners...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> add code to each event-dispatching method
- * (perhaps using AOP).
- * <li><strong>...with EventBus:</strong> subscribe to {@link
- * com.google.common.eventbus.DeadEvent}. The EventBus will notify you of any events that were
- * posted but not delivered. (Handy for debugging.)
- * </ul>
- *
- * <h3>For Producers</h3>
- *
- * <p>To keep track of listeners to your events...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> write code to manage a list of listeners to
- * your object, including synchronization, or use a utility class like EventListenerList.
- * <li><strong>...with EventBus:</strong> EventBus does this for you.
- * </ul>
- *
- * <p>To dispatch an event to listeners...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> write a method to dispatch events to each
- * event listener, including error isolation and (if desired) asynchronicity.
- * <li><strong>...with EventBus:</strong> pass the event object to an EventBus's {@link
- * com.google.common.eventbus.EventBus#post(Object)} method.
- * </ul>
- *
- * <h2>Glossary</h2>
- *
- * <p>The EventBus system and code use the following terms to discuss event distribution:
- *
- * <dl>
- * <dt>Event
- * <dd>Any object that may be <em>posted</em> to a bus.
- * <dt>Subscribing
- * <dd>The act of registering a <em>listener</em> with an EventBus, so that its <em>subscriber
- * methods</em> will receive events.
- * <dt>Listener
- * <dd>An object that wishes to receive events, by exposing <em>subscriber methods</em>.
- * <dt>Subscriber method
- * <dd>A public method that the EventBus should use to deliver <em>posted</em> events. Subscriber
- * methods are marked by the {@link com.google.common.eventbus.Subscribe} annotation.
- * <dt>Posting an event
- * <dd>Making the event available to any <em>listeners</em> through the EventBus.
- * </dl>
- *
- * <h2>FAQ</h2>
- *
- * <h3>Why must I create my own Event Bus, rather than using a singleton?</h3>
- *
- * <p>The Event Bus doesn't specify how you use it; there's nothing stopping your application from
- * having separate EventBus instances for each component, or using separate instances to separate
- * events by context or topic. This also makes it trivial to set up and tear down EventBus objects
- * in your tests.
- *
- * <p>Of course, if you'd like to have a process-wide EventBus singleton, there's nothing stopping
- * you from doing it that way. Simply have your container (such as Guice) create the EventBus as a
- * singleton at global scope (or stash it in a static field, if you're into that sort of thing).
- *
- * <p>In short, the EventBus is not a singleton because we'd rather not make that decision for you.
- * Use it how you like.
- *
- * <h3>Why use an annotation to mark subscriber methods, rather than requiring the listener to
- * implement an interface?</h3>
- *
- * <p>We feel that the Event Bus's {@code @Subscribe} annotation conveys your intentions just as
- * explicitly as implementing an interface (or perhaps more so), while leaving you free to place
- * event subscriber methods wherever you wish and give them intention-revealing names.
- *
- * <p>Traditional Java Events use a listener interface which typically sports only a handful of
- * methods -- typically one. This has a number of disadvantages:
- *
- * <ul>
- * <li>Any one class can only implement a single response to a given event.
- * <li>Listener interface methods may conflict.
- * <li>The method must be named after the event (e.g. {@code handleChangeEvent}), rather than its
- * purpose (e.g. {@code recordChangeInJournal}).
- * <li>Each event usually has its own interface, without a common parent interface for a family of
- * events (e.g. all UI events).
- * </ul>
- *
- * <p>The difficulties in implementing this cleanly has given rise to a pattern, particularly common
- * in Swing apps, of using tiny anonymous classes to implement event listener interfaces.
- *
- * <p>Compare these two cases:
- *
- * <pre>{@code
- * class ChangeRecorder {
- * void setCustomer(Customer cust) {
- * cust.addChangeListener(new ChangeListener() {
- * void customerChanged(ChangeEvent e) {
- * recordChange(e.getChange());
- * }
- * };
- * }
- * }
- *
- * // Class is typically registered by the container.
- * class EventBusChangeRecorder {
- * }{@code @Subscribe void recordCustomerChange(ChangeEvent e) {
- * recordChange(e.getChange());
- * }
- * }
- * }</pre>
- *
- * <p>The intent is actually clearer in the second case: there's less noise code, and the event
- * subscriber has a clear and meaningful name.
- *
- * <h3>What about a generic {@code Subscriber<T>} interface?</h3>
- *
- * <p>Some have proposed a generic {@code Subscriber<T>} interface for EventBus listeners. This runs
- * into issues with Java's use of type erasure, not to mention problems in usability.
- *
- * <p>Let's say the interface looked something like the following:
- *
- * <pre>{@code
- * interface Subscriber<T> {
- * void handleEvent(T event);
- * }
- * }</pre>
- *
- * <p>Due to erasure, no single class can implement a generic interface more than once with
- * different type parameters. This is a giant step backwards from traditional Java Events, where
- * even if {@code actionPerformed} and {@code keyPressed} aren't very meaningful names, at least you
- * can implement both methods!
- *
- * <h3>Doesn't EventBus destroy static typing and eliminate automated refactoring support?</h3>
- *
- * <p>Some have freaked out about EventBus's {@code register(Object)} and {@code post(Object)}
- * methods' use of the {@code Object} type.
- *
- * <p>{@code Object} is used here for a good reason: the Event Bus library places no restrictions on
- * the types of either your event listeners (as in {@code register(Object)}) or the events
- * themselves (in {@code post(Object)}).
- *
- * <p>Event subscriber methods, on the other hand, must explicitly declare their argument type --
- * the type of event desired (or one of its supertypes). Thus, searching for references to an event
- * class will instantly find all subscriber methods for that event, and renaming the type will
- * affect all subscriber methods within view of your IDE (and any code that creates the event).
- *
- * <p>It's true that you can rename your {@code @Subscribed} event subscriber methods at will; Event
- * Bus will not stop this or do anything to propagate the rename because, to Event Bus, the names of
- * your subscriber methods are irrelevant. Test code that calls the methods directly, of course,
- * will be affected by your renaming -- but that's what your refactoring tools are for.
- *
- * <h3>What happens if I {@code register} a listener without any subscriber methods?</h3>
- *
- * <p>Nothing at all.
- *
- * <p>The Event Bus was designed to integrate with containers and module systems, with Guice as the
- * prototypical example. In these cases, it's convenient to have the container/factory/environment
- * pass <i>every</i> created object to an EventBus's {@code register(Object)} method.
- *
- * <p>This way, any object created by the container/factory/environment can hook into the system's
- * event model simply by exposing subscriber methods.
- *
- * <h3>What Event Bus problems can be detected at compile time?</h3>
- *
- * <p>Any problem that can be unambiguously detected by Java's type system. For example, defining a
- * subscriber method for a nonexistent event type.
- *
- * <h3>What Event Bus problems can be detected immediately at registration?</h3>
- *
- * <p>Immediately upon invoking {@code register(Object)}, the listener being registered is checked
- * for the <i>well-formedness</i> of its subscriber methods. Specifically, any methods marked with
- * {@code @Subscribe} must take only a single argument.
- *
- * <p>Any violations of this rule will cause an {@code IllegalArgumentException} to be thrown.
- *
- * <p>(This check could be moved to compile-time using APT, a solution we're researching.)
- *
- * <h3>What Event Bus problems may only be detected later, at runtime?</h3>
- *
- * <p>If a component posts events with no registered listeners, it <i>may</i> indicate an error
- * (typically an indication that you missed a {@code @Subscribe} annotation, or that the listening
- * component is not loaded).
- *
- * <p>(Note that this is <i>not necessarily</i> indicative of a problem. There are many cases where
- * an application will deliberately ignore a posted event, particularly if the event is coming from
- * code you don't control.)
- *
- * <p>To handle such events, register a subscriber method for the {@code DeadEvent} class. Whenever
- * EventBus receives an event with no registered subscribers, it will turn it into a {@code
- * DeadEvent} and pass it your way -- allowing you to log it or otherwise recover.
- *
- * <h3>How do I test event listeners and their subscriber methods?</h3>
- *
- * <p>Because subscriber methods on your listener classes are normal methods, you can simply call
- * them from your test code to simulate the EventBus.
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
diff --git a/android/guava/src/com/google/common/graph/AbstractBaseGraph.java b/android/guava/src/com/google/common/graph/AbstractBaseGraph.java
index 797468b7a..5adcc9216 100644
--- a/android/guava/src/com/google/common/graph/AbstractBaseGraph.java
+++ b/android/guava/src/com/google/common/graph/AbstractBaseGraph.java
@@ -44,9 +44,9 @@ import javax.annotation.CheckForNull;
abstract class AbstractBaseGraph<N> implements BaseGraph<N> {
/**
- * Returns the number of edges in this graph; used to calculate the size of {@link #edges()}. This
- * implementation requires O(|N|) time. Classes extending this one may manually keep track of the
- * number of edges as the graph is updated, and override this method for better performance.
+ * Returns the number of edges in this graph; used to calculate the size of {@link Graph#edges()}.
+ * This implementation requires O(|N|) time. Classes extending this one may manually keep track of
+ * the number of edges as the graph is updated, and override this method for better performance.
*/
protected long edgeCount() {
long degreeSum = 0L;
@@ -59,8 +59,8 @@ abstract class AbstractBaseGraph<N> implements BaseGraph<N> {
}
/**
- * An implementation of {@link BaseGraph#edges()} defined in terms of {@link #nodes()} and {@link
- * #successors(Object)}.
+ * An implementation of {@link BaseGraph#edges()} defined in terms of {@link Graph#nodes()} and
+ * {@link #successors(Object)}.
*/
@Override
public Set<EndpointPair<N>> edges() {
@@ -177,7 +177,11 @@ abstract class AbstractBaseGraph<N> implements BaseGraph<N> {
checkArgument(isOrderingCompatible(endpoints), ENDPOINTS_MISMATCH);
}
+ /**
+ * Returns {@code true} iff {@code endpoints}' ordering is compatible with the directionality of
+ * this graph.
+ */
protected final boolean isOrderingCompatible(EndpointPair<?> endpoints) {
- return endpoints.isOrdered() || !this.isDirected();
+ return endpoints.isOrdered() == this.isDirected();
}
}
diff --git a/android/guava/src/com/google/common/graph/AbstractNetwork.java b/android/guava/src/com/google/common/graph/AbstractNetwork.java
index 9afbb0377..0e59378d3 100644
--- a/android/guava/src/com/google/common/graph/AbstractNetwork.java
+++ b/android/guava/src/com/google/common/graph/AbstractNetwork.java
@@ -23,7 +23,6 @@ import static com.google.common.graph.GraphConstants.MULTIPLE_EDGES_CONNECTING;
import static java.util.Collections.unmodifiableSet;
import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
@@ -71,13 +70,7 @@ public abstract class AbstractNetwork<N, E> implements Network<N, E> {
@Override
public Iterator<EndpointPair<N>> iterator() {
return Iterators.transform(
- AbstractNetwork.this.edges().iterator(),
- new Function<E, EndpointPair<N>>() {
- @Override
- public EndpointPair<N> apply(E edge) {
- return incidentNodes(edge);
- }
- });
+ AbstractNetwork.this.edges().iterator(), edge -> incidentNodes(edge));
}
@Override
@@ -241,7 +234,7 @@ public abstract class AbstractNetwork<N, E> implements Network<N, E> {
}
protected final boolean isOrderingCompatible(EndpointPair<?> endpoints) {
- return endpoints.isOrdered() || !this.isDirected();
+ return endpoints.isOrdered() == this.isDirected();
}
@Override
@@ -280,13 +273,6 @@ public abstract class AbstractNetwork<N, E> implements Network<N, E> {
}
private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) {
- Function<E, EndpointPair<N>> edgeToIncidentNodesFn =
- new Function<E, EndpointPair<N>>() {
- @Override
- public EndpointPair<N> apply(E edge) {
- return network.incidentNodes(edge);
- }
- };
- return Maps.asMap(network.edges(), edgeToIncidentNodesFn);
+ return Maps.asMap(network.edges(), network::incidentNodes);
}
}
diff --git a/android/guava/src/com/google/common/graph/AbstractValueGraph.java b/android/guava/src/com/google/common/graph/AbstractValueGraph.java
index 940aeffc5..d8316ef89 100644
--- a/android/guava/src/com/google/common/graph/AbstractValueGraph.java
+++ b/android/guava/src/com/google/common/graph/AbstractValueGraph.java
@@ -19,7 +19,6 @@ package com.google.common.graph;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Set;
@@ -141,14 +140,10 @@ public abstract class AbstractValueGraph<N, V> extends AbstractBaseGraph<N>
}
private static <N, V> Map<EndpointPair<N>, V> edgeValueMap(final ValueGraph<N, V> graph) {
- Function<EndpointPair<N>, V> edgeToValueFn =
- new Function<EndpointPair<N>, V>() {
- @Override
- public V apply(EndpointPair<N> edge) {
+ return Maps.asMap(
+ graph.edges(),
+ edge ->
// requireNonNull is safe because the endpoint pair comes from the graph.
- return requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
- }
- };
- return Maps.asMap(graph.edges(), edgeToValueFn);
+ requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null)));
}
}
diff --git a/android/guava/src/com/google/common/graph/GraphBuilder.java b/android/guava/src/com/google/common/graph/GraphBuilder.java
index 8c0871b46..e275c43a5 100644
--- a/android/guava/src/com/google/common/graph/GraphBuilder.java
+++ b/android/guava/src/com/google/common/graph/GraphBuilder.java
@@ -22,19 +22,26 @@ import static com.google.common.graph.Graphs.checkNonNegative;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
/**
* A builder for constructing instances of {@link MutableGraph} or {@link ImmutableGraph} with
* user-defined properties.
*
- * <p>A graph built by this class will have the following properties by default:
+ * <p>A {@code Graph} built by this class has the following default properties:
*
* <ul>
* <li>does not allow self-loops
- * <li>orders {@link Graph#nodes()} in the order in which the elements were added
+ * <li>orders {@link Graph#nodes()} in the order in which the elements were added (insertion
+ * order)
* </ul>
*
+ * <p>{@code Graph}s built by this class also guarantee that each collection-returning accessor
+ * returns a <b>(live) unmodifiable view</b>; see <a
+ * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
+ * documentation</a> for details.
+ *
* <p>Examples of use:
*
* <pre>{@code
@@ -118,6 +125,7 @@ public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public GraphBuilder<N> allowsSelfLoops(boolean allowsSelfLoops) {
this.allowsSelfLoops = allowsSelfLoops;
return this;
@@ -128,6 +136,7 @@ public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedNodeCount} is negative
*/
+ @CanIgnoreReturnValue
public GraphBuilder<N> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
diff --git a/android/guava/src/com/google/common/graph/GraphConstants.java b/android/guava/src/com/google/common/graph/GraphConstants.java
index ae224fdd2..4e8510662 100644
--- a/android/guava/src/com/google/common/graph/GraphConstants.java
+++ b/android/guava/src/com/google/common/graph/GraphConstants.java
@@ -52,7 +52,7 @@ final class GraphConstants {
+ "adjacentNode(node) if you already have a node, or nodeU()/nodeV() if you don't.";
static final String EDGE_ALREADY_EXISTS = "Edge %s already exists in the graph.";
static final String ENDPOINTS_MISMATCH =
- "Mismatch: unordered endpoints cannot be used with directed graphs";
+ "Mismatch: endpoints' ordering is not compatible with directionality of the graph";
/** Singleton edge value for {@link Graph} implementations backed by {@link ValueGraph}s. */
enum Presence {
diff --git a/android/guava/src/com/google/common/graph/Graphs.java b/android/guava/src/com/google/common/graph/Graphs.java
index bad8580ac..e608eebc0 100644
--- a/android/guava/src/com/google/common/graph/Graphs.java
+++ b/android/guava/src/com/google/common/graph/Graphs.java
@@ -21,7 +21,6 @@ import static com.google.common.graph.GraphConstants.NODE_NOT_IN_GRAPH;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@@ -288,12 +287,7 @@ public final class Graphs {
public Iterator<EndpointPair<N>> iterator() {
return Iterators.transform(
delegate().incidentEdges(node).iterator(),
- new Function<EndpointPair<N>, EndpointPair<N>>() {
- @Override
- public EndpointPair<N> apply(EndpointPair<N> edge) {
- return EndpointPair.of(delegate(), edge.nodeV(), edge.nodeU());
- }
- });
+ edge -> EndpointPair.of(delegate(), edge.nodeV(), edge.nodeU()));
}
};
}
diff --git a/android/guava/src/com/google/common/graph/Network.java b/android/guava/src/com/google/common/graph/Network.java
index 70e39cdc0..adf0c3dd8 100644
--- a/android/guava/src/com/google/common/graph/Network.java
+++ b/android/guava/src/com/google/common/graph/Network.java
@@ -282,9 +282,10 @@ public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFuncti
*
* <p>In an undirected network, this is equal to {@code edgesConnecting(nodeV, nodeU)}.
*
- * <p>The resulting set of edges will be parallel (i.e. have equal {@link #incidentNodes(Object)}.
- * If this network does not {@link #allowsParallelEdges() allow parallel edges}, the resulting set
- * will contain at most one edge (equivalent to {@code edgeConnecting(nodeU, nodeV).asSet()}).
+ * <p>The resulting set of edges will be parallel (i.e. have equal {@link
+ * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
+ * edges}, the resulting set will contain at most one edge (equivalent to {@code
+ * edgeConnecting(nodeU, nodeV).asSet()}).
*
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* network
@@ -295,9 +296,10 @@ public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFuncti
* Returns the set of edges that each directly connect {@code endpoints} (in the order, if any,
* specified by {@code endpoints}).
*
- * <p>The resulting set of edges will be parallel (i.e. have equal {@link #incidentNodes(Object)}.
- * If this network does not {@link #allowsParallelEdges() allow parallel edges}, the resulting set
- * will contain at most one edge (equivalent to {@code edgeConnecting(endpoints).asSet()}).
+ * <p>The resulting set of edges will be parallel (i.e. have equal {@link
+ * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
+ * edges}, the resulting set will contain at most one edge (equivalent to {@code
+ * edgeConnecting(endpoints).asSet()}).
*
* <p>If this network is directed, {@code endpoints} must be ordered.
*
diff --git a/android/guava/src/com/google/common/graph/NetworkBuilder.java b/android/guava/src/com/google/common/graph/NetworkBuilder.java
index 968944493..c1f37147b 100644
--- a/android/guava/src/com/google/common/graph/NetworkBuilder.java
+++ b/android/guava/src/com/google/common/graph/NetworkBuilder.java
@@ -21,20 +21,26 @@ import static com.google.common.graph.Graphs.checkNonNegative;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
/**
* A builder for constructing instances of {@link MutableNetwork} or {@link ImmutableNetwork} with
* user-defined properties.
*
- * <p>A network built by this class will have the following properties by default:
+ * <p>A {@code Network} built by this class has the following default properties:
*
* <ul>
* <li>does not allow parallel edges
* <li>does not allow self-loops
* <li>orders {@link Network#nodes()} and {@link Network#edges()} in the order in which the
- * elements were added
+ * elements were added (insertion order)
* </ul>
*
+ * <p>{@code Network}s built by this class also guarantee that each collection-returning accessor
+ * returns a <b>(live) unmodifiable view</b>; see <a
+ * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
+ * documentation</a> for details.
+ *
* <p>Examples of use:
*
* <pre>{@code
@@ -122,6 +128,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> allowsParallelEdges(boolean allowsParallelEdges) {
this.allowsParallelEdges = allowsParallelEdges;
return this;
@@ -134,6 +141,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> allowsSelfLoops(boolean allowsSelfLoops) {
this.allowsSelfLoops = allowsSelfLoops;
return this;
@@ -144,6 +152,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedNodeCount} is negative
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
@@ -154,6 +163,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedEdgeCount} is negative
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> expectedEdgeCount(int expectedEdgeCount) {
this.expectedEdgeCount = Optional.of(checkNonNegative(expectedEdgeCount));
return this;
diff --git a/android/guava/src/com/google/common/graph/ParametricNullness.java b/android/guava/src/com/google/common/graph/ParametricNullness.java
index 87ff930a4..32fd5ee7e 100644
--- a/android/guava/src/com/google/common/graph/ParametricNullness.java
+++ b/android/guava/src/com/google/common/graph/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/graph/Traverser.java b/android/guava/src/com/google/common/graph/Traverser.java
index fb594b440..4ab4585f7 100644
--- a/android/guava/src/com/google/common/graph/Traverser.java
+++ b/android/guava/src/com/google/common/graph/Traverser.java
@@ -396,7 +396,7 @@ public abstract class Traverser<N> {
* requireNonNull(top.next())`) once our checker supports it.
*
* (The problem is likely
- * https://github.com/jspecify/nullness-checker-for-checker-framework/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecAnnotatedTypeFactory.java#L896)
+ * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecAnnotatedTypeFactory.java#L896)
*/
requireNonNull(element);
if (visited.add(element)) {
diff --git a/android/guava/src/com/google/common/graph/ValueGraphBuilder.java b/android/guava/src/com/google/common/graph/ValueGraphBuilder.java
index ce146c325..a4014606d 100644
--- a/android/guava/src/com/google/common/graph/ValueGraphBuilder.java
+++ b/android/guava/src/com/google/common/graph/ValueGraphBuilder.java
@@ -22,18 +22,25 @@ import static com.google.common.graph.Graphs.checkNonNegative;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
/**
* A builder for constructing instances of {@link MutableValueGraph} or {@link ImmutableValueGraph}
* with user-defined properties.
*
- * <p>A graph built by this class will have the following properties by default:
+ * <p>A {@code ValueGraph} built by this class has the following default properties:
*
* <ul>
* <li>does not allow self-loops
- * <li>orders {@link Graph#nodes()} in the order in which the elements were added
+ * <li>orders {@link ValueGraph#nodes()} in the order in which the elements were added (insertion
+ * order)
* </ul>
*
+ * <p>{@code ValueGraph}s built by this class also guarantee that each collection-returning accessor
+ * returns a <b>(live) unmodifiable view</b>; see <a
+ * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
+ * documentation</a> for details.
+ *
* <p>Examples of use:
*
* <pre>{@code
@@ -122,6 +129,7 @@ public final class ValueGraphBuilder<N, V> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public ValueGraphBuilder<N, V> allowsSelfLoops(boolean allowsSelfLoops) {
this.allowsSelfLoops = allowsSelfLoops;
return this;
@@ -132,6 +140,7 @@ public final class ValueGraphBuilder<N, V> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedNodeCount} is negative
*/
+ @CanIgnoreReturnValue
public ValueGraphBuilder<N, V> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
diff --git a/android/guava/src/com/google/common/hash/AbstractByteHasher.java b/android/guava/src/com/google/common/hash/AbstractByteHasher.java
index 9f7e04190..2c8682575 100644
--- a/android/guava/src/com/google/common/hash/AbstractByteHasher.java
+++ b/android/guava/src/com/google/common/hash/AbstractByteHasher.java
@@ -31,7 +31,6 @@ import java.nio.ByteOrder;
*
* @author Colin Decker
*/
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
abstract class AbstractByteHasher extends AbstractHasher {
private final ByteBuffer scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
@@ -64,6 +63,7 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
/** Updates the sink with the given number of bytes from the buffer. */
+ @CanIgnoreReturnValue
private Hasher update(int bytes) {
try {
update(scratch.array(), 0, bytes);
@@ -74,12 +74,14 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putByte(byte b) {
update(b);
return this;
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes) {
checkNotNull(bytes);
update(bytes);
@@ -87,6 +89,7 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
update(bytes, off, len);
@@ -94,30 +97,35 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(ByteBuffer bytes) {
update(bytes);
return this;
}
@Override
+ @CanIgnoreReturnValue
public Hasher putShort(short s) {
scratch.putShort(s);
return update(Shorts.BYTES);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putInt(int i) {
scratch.putInt(i);
return update(Ints.BYTES);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putLong(long l) {
scratch.putLong(l);
return update(Longs.BYTES);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putChar(char c) {
scratch.putChar(c);
return update(Chars.BYTES);
diff --git a/android/guava/src/com/google/common/hash/AbstractHasher.java b/android/guava/src/com/google/common/hash/AbstractHasher.java
index c72e05be0..905a425c9 100644
--- a/android/guava/src/com/google/common/hash/AbstractHasher.java
+++ b/android/guava/src/com/google/common/hash/AbstractHasher.java
@@ -26,25 +26,28 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Dimitris Andreou
*/
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
abstract class AbstractHasher implements Hasher {
@Override
+ @CanIgnoreReturnValue
public final Hasher putBoolean(boolean b) {
return putByte(b ? (byte) 1 : (byte) 0);
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putDouble(double d) {
return putLong(Double.doubleToRawLongBits(d));
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putFloat(float f) {
return putInt(Float.floatToRawIntBits(f));
}
@Override
+ @CanIgnoreReturnValue
public Hasher putUnencodedChars(CharSequence charSequence) {
for (int i = 0, len = charSequence.length(); i < len; i++) {
putChar(charSequence.charAt(i));
@@ -53,16 +56,19 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putString(CharSequence charSequence, Charset charset) {
return putBytes(charSequence.toString().getBytes(charset));
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes) {
return putBytes(bytes, 0, bytes.length);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes, int off, int len) {
Preconditions.checkPositionIndexes(off, off + len, bytes.length);
for (int i = 0; i < len; i++) {
@@ -72,6 +78,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(ByteBuffer b) {
if (b.hasArray()) {
putBytes(b.array(), b.arrayOffset() + b.position(), b.remaining());
@@ -85,6 +92,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putShort(short s) {
putByte((byte) s);
putByte((byte) (s >>> 8));
@@ -92,6 +100,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putInt(int i) {
putByte((byte) i);
putByte((byte) (i >>> 8));
@@ -101,6 +110,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putLong(long l) {
for (int i = 0; i < 64; i += 8) {
putByte((byte) (l >>> i));
@@ -109,6 +119,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putChar(char c) {
putByte((byte) c);
putByte((byte) (c >>> 8));
@@ -116,6 +127,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public <T extends @Nullable Object> Hasher putObject(
@ParametricNullness T instance, Funnel<? super T> funnel) {
funnel.funnel(instance, this);
diff --git a/android/guava/src/com/google/common/hash/AbstractStreamingHasher.java b/android/guava/src/com/google/common/hash/AbstractStreamingHasher.java
index a987b48c3..875bc6ec4 100644
--- a/android/guava/src/com/google/common/hash/AbstractStreamingHasher.java
+++ b/android/guava/src/com/google/common/hash/AbstractStreamingHasher.java
@@ -28,7 +28,6 @@ import java.nio.ByteOrder;
* @author Dimitris Andreou
*/
// TODO(kevinb): this class still needs some design-and-document-for-inheritance love
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
abstract class AbstractStreamingHasher extends AbstractHasher {
/** Buffer via which we pass data to the hash algorithm (the implementor) */
@@ -92,11 +91,13 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putBytes(byte[] bytes, int off, int len) {
return putBytesInternal(ByteBuffer.wrap(bytes, off, len).order(ByteOrder.LITTLE_ENDIAN));
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putBytes(ByteBuffer readBuffer) {
ByteOrder order = readBuffer.order();
try {
@@ -107,6 +108,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
}
+ @CanIgnoreReturnValue
private Hasher putBytesInternal(ByteBuffer readBuffer) {
// If we have room for all of it, this is easy
if (readBuffer.remaining() <= buffer.remaining()) {
@@ -143,6 +145,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
*/
@Override
+ @CanIgnoreReturnValue
public final Hasher putByte(byte b) {
buffer.put(b);
munchIfFull();
@@ -150,6 +153,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putShort(short s) {
buffer.putShort(s);
munchIfFull();
@@ -157,6 +161,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putChar(char c) {
buffer.putChar(c);
munchIfFull();
@@ -164,6 +169,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putInt(int i) {
buffer.putInt(i);
munchIfFull();
@@ -171,6 +177,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putLong(long l) {
buffer.putLong(l);
munchIfFull();
diff --git a/android/guava/src/com/google/common/hash/BloomFilter.java b/android/guava/src/com/google/common/hash/BloomFilter.java
index 331d160dc..d8b0690a7 100644
--- a/android/guava/src/com/google/common/hash/BloomFilter.java
+++ b/android/guava/src/com/google/common/hash/BloomFilter.java
@@ -31,6 +31,8 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.RoundingMode;
@@ -471,6 +473,10 @@ public final class BloomFilter<T extends @Nullable Object> implements Predicate<
return new SerialForm<T>(this);
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static class SerialForm<T extends @Nullable Object> implements Serializable {
final long[] data;
final int numHashFunctions;
diff --git a/android/guava/src/com/google/common/hash/BloomFilterStrategies.java b/android/guava/src/com/google/common/hash/BloomFilterStrategies.java
index 876269e9c..7c5650b2d 100644
--- a/android/guava/src/com/google/common/hash/BloomFilterStrategies.java
+++ b/android/guava/src/com/google/common/hash/BloomFilterStrategies.java
@@ -94,7 +94,7 @@ enum BloomFilterStrategies implements BloomFilter.Strategy {
},
/**
* This strategy uses all 128 bits of {@link Hashing#murmur3_128} when hashing. It looks different
- * than the implementation in MURMUR128_MITZ_32 because we're avoiding the multiplication in the
+ * from the implementation in MURMUR128_MITZ_32 because we're avoiding the multiplication in the
* loop and doing a (much simpler) += hash2. We're also changing the index to a positive number by
* AND'ing with Long.MAX_VALUE instead of flipping the bits.
*/
diff --git a/android/guava/src/com/google/common/hash/FarmHashFingerprint64.java b/android/guava/src/com/google/common/hash/FarmHashFingerprint64.java
index 3437b00a2..329a981c4 100644
--- a/android/guava/src/com/google/common/hash/FarmHashFingerprint64.java
+++ b/android/guava/src/com/google/common/hash/FarmHashFingerprint64.java
@@ -117,7 +117,7 @@ final class FarmHashFingerprint64 extends AbstractNonStreamingHashFunction {
private static long hashLength0to16(byte[] bytes, int offset, int length) {
if (length >= 8) {
- long mul = K2 + length * 2;
+ long mul = K2 + length * 2L;
long a = load64(bytes, offset) + K2;
long b = load64(bytes, offset + length - 8);
long c = rotateRight(b, 37) * mul + a;
@@ -141,7 +141,7 @@ final class FarmHashFingerprint64 extends AbstractNonStreamingHashFunction {
}
private static long hashLength17to32(byte[] bytes, int offset, int length) {
- long mul = K2 + length * 2;
+ long mul = K2 + length * 2L;
long a = load64(bytes, offset) * K1;
long b = load64(bytes, offset + 8);
long c = load64(bytes, offset + length - 8) * mul;
@@ -151,7 +151,7 @@ final class FarmHashFingerprint64 extends AbstractNonStreamingHashFunction {
}
private static long hashLength33To64(byte[] bytes, int offset, int length) {
- long mul = K2 + length * 2;
+ long mul = K2 + length * 2L;
long a = load64(bytes, offset) * K2;
long b = load64(bytes, offset + 8);
long c = load64(bytes, offset + length - 8) * mul;
diff --git a/android/guava/src/com/google/common/hash/Funnels.java b/android/guava/src/com/google/common/hash/Funnels.java
index b8e63d504..1d1d0a499 100644
--- a/android/guava/src/com/google/common/hash/Funnels.java
+++ b/android/guava/src/com/google/common/hash/Funnels.java
@@ -16,6 +16,8 @@ package com.google.common.hash;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
@@ -122,6 +124,10 @@ public final class Funnels {
return new SerializedForm(charset);
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static class SerializedForm implements Serializable {
private final String charsetCanonicalName;
diff --git a/android/guava/src/com/google/common/hash/Hasher.java b/android/guava/src/com/google/common/hash/Hasher.java
index b3f24fa28..f9a74c046 100644
--- a/android/guava/src/com/google/common/hash/Hasher.java
+++ b/android/guava/src/com/google/common/hash/Hasher.java
@@ -54,42 +54,52 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 11.0
*/
@Beta
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
public interface Hasher extends PrimitiveSink {
+ @CanIgnoreReturnValue
@Override
Hasher putByte(byte b);
+ @CanIgnoreReturnValue
@Override
Hasher putBytes(byte[] bytes);
+ @CanIgnoreReturnValue
@Override
Hasher putBytes(byte[] bytes, int off, int len);
+ @CanIgnoreReturnValue
@Override
Hasher putBytes(ByteBuffer bytes);
+ @CanIgnoreReturnValue
@Override
Hasher putShort(short s);
+ @CanIgnoreReturnValue
@Override
Hasher putInt(int i);
+ @CanIgnoreReturnValue
@Override
Hasher putLong(long l);
/** Equivalent to {@code putInt(Float.floatToRawIntBits(f))}. */
+ @CanIgnoreReturnValue
@Override
Hasher putFloat(float f);
/** Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}. */
+ @CanIgnoreReturnValue
@Override
Hasher putDouble(double d);
/** Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}. */
+ @CanIgnoreReturnValue
@Override
Hasher putBoolean(boolean b);
+ @CanIgnoreReturnValue
@Override
Hasher putChar(char c);
@@ -106,6 +116,7 @@ public interface Hasher extends PrimitiveSink {
*
* @since 15.0 (since 11.0 as putString(CharSequence)).
*/
+ @CanIgnoreReturnValue
@Override
Hasher putUnencodedChars(CharSequence charSequence);
@@ -117,10 +128,12 @@ public interface Hasher extends PrimitiveSink {
* faster, produces the same output across Java releases, and hashes every {@code char} in the
* input, even if some are invalid.
*/
+ @CanIgnoreReturnValue
@Override
Hasher putString(CharSequence charSequence, Charset charset);
/** A simple convenience for {@code funnel.funnel(object, this)}. */
+ @CanIgnoreReturnValue
<T extends @Nullable Object> Hasher putObject(
@ParametricNullness T instance, Funnel<? super T> funnel);
diff --git a/android/guava/src/com/google/common/hash/Hashing.java b/android/guava/src/com/google/common/hash/Hashing.java
index afff20c74..1d9d1e741 100644
--- a/android/guava/src/com/google/common/hash/Hashing.java
+++ b/android/guava/src/com/google/common/hash/Hashing.java
@@ -57,7 +57,8 @@ public final class Hashing {
* <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value
* for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances.
*
- * @param minimumBits a positive integer (can be arbitrarily large)
+ * @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link
+ * HashFunction} instance may use memory proportional to this integer.
* @return a hash function, described above, that produces hash codes of length {@code
* minimumBits} or greater
*/
@@ -373,9 +374,13 @@ public final class Hashing {
}
private static String hmacToString(String methodName, Key key) {
- return String.format(
- "Hashing.%s(Key[algorithm=%s, format=%s])",
- methodName, key.getAlgorithm(), key.getFormat());
+ return "Hashing."
+ + methodName
+ + "(Key[algorithm="
+ + key.getAlgorithm()
+ + ", format="
+ + key.getFormat()
+ + "])";
}
/**
diff --git a/android/guava/src/com/google/common/hash/IgnoreJRERequirement.java b/android/guava/src/com/google/common/hash/IgnoreJRERequirement.java
new file mode 100644
index 000000000..0de7c9a92
--- /dev/null
+++ b/android/guava/src/com/google/common/hash/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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.hash;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/android/guava/src/com/google/common/hash/LittleEndianByteArray.java b/android/guava/src/com/google/common/hash/LittleEndianByteArray.java
index 625201547..f8b9e7277 100644
--- a/android/guava/src/com/google/common/hash/LittleEndianByteArray.java
+++ b/android/guava/src/com/google/common/hash/LittleEndianByteArray.java
@@ -15,7 +15,11 @@
package com.google.common.hash;
import com.google.common.primitives.Longs;
+import java.lang.reflect.Field;
import java.nio.ByteOrder;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
import sun.misc.Unsafe;
/**
@@ -160,34 +164,32 @@ final class LittleEndianByteArray {
private static final int BYTE_ARRAY_BASE_OFFSET;
/**
- * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple
- * call to Unsafe.getUnsafe when integrating into a jdk.
+ * Returns an Unsafe. Suitable for use in a 3rd party package. Replace with a simple call to
+ * Unsafe.getUnsafe when integrating into a JDK.
*
- * @return a sun.misc.Unsafe instance if successful
+ * @return an Unsafe instance if successful
*/
- private static sun.misc.Unsafe getUnsafe() {
+ private static Unsafe getUnsafe() {
try {
- return sun.misc.Unsafe.getUnsafe();
+ return Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {
// We'll try reflection instead.
}
try {
- return java.security.AccessController.doPrivileged(
- new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
- @Override
- public sun.misc.Unsafe run() throws Exception {
- Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
- for (java.lang.reflect.Field f : k.getDeclaredFields()) {
- f.setAccessible(true);
- Object x = f.get(null);
- if (k.isInstance(x)) {
- return k.cast(x);
+ return AccessController.doPrivileged(
+ (PrivilegedExceptionAction<Unsafe>)
+ () -> {
+ Class<Unsafe> k = Unsafe.class;
+ for (Field f : k.getDeclaredFields()) {
+ f.setAccessible(true);
+ Object x = f.get(null);
+ if (k.isInstance(x)) {
+ return k.cast(x);
+ }
}
- }
- throw new NoSuchFieldError("the Unsafe");
- }
- });
- } catch (java.security.PrivilegedActionException e) {
+ throw new NoSuchFieldError("the Unsafe");
+ });
+ } catch (PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics", e.getCause());
}
}
@@ -226,7 +228,7 @@ final class LittleEndianByteArray {
sink[offset + i] = (byte) ((value & mask) >> (i * 8));
}
}
- };
+ }
}
static {
diff --git a/android/guava/src/com/google/common/hash/MessageDigestHashFunction.java b/android/guava/src/com/google/common/hash/MessageDigestHashFunction.java
index 43fc087f2..0fe3347ea 100644
--- a/android/guava/src/com/google/common/hash/MessageDigestHashFunction.java
+++ b/android/guava/src/com/google/common/hash/MessageDigestHashFunction.java
@@ -19,6 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.errorprone.annotations.Immutable;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
@@ -120,6 +122,10 @@ final class MessageDigestHashFunction extends AbstractHashFunction implements Se
return new SerializedForm(prototype.getAlgorithm(), bytes, toString);
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/** Hasher that updates a message digest. */
private static final class MessageDigestHasher extends AbstractByteHasher {
private final MessageDigest digest;
diff --git a/android/guava/src/com/google/common/hash/Murmur3_32HashFunction.java b/android/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
index a47184be5..c320cd218 100644
--- a/android/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
+++ b/android/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
@@ -267,7 +267,6 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return HashCode.fromInt(h1);
}
- @CanIgnoreReturnValue
private static final class Murmur3_32Hasher extends AbstractHasher {
private int h1;
private long buffer;
@@ -294,12 +293,14 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
}
}
+ @CanIgnoreReturnValue
@Override
public Hasher putByte(byte b) {
update(1, b & 0xFF);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putBytes(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
@@ -313,6 +314,7 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putBytes(ByteBuffer buffer) {
ByteOrder bo = buffer.order();
@@ -327,12 +329,14 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putInt(int i) {
update(4, i);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putLong(long l) {
update(4, (int) l);
@@ -340,12 +344,14 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putChar(char c) {
update(2, c);
return this;
}
+ @CanIgnoreReturnValue
@SuppressWarnings("deprecation") // need to use Charsets for Android tests to pass
@Override
public Hasher putString(CharSequence input, Charset charset) {
diff --git a/android/guava/src/com/google/common/hash/ParametricNullness.java b/android/guava/src/com/google/common/hash/ParametricNullness.java
index 460106c09..4ebc40bb7 100644
--- a/android/guava/src/com/google/common/hash/ParametricNullness.java
+++ b/android/guava/src/com/google/common/hash/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/hash/PrimitiveSink.java b/android/guava/src/com/google/common/hash/PrimitiveSink.java
index a29ba4e13..ecd6a32c8 100644
--- a/android/guava/src/com/google/common/hash/PrimitiveSink.java
+++ b/android/guava/src/com/google/common/hash/PrimitiveSink.java
@@ -26,7 +26,6 @@ import java.nio.charset.Charset;
* @since 12.0 (in 11.0 as {@code Sink})
*/
@Beta
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
public interface PrimitiveSink {
/**
@@ -35,6 +34,7 @@ public interface PrimitiveSink {
* @param b a byte
* @return this instance
*/
+ @CanIgnoreReturnValue
PrimitiveSink putByte(byte b);
/**
@@ -43,6 +43,7 @@ public interface PrimitiveSink {
* @param bytes a byte array
* @return this instance
*/
+ @CanIgnoreReturnValue
PrimitiveSink putBytes(byte[] bytes);
/**
@@ -56,6 +57,7 @@ public interface PrimitiveSink {
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or
* {@code len < 0}
*/
+ @CanIgnoreReturnValue
PrimitiveSink putBytes(byte[] bytes, int off, int len);
/**
@@ -67,27 +69,35 @@ public interface PrimitiveSink {
* @return this instance
* @since 23.0
*/
+ @CanIgnoreReturnValue
PrimitiveSink putBytes(ByteBuffer bytes);
/** Puts a short into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putShort(short s);
/** Puts an int into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putInt(int i);
/** Puts a long into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putLong(long l);
/** Puts a float into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putFloat(float f);
/** Puts a double into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putDouble(double d);
/** Puts a boolean into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putBoolean(boolean b);
/** Puts a character into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putChar(char c);
/**
@@ -99,6 +109,7 @@ public interface PrimitiveSink {
*
* @since 15.0 (since 11.0 as putString(CharSequence))
*/
+ @CanIgnoreReturnValue
PrimitiveSink putUnencodedChars(CharSequence charSequence);
/**
@@ -109,5 +120,6 @@ public interface PrimitiveSink {
* is faster, produces the same output across Java releases, and processes every {@code char} in
* the input, even if some are invalid.
*/
+ @CanIgnoreReturnValue
PrimitiveSink putString(CharSequence charSequence, Charset charset);
}
diff --git a/android/guava/src/com/google/common/html/ParametricNullness.java b/android/guava/src/com/google/common/html/ParametricNullness.java
index 61b446164..50a64c781 100644
--- a/android/guava/src/com/google/common/html/ParametricNullness.java
+++ b/android/guava/src/com/google/common/html/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/html/package-info.java b/android/guava/src/com/google/common/html/package-info.java
index f84d7f23d..1a97bccd1 100644
--- a/android/guava/src/com/google/common/html/package-info.java
+++ b/android/guava/src/com/google/common/html/package-info.java
@@ -17,7 +17,7 @@
* for
* HTML.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/android/guava/src/com/google/common/io/AppendableWriter.java b/android/guava/src/com/google/common/io/AppendableWriter.java
index d9aab342f..8566569a9 100644
--- a/android/guava/src/com/google/common/io/AppendableWriter.java
+++ b/android/guava/src/com/google/common/io/AppendableWriter.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
@@ -31,6 +32,7 @@ import javax.annotation.CheckForNull;
* @author Sebastian Kanthak
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
class AppendableWriter extends Writer {
diff --git a/android/guava/src/com/google/common/io/BaseEncoding.java b/android/guava/src/com/google/common/io/BaseEncoding.java
index 0d6f2e068..50a8ff7e4 100644
--- a/android/guava/src/com/google/common/io/BaseEncoding.java
+++ b/android/guava/src/com/google/common/io/BaseEncoding.java
@@ -26,8 +26,8 @@ import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
-import com.google.common.base.Objects;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.IOException;
import java.io.InputStream;
@@ -35,6 +35,7 @@ import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
+import java.util.Objects;
import javax.annotation.CheckForNull;
/**
@@ -169,12 +170,14 @@ public abstract class BaseEncoding {
* {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code
* Writer}.
*/
+ @J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
public abstract OutputStream encodingStream(Writer writer);
/**
* Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}.
*/
+ @J2ktIncompatible
@GwtIncompatible // ByteSink,CharSink
public final ByteSink encodingSink(CharSink encodedSink) {
checkNotNull(encodedSink);
@@ -239,6 +242,7 @@ public abstract class BaseEncoding {
* Returns an {@code InputStream} that decodes base-encoded input from the specified {@code
* Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors.
*/
+ @J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public abstract InputStream decodingStream(Reader reader);
@@ -246,6 +250,7 @@ public abstract class BaseEncoding {
* Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code
* CharSource}.
*/
+ @J2ktIncompatible
@GwtIncompatible // ByteSource,CharSource
public final ByteSource decodingSource(CharSource encodedSource) {
checkNotNull(encodedSource);
@@ -318,6 +323,16 @@ public abstract class BaseEncoding {
*/
public abstract BaseEncoding lowerCase();
+ /**
+ * Returns an encoding that behaves equivalently to this encoding, but decodes letters without
+ * regard to case.
+ *
+ * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
+ * lower-case characters
+ * @since 32.0.0
+ */
+ public abstract BaseEncoding ignoreCase();
+
private static final BaseEncoding BASE64 =
new Base64Encoding(
"base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '=');
@@ -428,8 +443,13 @@ public abstract class BaseEncoding {
final int bytesPerChunk;
private final byte[] decodabet;
private final boolean[] validPadding;
+ private final boolean ignoreCase;
Alphabet(String name, char[] chars) {
+ this(name, chars, decodabetFor(chars), /* ignoreCase= */ false);
+ }
+
+ private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) {
this.name = checkNotNull(name);
this.chars = checkNotNull(chars);
try {
@@ -438,20 +458,30 @@ public abstract class BaseEncoding {
throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e);
}
- /*
- * e.g. for base64, bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. This makes
- * for the smallest chunk size that still has charsPerChunk * bitsPerChar be a multiple of 8.
- */
- int gcd = Math.min(8, Integer.lowestOneBit(bitsPerChar));
- try {
- this.charsPerChunk = 8 / gcd;
- this.bytesPerChunk = bitsPerChar / gcd;
- } catch (ArithmeticException e) {
- throw new IllegalArgumentException("Illegal alphabet " + new String(chars), e);
- }
+ // Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into
+ // 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3.
+ // We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a
+ // multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many
+ // extra zero bits we need to add to the end of bitsPerChar to get 3 in total.
+ // The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII
+ // characters that can't happen.
+ int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar);
+ this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar);
+ this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar;
this.mask = chars.length - 1;
+ this.decodabet = decodabet;
+
+ boolean[] validPadding = new boolean[charsPerChunk];
+ for (int i = 0; i < bytesPerChunk; i++) {
+ validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
+ }
+ this.validPadding = validPadding;
+ this.ignoreCase = ignoreCase;
+ }
+
+ private static byte[] decodabetFor(char[] chars) {
byte[] decodabet = new byte[Ascii.MAX + 1];
Arrays.fill(decodabet, (byte) -1);
for (int i = 0; i < chars.length; i++) {
@@ -460,13 +490,33 @@ public abstract class BaseEncoding {
checkArgument(decodabet[c] == -1, "Duplicate character: %s", c);
decodabet[c] = (byte) i;
}
- this.decodabet = decodabet;
+ return decodabet;
+ }
- boolean[] validPadding = new boolean[charsPerChunk];
- for (int i = 0; i < bytesPerChunk; i++) {
- validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
+ /** Returns an equivalent {@code Alphabet} except it ignores case. */
+ Alphabet ignoreCase() {
+ if (ignoreCase) {
+ return this;
}
- this.validPadding = validPadding;
+
+ // We can't use .clone() because of GWT.
+ byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length);
+ for (int upper = 'A'; upper <= 'Z'; upper++) {
+ int lower = upper | 0x20;
+ byte decodeUpper = decodabet[upper];
+ byte decodeLower = decodabet[lower];
+ if (decodeUpper == -1) {
+ newDecodabet[upper] = decodeLower;
+ } else {
+ checkState(
+ decodeLower == -1,
+ "Can't ignoreCase() since '%s' and '%s' encode different values",
+ (char) upper,
+ (char) lower);
+ newDecodabet[lower] = decodeUpper;
+ }
+ }
+ return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true);
}
char encode(int bits) {
@@ -523,7 +573,8 @@ public abstract class BaseEncoding {
for (int i = 0; i < chars.length; i++) {
upperCased[i] = Ascii.toUpperCase(chars[i]);
}
- return new Alphabet(name + ".upperCase()", upperCased);
+ Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased);
+ return ignoreCase ? upperCase.ignoreCase() : upperCase;
}
Alphabet lowerCase() {
@@ -535,7 +586,8 @@ public abstract class BaseEncoding {
for (int i = 0; i < chars.length; i++) {
lowerCased[i] = Ascii.toLowerCase(chars[i]);
}
- return new Alphabet(name + ".lowerCase()", lowerCased);
+ Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased);
+ return ignoreCase ? lowerCase.ignoreCase() : lowerCase;
}
public boolean matches(char c) {
@@ -551,19 +603,18 @@ public abstract class BaseEncoding {
public boolean equals(@CheckForNull Object other) {
if (other instanceof Alphabet) {
Alphabet that = (Alphabet) other;
- return Arrays.equals(this.chars, that.chars);
+ return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars);
}
return false;
}
@Override
public int hashCode() {
- return Arrays.hashCode(chars);
+ return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237);
}
}
static class StandardBaseEncoding extends BaseEncoding {
- // TODO(lowasser): provide a useful toString
final Alphabet alphabet;
@CheckForNull final Character paddingChar;
@@ -586,6 +637,7 @@ public abstract class BaseEncoding {
return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING);
}
+ @J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer out) {
@@ -727,6 +779,7 @@ public abstract class BaseEncoding {
}
@Override
+ @J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
checkNotNull(reader);
@@ -830,8 +883,9 @@ public abstract class BaseEncoding {
return new SeparatedBaseEncoding(this, separator, afterEveryChars);
}
- @LazyInit @CheckForNull private transient BaseEncoding upperCase;
- @LazyInit @CheckForNull private transient BaseEncoding lowerCase;
+ @LazyInit @CheckForNull private volatile BaseEncoding upperCase;
+ @LazyInit @CheckForNull private volatile BaseEncoding lowerCase;
+ @LazyInit @CheckForNull private volatile BaseEncoding ignoreCase;
@Override
public BaseEncoding upperCase() {
@@ -853,6 +907,16 @@ public abstract class BaseEncoding {
return result;
}
+ @Override
+ public BaseEncoding ignoreCase() {
+ BaseEncoding result = ignoreCase;
+ if (result == null) {
+ Alphabet ignore = alphabet.ignoreCase();
+ result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar);
+ }
+ return result;
+ }
+
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new StandardBaseEncoding(alphabet, paddingChar);
}
@@ -860,7 +924,7 @@ public abstract class BaseEncoding {
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BaseEncoding.");
- builder.append(alphabet.toString());
+ builder.append(alphabet);
if (8 % alphabet.bitsPerChar != 0) {
if (paddingChar == null) {
builder.append(".omitPadding()");
@@ -876,7 +940,7 @@ public abstract class BaseEncoding {
if (other instanceof StandardBaseEncoding) {
StandardBaseEncoding that = (StandardBaseEncoding) other;
return this.alphabet.equals(that.alphabet)
- && Objects.equal(this.paddingChar, that.paddingChar);
+ && Objects.equals(this.paddingChar, that.paddingChar);
}
return false;
}
@@ -991,6 +1055,7 @@ public abstract class BaseEncoding {
}
}
+ @J2ktIncompatible
@GwtIncompatible
static Reader ignoringReader(Reader delegate, String toIgnore) {
checkNotNull(delegate);
@@ -1048,6 +1113,7 @@ public abstract class BaseEncoding {
};
}
+ @J2ktIncompatible
@GwtIncompatible // Writer
static Writer separatingWriter(Writer delegate, String separator, int afterEveryChars) {
Appendable separatingAppendable = separatingAppendable(delegate, separator, afterEveryChars);
@@ -1099,6 +1165,7 @@ public abstract class BaseEncoding {
+ separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR);
}
+ @J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer output) {
@@ -1140,6 +1207,7 @@ public abstract class BaseEncoding {
}
@Override
+ @J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
return delegate.decodingStream(ignoringReader(reader, separator));
@@ -1171,6 +1239,11 @@ public abstract class BaseEncoding {
}
@Override
+ public BaseEncoding ignoreCase() {
+ return delegate.ignoreCase().withSeparator(separator, afterEveryChars);
+ }
+
+ @Override
public String toString() {
return delegate + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")";
}
diff --git a/android/guava/src/com/google/common/io/ByteArrayDataInput.java b/android/guava/src/com/google/common/io/ByteArrayDataInput.java
index cf84fcc13..9fa295904 100644
--- a/android/guava/src/com/google/common/io/ByteArrayDataInput.java
+++ b/android/guava/src/com/google/common/io/ByteArrayDataInput.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.DataInput;
import java.io.IOException;
@@ -32,6 +33,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ByteArrayDataInput extends DataInput {
diff --git a/android/guava/src/com/google/common/io/ByteArrayDataOutput.java b/android/guava/src/com/google/common/io/ByteArrayDataOutput.java
index 373907361..487783531 100644
--- a/android/guava/src/com/google/common/io/ByteArrayDataOutput.java
+++ b/android/guava/src/com/google/common/io/ByteArrayDataOutput.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.DataOutput;
import java.io.IOException;
@@ -25,6 +26,7 @@ import java.io.IOException;
* @author Jayaprabhakar Kadarkarai
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ByteArrayDataOutput extends DataOutput {
diff --git a/android/guava/src/com/google/common/io/ByteProcessor.java b/android/guava/src/com/google/common/io/ByteProcessor.java
index 98ea3ffbb..cfb531c5a 100644
--- a/android/guava/src/com/google/common/io/ByteProcessor.java
+++ b/android/guava/src/com/google/common/io/ByteProcessor.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.io.IOException;
@@ -30,8 +30,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Chris Nokleberg
* @since 1.0
*/
-@Beta
@DoNotMock("Implement it normally")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ByteProcessor<T extends @Nullable Object> {
diff --git a/android/guava/src/com/google/common/io/ByteSink.java b/android/guava/src/com/google/common/io/ByteSink.java
index 7a6af6fc5..230216919 100644
--- a/android/guava/src/com/google/common/io/ByteSink.java
+++ b/android/guava/src/com/google/common/io/ByteSink.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedOutputStream;
import java.io.IOException;
@@ -45,6 +46,7 @@ import java.nio.charset.Charset;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ByteSink {
diff --git a/android/guava/src/com/google/common/io/ByteSource.java b/android/guava/src/com/google/common/io/ByteSource.java
index c8da9678b..31a5aa5d5 100644
--- a/android/guava/src/com/google/common/io/ByteSource.java
+++ b/android/guava/src/com/google/common/io/ByteSource.java
@@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.ByteStreams.createBuffer;
import static com.google.common.io.ByteStreams.skipUpTo;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
@@ -73,6 +73,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ByteSource {
@@ -178,7 +179,6 @@ public abstract class ByteSource {
*
* @since 19.0
*/
- @Beta
public Optional<Long> sizeIfKnown() {
return Optional.absent();
}
@@ -314,8 +314,8 @@ public abstract class ByteSource {
* processor} throws an {@code IOException}
* @since 16.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
+ @ParametricNullness
public <T extends @Nullable Object> T read(ByteProcessor<T> processor) throws IOException {
checkNotNull(processor);
@@ -571,7 +571,9 @@ public abstract class ByteSource {
}
}
- private static class ByteArrayByteSource extends ByteSource {
+ private static class ByteArrayByteSource extends
+ ByteSource
+ {
final byte[] bytes;
final int offset;
@@ -594,7 +596,7 @@ public abstract class ByteSource {
}
@Override
- public InputStream openBufferedStream() throws IOException {
+ public InputStream openBufferedStream() {
return openStream();
}
diff --git a/android/guava/src/com/google/common/io/ByteStreams.java b/android/guava/src/com/google/common/io/ByteStreams.java
index 99213bf16..640bc8bfc 100644
--- a/android/guava/src/com/google/common/io/ByteStreams.java
+++ b/android/guava/src/com/google/common/io/ByteStreams.java
@@ -21,8 +21,8 @@ import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Math.max;
import static java.lang.Math.min;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.ByteArrayInputStream;
@@ -53,6 +53,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ByteStreams {
@@ -99,6 +100,9 @@ public final class ByteStreams {
* Copies all bytes from the input stream to the output stream. Does not close or flush either
* stream.
*
+ * <p><b>Java 9 users and later:</b> this method should be treated as deprecated; use the
+ * equivalent {@link InputStream#transferTo} method instead.
+ *
* @param from the input stream to read from
* @param to the output stream to write to
* @return the number of bytes copied
@@ -283,7 +287,6 @@ public final class ByteStreams {
* @since 20.0
*/
@CanIgnoreReturnValue
- @Beta
public static long exhaust(InputStream in) throws IOException {
long total = 0;
long read;
@@ -298,7 +301,6 @@ public final class ByteStreams {
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the
* beginning.
*/
- @Beta
public static ByteArrayDataInput newDataInput(byte[] bytes) {
return newDataInput(new ByteArrayInputStream(bytes));
}
@@ -310,7 +312,6 @@ public final class ByteStreams {
* @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of
* the array
*/
- @Beta
public static ByteArrayDataInput newDataInput(byte[] bytes, int start) {
checkPositionIndex(start, bytes.length);
return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start));
@@ -323,7 +324,6 @@ public final class ByteStreams {
*
* @since 17.0
*/
- @Beta
public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) {
return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream));
}
@@ -475,7 +475,6 @@ public final class ByteStreams {
}
/** Returns a new {@link ByteArrayDataOutput} instance with a default size. */
- @Beta
public static ByteArrayDataOutput newDataOutput() {
return newDataOutput(new ByteArrayOutputStream());
}
@@ -486,7 +485,6 @@ public final class ByteStreams {
*
* @throws IllegalArgumentException if {@code size} is negative
*/
- @Beta
public static ByteArrayDataOutput newDataOutput(int size) {
// When called at high frequency, boxing size generates too much garbage,
// so avoid doing that if we can.
@@ -508,7 +506,6 @@ public final class ByteStreams {
*
* @since 17.0
*/
- @Beta
public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputStream) {
return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputStream));
}
@@ -685,7 +682,6 @@ public final class ByteStreams {
*
* @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream)
*/
- @Beta
public static OutputStream nullOutputStream() {
return NULL_OUTPUT_STREAM;
}
@@ -698,7 +694,6 @@ public final class ByteStreams {
* @return a length-limited {@link InputStream}
* @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream)
*/
- @Beta
public static InputStream limit(InputStream in, long limit) {
return new LimitedInputStream(in, limit);
}
@@ -785,7 +780,6 @@ public final class ByteStreams {
* @throws EOFException if this stream reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
- @Beta
public static void readFully(InputStream in, byte[] b) throws IOException {
readFully(in, b, 0, b.length);
}
@@ -802,7 +796,6 @@ public final class ByteStreams {
* @throws EOFException if this stream reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
- @Beta
public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException {
int read = read(in, b, off, len);
if (read != len) {
@@ -820,7 +813,6 @@ public final class ByteStreams {
* @throws EOFException if this stream reaches the end before skipping all the bytes
* @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
- @Beta
public static void skipFully(InputStream in, long n) throws IOException {
long skipped = skipUpTo(in, n);
if (skipped < n) {
@@ -886,7 +878,6 @@ public final class ByteStreams {
* @throws IOException if an I/O error occurs
* @since 14.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public static <T extends @Nullable Object> T readBytes(
@@ -926,7 +917,6 @@ public final class ByteStreams {
* @throws IndexOutOfBoundsException if {@code off} is negative, if {@code len} is negative, or if
* {@code off + len} is greater than {@code b.length}
*/
- @Beta
@CanIgnoreReturnValue
// Sometimes you don't care how many bytes you actually read, I guess.
// (You know that it's either going to read len bytes or stop at EOF.)
diff --git a/android/guava/src/com/google/common/io/CharSequenceReader.java b/android/guava/src/com/google/common/io/CharSequenceReader.java
index 790e26623..152743fec 100644
--- a/android/guava/src/com/google/common/io/CharSequenceReader.java
+++ b/android/guava/src/com/google/common/io/CharSequenceReader.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
@@ -32,6 +33,7 @@ import javax.annotation.CheckForNull;
* @author Colin Decker
*/
// TODO(cgdecker): make this public? as a type, or a method in CharStreams?
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class CharSequenceReader extends Reader {
diff --git a/android/guava/src/com/google/common/io/CharSink.java b/android/guava/src/com/google/common/io/CharSink.java
index bdf5f38c3..2ea37c929 100644
--- a/android/guava/src/com/google/common/io/CharSink.java
+++ b/android/guava/src/com/google/common/io/CharSink.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -47,6 +48,7 @@ import java.nio.charset.Charset;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class CharSink {
diff --git a/android/guava/src/com/google/common/io/CharSource.java b/android/guava/src/com/google/common/io/CharSource.java
index b7623ff62..f7a4abe87 100644
--- a/android/guava/src/com/google/common/io/CharSource.java
+++ b/android/guava/src/com/google/common/io/CharSource.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
@@ -76,6 +76,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class CharSource {
@@ -94,7 +95,6 @@ public abstract class CharSource {
*
* @since 20.0
*/
- @Beta
public ByteSource asByteSource(Charset charset) {
return new AsByteSource(charset);
}
@@ -138,7 +138,6 @@ public abstract class CharSource {
*
* @since 19.0
*/
- @Beta
public Optional<Long> lengthIfKnown() {
return Optional.absent();
}
@@ -162,7 +161,6 @@ public abstract class CharSource {
* @throws IOException if an I/O error occurs while reading the length of this source
* @since 19.0
*/
- @Beta
public long length() throws IOException {
Optional<Long> lengthIfKnown = lengthIfKnown();
if (lengthIfKnown.isPresent()) {
@@ -317,7 +315,6 @@ public abstract class CharSource {
* processor} throws an {@code IOException}
* @since 16.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException {
diff --git a/android/guava/src/com/google/common/io/CharStreams.java b/android/guava/src/com/google/common/io/CharStreams.java
index d36f9a3c5..877de824d 100644
--- a/android/guava/src/com/google/common/io/CharStreams.java
+++ b/android/guava/src/com/google/common/io/CharStreams.java
@@ -17,8 +17,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Closeable;
import java.io.EOFException;
@@ -43,6 +43,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CharStreams {
@@ -193,7 +194,6 @@ public final class CharStreams {
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
- @Beta
public static List<String> readLines(Readable r) throws IOException {
List<String> result = new ArrayList<>();
LineReader lineReader = new LineReader(r);
@@ -213,7 +213,6 @@ public final class CharStreams {
* @throws IOException if an I/O error occurs
* @since 14.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public static <T extends @Nullable Object> T readLines(
@@ -237,7 +236,6 @@ public final class CharStreams {
*
* @since 20.0
*/
- @Beta
@CanIgnoreReturnValue
public static long exhaust(Readable readable) throws IOException {
long total = 0;
@@ -259,7 +257,6 @@ public final class CharStreams {
* @throws EOFException if this stream reaches the end before skipping all the characters
* @throws IOException if an I/O error occurs
*/
- @Beta
public static void skipFully(Reader reader, long n) throws IOException {
checkNotNull(reader);
while (n > 0) {
@@ -276,7 +273,6 @@ public final class CharStreams {
*
* @since 15.0
*/
- @Beta
public static Writer nullWriter() {
return NullWriter.INSTANCE;
}
@@ -344,7 +340,6 @@ public final class CharStreams {
* @param target the object to which output will be sent
* @return a new Writer object, unless target is a Writer, in which case the target is returned
*/
- @Beta
public static Writer asWriter(Appendable target) {
if (target instanceof Writer) {
return (Writer) target;
diff --git a/android/guava/src/com/google/common/io/Closeables.java b/android/guava/src/com/google/common/io/Closeables.java
index b45f5f0fd..aca51a996 100644
--- a/android/guava/src/com/google/common/io/Closeables.java
+++ b/android/guava/src/com/google/common/io/Closeables.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.IOException;
@@ -31,7 +31,7 @@ import javax.annotation.CheckForNull;
* @author Michael Lancaster
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Closeables {
diff --git a/android/guava/src/com/google/common/io/Closer.java b/android/guava/src/com/google/common/io/Closer.java
index 12998eff9..8e1db7a83 100644
--- a/android/guava/src/com/google/common/io/Closer.java
+++ b/android/guava/src/com/google/common/io/Closer.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -87,7 +87,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0
*/
// Coffee's for {@link Closer closers} only.
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Closer implements Closeable {
diff --git a/android/guava/src/com/google/common/io/CountingInputStream.java b/android/guava/src/com/google/common/io/CountingInputStream.java
index a37807ae7..bc481dd74 100644
--- a/android/guava/src/com/google/common/io/CountingInputStream.java
+++ b/android/guava/src/com/google/common/io/CountingInputStream.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -28,7 +28,7 @@ import java.io.InputStream;
* @author Chris Nokleberg
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CountingInputStream extends FilterInputStream {
diff --git a/android/guava/src/com/google/common/io/CountingOutputStream.java b/android/guava/src/com/google/common/io/CountingOutputStream.java
index cf62b9c37..1cbfe081f 100644
--- a/android/guava/src/com/google/common/io/CountingOutputStream.java
+++ b/android/guava/src/com/google/common/io/CountingOutputStream.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -27,6 +28,7 @@ import java.io.OutputStream;
* @author Chris Nokleberg
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CountingOutputStream extends FilterOutputStream {
diff --git a/android/guava/src/com/google/common/io/FileBackedOutputStream.java b/android/guava/src/com/google/common/io/FileBackedOutputStream.java
index 9912e2fcd..dd297e90a 100644
--- a/android/guava/src/com/google/common/io/FileBackedOutputStream.java
+++ b/android/guava/src/com/google/common/io/FileBackedOutputStream.java
@@ -14,12 +14,15 @@
package com.google.common.io;
+import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -34,6 +37,14 @@ import javax.annotation.CheckForNull;
* An {@link OutputStream} that starts buffering to a byte array, but switches to file buffering
* once the data reaches a configurable size.
*
+ * <p>When this stream creates a temporary file, it restricts the file's permissions to the current
+ * user or, in the case of Android, the current app. If that is not possible (as is the case under
+ * the very old Android Ice Cream Sandwich release), then this stream throws an exception instead of
+ * creating a file that would be more accessible. (This behavior is new in Guava 32.0.0. Previous
+ * versions would create a file that is more accessible, as discussed in <a
+ * href="https://github.com/google/guava/issues/2575">Guava issue 2575</a>. TODO: b/283778848 - Fill
+ * in CVE number once it's available.)
+ *
* <p>Temporary files created by this stream may live in the local filesystem until either:
*
* <ul>
@@ -51,13 +62,14 @@ import javax.annotation.CheckForNull;
* @since 1.0
*/
@Beta
+@J2ktIncompatible
@GwtIncompatible
+@J2ObjCIncompatible
@ElementTypesAreNonnullByDefault
public final class FileBackedOutputStream extends OutputStream {
private final int fileThreshold;
private final boolean resetOnFinalize;
private final ByteSource source;
- @CheckForNull private final File parentDirectory;
@GuardedBy("this")
private OutputStream out;
@@ -93,6 +105,7 @@ public final class FileBackedOutputStream extends OutputStream {
* {@link ByteSource} returned by {@link #asByteSource} is finalized.
*
* @param fileThreshold the number of bytes before the stream should switch to buffering to a file
+ * @throws IllegalArgumentException if {@code fileThreshold} is negative
*/
public FileBackedOutputStream(int fileThreshold) {
this(fileThreshold, false);
@@ -105,16 +118,13 @@ public final class FileBackedOutputStream extends OutputStream {
* @param fileThreshold the number of bytes before the stream should switch to buffering to a file
* @param resetOnFinalize if true, the {@link #reset} method will be called when the {@link
* ByteSource} returned by {@link #asByteSource} is finalized.
+ * @throws IllegalArgumentException if {@code fileThreshold} is negative
*/
public FileBackedOutputStream(int fileThreshold, boolean resetOnFinalize) {
- this(fileThreshold, resetOnFinalize, null);
- }
-
- private FileBackedOutputStream(
- int fileThreshold, boolean resetOnFinalize, @CheckForNull File parentDirectory) {
+ checkArgument(
+ fileThreshold >= 0, "fileThreshold must be non-negative, but was %s", fileThreshold);
this.fileThreshold = fileThreshold;
this.resetOnFinalize = resetOnFinalize;
- this.parentDirectory = parentDirectory;
memory = new MemoryOutput();
out = memory;
@@ -225,7 +235,7 @@ public final class FileBackedOutputStream extends OutputStream {
@GuardedBy("this")
private void update(int len) throws IOException {
if (memory != null && (memory.getCount() + len > fileThreshold)) {
- File temp = File.createTempFile("FileBackedOutputStream", null, parentDirectory);
+ File temp = TempFileCreator.INSTANCE.createTempFile("FileBackedOutputStream");
if (resetOnFinalize) {
// Finalizers are not guaranteed to be called on system shutdown;
// this is insurance.
diff --git a/android/guava/src/com/google/common/io/FileWriteMode.java b/android/guava/src/com/google/common/io/FileWriteMode.java
index 86872d1ba..47cf251e7 100644
--- a/android/guava/src/com/google/common/io/FileWriteMode.java
+++ b/android/guava/src/com/google/common/io/FileWriteMode.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
/**
* Modes for opening a file for writing. The default when mode when none is specified is to truncate
@@ -22,6 +23,7 @@ import com.google.common.annotations.GwtIncompatible;
*
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public enum FileWriteMode {
diff --git a/android/guava/src/com/google/common/io/Files.java b/android/guava/src/com/google/common/io/Files.java
index ba5528ff8..499ea6a20 100644
--- a/android/guava/src/com/google/common/io/Files.java
+++ b/android/guava/src/com/google/common/io/Files.java
@@ -20,6 +20,7 @@ import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
@@ -33,6 +34,7 @@ import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.InlineMe;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
@@ -66,13 +68,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Files {
- /** Maximum loop count when creating temp directories. */
- private static final int TEMP_DIR_ATTEMPTS = 10000;
-
private Files() {}
/**
@@ -119,7 +119,9 @@ public final class Files {
return new FileByteSource(file);
}
- private static final class FileByteSource extends ByteSource {
+ private static final class FileByteSource extends
+ ByteSource
+ {
private final File file;
@@ -394,17 +396,19 @@ public final class Files {
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
+ * <p>The temporary directory is created with permissions restricted to the current user or, in
+ * the case of Android, the current app. If that is not possible (as is the case under the very
+ * old Android Ice Cream Sandwich release), then this method throws an exception instead of
+ * creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0.
+ * Previous versions would create a directory that is more accessible, as discussed in <a
+ * href="https://github.com/google/guava/issues/4011">CVE-2020-8908</a>.)
+ *
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
- * <p>Depending on the environmment that this code is run in, the system temporary directory (and
- * thus the directory this method creates) may be more visible that a program would like - files
- * written to this directory may be read or overwritten by hostile programs running on the same
- * machine.
- *
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
@@ -412,36 +416,26 @@ public final class Files {
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
- * @throws IllegalStateException if the directory could not be created
+ * @throws IllegalStateException if the directory could not be created, such as if the system does
+ * not support creating temporary directories securely
* @deprecated For Android users, see the <a
* href="https://developer.android.com/training/data-storage" target="_blank">Data and File
* Storage overview</a> to select an appropriate temporary directory (perhaps {@code
- * context.getCacheDir()}). For developers on Java 7 or later, use {@link
- * java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using {@link
- * java.nio.file.Path#toFile() toFile()} if needed.
+ * context.getCacheDir()}), and create your own directory under that. (For example, you might
+ * use {@code new File(context.getCacheDir(), "directoryname").mkdir()}, or, if you need an
+ * arbitrary number of temporary directories, you might have to generate multiple directory
+ * names in a loop until {@code mkdir()} returns {@code true}.) For developers on Java 7 or
+ * later, use {@link java.nio.file.Files#createTempDirectory}, transforming it to a {@link
+ * File} using {@link java.nio.file.Path#toFile() toFile()} if needed. To restrict permissions
+ * as this method does, pass {@code
+ * PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))} to your
+ * call to {@code createTempDirectory}.
*/
@Beta
@Deprecated
+ @J2ObjCIncompatible
public static File createTempDir() {
- File baseDir = new File(System.getProperty("java.io.tmpdir"));
- @SuppressWarnings("GoodTime") // reading system time without TimeSource
- String baseName = System.currentTimeMillis() + "-";
-
- for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
- File tempDir = new File(baseDir, baseName + counter);
- if (tempDir.mkdir()) {
- return tempDir;
- }
- }
- throw new IllegalStateException(
- "Failed to create directory within "
- + TEMP_DIR_ATTEMPTS
- + " attempts (tried "
- + baseName
- + "0 to "
- + baseName
- + (TEMP_DIR_ATTEMPTS - 1)
- + ')');
+ return TempFileCreator.INSTANCE.createTempDir();
}
/**
@@ -847,7 +841,6 @@ public final class Files {
*
* @since 23.5
*/
- @Beta
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
diff --git a/android/guava/src/com/google/common/io/Flushables.java b/android/guava/src/com/google/common/io/Flushables.java
index 1f795a24a..4a42e4a40 100644
--- a/android/guava/src/com/google/common/io/Flushables.java
+++ b/android/guava/src/com/google/common/io/Flushables.java
@@ -16,6 +16,7 @@ package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Flushable;
import java.io.IOException;
import java.util.logging.Level;
@@ -27,7 +28,7 @@ import java.util.logging.Logger;
* @author Michael Lancaster
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Flushables {
@@ -66,6 +67,7 @@ public final class Flushables {
*
* @param flushable the {@code Flushable} object to be flushed.
*/
+ @Beta
public static void flushQuietly(Flushable flushable) {
try {
flush(flushable, true);
diff --git a/android/guava/src/com/google/common/primitives/Platform.java b/android/guava/src/com/google/common/io/IgnoreJRERequirement.java
index 83b248517..b1b8e1032 100644
--- a/android/guava/src/com/google/common/primitives/Platform.java
+++ b/android/guava/src/com/google/common/io/IgnoreJRERequirement.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Guava Authors
+ * Copyright 2019 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
@@ -12,15 +12,19 @@
* the License.
*/
-package com.google.common.primitives;
+package com.google.common.io;
-import com.google.common.annotations.GwtCompatible;
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
-/** Methods factored out so that they can be emulated differently in GWT. */
-@GwtCompatible(emulated = true)
-@ElementTypesAreNonnullByDefault
-final class Platform {
- static void checkGwtRpcEnabled() {}
+import java.lang.annotation.Target;
- private Platform() {}
-}
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/android/guava/src/com/google/common/io/Java8Compatibility.java b/android/guava/src/com/google/common/io/Java8Compatibility.java
index 705d97b4d..bd3e6e055 100644
--- a/android/guava/src/com/google/common/io/Java8Compatibility.java
+++ b/android/guava/src/com/google/common/io/Java8Compatibility.java
@@ -15,12 +15,14 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.Buffer;
/**
* Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
* https://github.com/google/guava/issues/3990
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
diff --git a/android/guava/src/com/google/common/io/LineBuffer.java b/android/guava/src/com/google/common/io/LineBuffer.java
index f944abc49..201dfd616 100644
--- a/android/guava/src/com/google/common/io/LineBuffer.java
+++ b/android/guava/src/com/google/common/io/LineBuffer.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -29,6 +30,7 @@ import java.io.IOException;
* @author Chris Nokleberg
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class LineBuffer {
diff --git a/android/guava/src/com/google/common/io/LineProcessor.java b/android/guava/src/com/google/common/io/LineProcessor.java
index e28bebcc5..c0e08fa11 100644
--- a/android/guava/src/com/google/common/io/LineProcessor.java
+++ b/android/guava/src/com/google/common/io/LineProcessor.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -29,7 +29,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Miles Barr
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface LineProcessor<T extends @Nullable Object> {
diff --git a/android/guava/src/com/google/common/io/LineReader.java b/android/guava/src/com/google/common/io/LineReader.java
index 2c57ac454..54bf04c7c 100644
--- a/android/guava/src/com/google/common/io/LineReader.java
+++ b/android/guava/src/com/google/common/io/LineReader.java
@@ -17,8 +17,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.CharStreams.createBuffer;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.Reader;
@@ -35,7 +35,7 @@ import javax.annotation.CheckForNull;
* @author Chris Nokleberg
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class LineReader {
diff --git a/android/guava/src/com/google/common/io/LittleEndianDataInputStream.java b/android/guava/src/com/google/common/io/LittleEndianDataInputStream.java
index 88c8e27bc..54b1b14e8 100644
--- a/android/guava/src/com/google/common/io/LittleEndianDataInputStream.java
+++ b/android/guava/src/com/google/common/io/LittleEndianDataInputStream.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
@@ -39,7 +39,7 @@ import java.io.InputStream;
* @author Keith Bottner
* @since 8.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class LittleEndianDataInputStream extends FilterInputStream implements DataInput {
diff --git a/android/guava/src/com/google/common/io/LittleEndianDataOutputStream.java b/android/guava/src/com/google/common/io/LittleEndianDataOutputStream.java
index 6e51aff49..5d534f61c 100644
--- a/android/guava/src/com/google/common/io/LittleEndianDataOutputStream.java
+++ b/android/guava/src/com/google/common/io/LittleEndianDataOutputStream.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import java.io.DataOutput;
@@ -35,7 +35,7 @@ import java.io.OutputStream;
* @author Keith Bottner
* @since 8.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class LittleEndianDataOutputStream extends FilterOutputStream implements DataOutput {
diff --git a/android/guava/src/com/google/common/io/MultiInputStream.java b/android/guava/src/com/google/common/io/MultiInputStream.java
index 9a7e0fd1c..068baf679 100644
--- a/android/guava/src/com/google/common/io/MultiInputStream.java
+++ b/android/guava/src/com/google/common/io/MultiInputStream.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
@@ -29,6 +30,7 @@ import javax.annotation.CheckForNull;
* @author Chris Nokleberg
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class MultiInputStream extends InputStream {
diff --git a/android/guava/src/com/google/common/io/MultiReader.java b/android/guava/src/com/google/common/io/MultiReader.java
index cc36e527b..9e3a7eccb 100644
--- a/android/guava/src/com/google/common/io/MultiReader.java
+++ b/android/guava/src/com/google/common/io/MultiReader.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Reader;
@@ -29,6 +30,7 @@ import javax.annotation.CheckForNull;
* @author Bin Zhu
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
class MultiReader extends Reader {
diff --git a/android/guava/src/com/google/common/io/ParametricNullness.java b/android/guava/src/com/google/common/io/ParametricNullness.java
index 98da76585..881c07d49 100644
--- a/android/guava/src/com/google/common/io/ParametricNullness.java
+++ b/android/guava/src/com/google/common/io/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/io/PatternFilenameFilter.java b/android/guava/src/com/google/common/io/PatternFilenameFilter.java
index 3cb2371e2..ee0a0bda2 100644
--- a/android/guava/src/com/google/common/io/PatternFilenameFilter.java
+++ b/android/guava/src/com/google/common/io/PatternFilenameFilter.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FilenameFilter;
@@ -29,7 +29,7 @@ import java.util.regex.PatternSyntaxException;
* @author Apple Chow
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class PatternFilenameFilter implements FilenameFilter {
diff --git a/android/guava/src/com/google/common/io/ReaderInputStream.java b/android/guava/src/com/google/common/io/ReaderInputStream.java
index 75f8a3e1e..af84686ec 100644
--- a/android/guava/src/com/google/common/io/ReaderInputStream.java
+++ b/android/guava/src/com/google/common/io/ReaderInputStream.java
@@ -19,6 +19,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.UnsignedBytes;
import java.io.IOException;
import java.io.InputStream;
@@ -43,6 +44,7 @@ import java.util.Arrays;
*
* @author Chris Nokleberg
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class ReaderInputStream extends InputStream {
@@ -198,8 +200,8 @@ final class ReaderInputStream extends InputStream {
/** Handle the case of underflow caused by needing more input characters. */
private void readMoreChars() throws IOException {
// Possibilities:
- // 1) array has space available on right hand side (between limit and capacity)
- // 2) array has space available on left hand side (before position)
+ // 1) array has space available on right-hand side (between limit and capacity)
+ // 2) array has space available on left-hand side (before position)
// 3) array has no space available
//
// In case 2 we shift the existing chars to the left, and in case 3 we create a bigger
diff --git a/android/guava/src/com/google/common/io/Resources.java b/android/guava/src/com/google/common/io/Resources.java
index d1e37070a..aedf3ade2 100644
--- a/android/guava/src/com/google/common/io/Resources.java
+++ b/android/guava/src/com/google/common/io/Resources.java
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
@@ -40,6 +41,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Resources {
diff --git a/android/guava/src/com/google/common/io/TempFileCreator.java b/android/guava/src/com/google/common/io/TempFileCreator.java
new file mode 100644
index 000000000..966323599
--- /dev/null
+++ b/android/guava/src/com/google/common/io/TempFileCreator.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright (C) 2007 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.io;
+
+import static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR;
+import static com.google.common.base.StandardSystemProperty.USER_NAME;
+import static java.nio.file.attribute.AclEntryFlag.DIRECTORY_INHERIT;
+import static java.nio.file.attribute.AclEntryFlag.FILE_INHERIT;
+import static java.nio.file.attribute.AclEntryType.ALLOW;
+import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;
+
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import com.google.common.collect.ImmutableList;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Paths;
+import java.nio.file.attribute.AclEntry;
+import java.nio.file.attribute.AclEntryPermission;
+import java.nio.file.attribute.FileAttribute;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.nio.file.attribute.UserPrincipal;
+import java.util.EnumSet;
+import java.util.Set;
+
+/**
+ * Creates temporary files and directories whose permissions are restricted to the current user or,
+ * in the case of Android, the current app. If that is not possible (as is the case under the very
+ * old Android Ice Cream Sandwich release), then this class throws an exception instead of creating
+ * a file or directory that would be more accessible.
+ */
+@J2ktIncompatible
+@GwtIncompatible
+@J2ObjCIncompatible
+@ElementTypesAreNonnullByDefault
+abstract class TempFileCreator {
+ static final TempFileCreator INSTANCE = pickSecureCreator();
+
+ /**
+ * @throws IllegalStateException if the directory could not be created (to implement the contract
+ * of {@link Files#createTempDir()}, such as if the system does not support creating temporary
+ * directories securely
+ */
+ abstract File createTempDir();
+
+ abstract File createTempFile(String prefix) throws IOException;
+
+ private static TempFileCreator pickSecureCreator() {
+ try {
+ Class.forName("java.nio.file.Path");
+ return new JavaNioCreator();
+ } catch (ClassNotFoundException runningUnderAndroid) {
+ // Try another way.
+ }
+
+ try {
+ int version = (int) Class.forName("android.os.Build$VERSION").getField("SDK_INT").get(null);
+ int jellyBean =
+ (int) Class.forName("android.os.Build$VERSION_CODES").getField("JELLY_BEAN").get(null);
+ /*
+ * I assume that this check can't fail because JELLY_BEAN will be present only if we're
+ * running under Jelly Bean or higher. But it seems safest to check.
+ */
+ if (version < jellyBean) {
+ return new ThrowingCreator();
+ }
+
+ // Don't merge these catch() blocks, let alone use ReflectiveOperationException directly:
+ // b/65343391
+ } catch (NoSuchFieldException e) {
+ // The JELLY_BEAN field doesn't exist because we're running on a version before Jelly Bean :)
+ return new ThrowingCreator();
+ } catch (ClassNotFoundException e) {
+ // Should be impossible, but we want to return *something* so that class init succeeds.
+ return new ThrowingCreator();
+ } catch (IllegalAccessException e) {
+ // ditto
+ return new ThrowingCreator();
+ }
+
+ // Android isolates apps' temporary directories since Jelly Bean:
+ // https://github.com/google/guava/issues/4011#issuecomment-770020802
+ // So we can create files there with any permissions and still get security from the isolation.
+ return new JavaIoCreator();
+ }
+
+ @IgnoreJRERequirement // used only when Path is available
+ private static final class JavaNioCreator extends TempFileCreator {
+ @Override
+ File createTempDir() {
+ try {
+ return java.nio.file.Files.createTempDirectory(
+ Paths.get(JAVA_IO_TMPDIR.value()), /* prefix= */ null, directoryPermissions.get())
+ .toFile();
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to create directory", e);
+ }
+ }
+
+ @Override
+ File createTempFile(String prefix) throws IOException {
+ return java.nio.file.Files.createTempFile(
+ Paths.get(JAVA_IO_TMPDIR.value()),
+ /* prefix= */ prefix,
+ /* suffix= */ null,
+ filePermissions.get())
+ .toFile();
+ }
+
+ @IgnoreJRERequirement // see enclosing class (whose annotation Animal Sniffer ignores here...)
+ private interface PermissionSupplier {
+ FileAttribute<?> get() throws IOException;
+ }
+
+ private static final PermissionSupplier filePermissions;
+ private static final PermissionSupplier directoryPermissions;
+
+ static {
+ Set<String> views = FileSystems.getDefault().supportedFileAttributeViews();
+ if (views.contains("posix")) {
+ filePermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rw-------"));
+ directoryPermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rwx------"));
+ } else if (views.contains("acl")) {
+ filePermissions = directoryPermissions = userPermissions();
+ } else {
+ filePermissions =
+ directoryPermissions =
+ () -> {
+ throw new IOException("unrecognized FileSystem type " + FileSystems.getDefault());
+ };
+ }
+ }
+
+ private static PermissionSupplier userPermissions() {
+ try {
+ UserPrincipal user =
+ FileSystems.getDefault()
+ .getUserPrincipalLookupService()
+ .lookupPrincipalByName(USER_NAME.value());
+ ImmutableList<AclEntry> acl =
+ ImmutableList.of(
+ AclEntry.newBuilder()
+ .setType(ALLOW)
+ .setPrincipal(user)
+ .setPermissions(EnumSet.allOf(AclEntryPermission.class))
+ .setFlags(DIRECTORY_INHERIT, FILE_INHERIT)
+ .build());
+ FileAttribute<ImmutableList<AclEntry>> attribute =
+ new FileAttribute<ImmutableList<AclEntry>>() {
+ @Override
+ public String name() {
+ return "acl:acl";
+ }
+
+ @Override
+ public ImmutableList<AclEntry> value() {
+ return acl;
+ }
+ };
+ return () -> attribute;
+ } catch (IOException e) {
+ // We throw a new exception each time so that the stack trace is right.
+ return () -> {
+ throw new IOException("Could not find user", e);
+ };
+ }
+ }
+ }
+
+ private static final class JavaIoCreator extends TempFileCreator {
+ @Override
+ File createTempDir() {
+ File baseDir = new File(JAVA_IO_TMPDIR.value());
+ @SuppressWarnings("GoodTime") // reading system time without TimeSource
+ String baseName = System.currentTimeMillis() + "-";
+
+ for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
+ File tempDir = new File(baseDir, baseName + counter);
+ if (tempDir.mkdir()) {
+ return tempDir;
+ }
+ }
+ throw new IllegalStateException(
+ "Failed to create directory within "
+ + TEMP_DIR_ATTEMPTS
+ + " attempts (tried "
+ + baseName
+ + "0 to "
+ + baseName
+ + (TEMP_DIR_ATTEMPTS - 1)
+ + ')');
+ }
+
+ @Override
+ File createTempFile(String prefix) throws IOException {
+ return File.createTempFile(
+ /* prefix= */ prefix,
+ /* suffix= */ null,
+ /* directory= */ null /* defaults to java.io.tmpdir */);
+ }
+
+ /** Maximum loop count when creating temp directories. */
+ private static final int TEMP_DIR_ATTEMPTS = 10000;
+ }
+
+ private static final class ThrowingCreator extends TempFileCreator {
+ private static final String MESSAGE =
+ "Guava cannot securely create temporary files or directories under SDK versions before"
+ + " Jelly Bean. You can create one yourself, either in the insecure default directory"
+ + " or in a more secure directory, such as context.getCacheDir(). For more information,"
+ + " see the Javadoc for Files.createTempDir().";
+
+ @Override
+ File createTempDir() {
+ throw new IllegalStateException(MESSAGE);
+ }
+
+ @Override
+ File createTempFile(String prefix) throws IOException {
+ throw new IOException(MESSAGE);
+ }
+ }
+
+ private TempFileCreator() {}
+}
diff --git a/android/guava/src/com/google/common/io/package-info.java b/android/guava/src/com/google/common/io/package-info.java
index f0666b26f..e4eebbd0d 100644
--- a/android/guava/src/com/google/common/io/package-info.java
+++ b/android/guava/src/com/google/common/io/package-info.java
@@ -13,16 +13,15 @@
*/
/**
- * This package contains utility methods and classes for working with Java I/O; for example input
- * streams, output streams, readers, writers, and files.
+ * Utility methods and classes for I/O; for example input streams, output streams, readers, writers,
+ * and files.
*
- * <p>At the core of this package are the Source/Sink types: {@link com.google.common.io.ByteSource
- * ByteSource}, {@link com.google.common.io.CharSource CharSource}, {@link
- * com.google.common.io.ByteSink ByteSink} and {@link com.google.common.io.CharSink CharSink}. They
- * are factories for I/O streams that provide many convenience methods that handle both opening and
+ * <p>At the core of this package are the Source/Sink types: {@link ByteSource ByteSource}, {@link
+ * CharSource CharSource}, {@link ByteSink ByteSink} and {@link CharSink CharSink}. They are
+ * factories for I/O streams that provide many convenience methods that handle both opening and
* closing streams for you.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library. For more information on Sources and Sinks as well as other features of this package, see
* <a href="https://github.com/google/guava/wiki/IOExplained">I/O Explained</a> on the Guava wiki.
*
diff --git a/android/guava/src/com/google/common/math/BigDecimalMath.java b/android/guava/src/com/google/common/math/BigDecimalMath.java
index 33a55d356..d70940479 100644
--- a/android/guava/src/com/google/common/math/BigDecimalMath.java
+++ b/android/guava/src/com/google/common/math/BigDecimalMath.java
@@ -15,6 +15,7 @@
package com.google.common.math;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -24,6 +25,7 @@ import java.math.RoundingMode;
* @author Louis Wasserman
* @since 30.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class BigDecimalMath {
diff --git a/android/guava/src/com/google/common/math/BigIntegerMath.java b/android/guava/src/com/google/common/math/BigIntegerMath.java
index 6ef1e81ed..cf943195d 100644
--- a/android/guava/src/com/google/common/math/BigIntegerMath.java
+++ b/android/guava/src/com/google/common/math/BigIntegerMath.java
@@ -25,9 +25,9 @@ import static java.math.RoundingMode.HALF_DOWN;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.UNNECESSARY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -57,7 +57,6 @@ public final class BigIntegerMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static BigInteger ceilingPowerOfTwo(BigInteger x) {
return BigInteger.ZERO.setBit(log2(x, CEILING));
}
@@ -69,7 +68,6 @@ public final class BigIntegerMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static BigInteger floorPowerOfTwo(BigInteger x) {
return BigInteger.ZERO.setBit(log2(x, FLOOR));
}
@@ -146,6 +144,7 @@ public final class BigIntegerMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static int log10(BigInteger x, RoundingMode mode) {
@@ -224,6 +223,7 @@ public final class BigIntegerMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
* sqrt(x)} is not an integer
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
@@ -260,6 +260,7 @@ public final class BigIntegerMath {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static BigInteger sqrtFloor(BigInteger x) {
/*
@@ -304,6 +305,7 @@ public final class BigIntegerMath {
return sqrt0;
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static BigInteger sqrtApproxWithDoubles(BigInteger x) {
return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN);
@@ -330,11 +332,13 @@ public final class BigIntegerMath {
* is not precisely representable as a {@code double}
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible
public static double roundToDouble(BigInteger x, RoundingMode mode) {
return BigIntegerToDoubleRounder.INSTANCE.roundToDouble(x, mode);
}
+ @J2ktIncompatible
@GwtIncompatible
private static class BigIntegerToDoubleRounder extends ToDoubleRounder<BigInteger> {
static final BigIntegerToDoubleRounder INSTANCE = new BigIntegerToDoubleRounder();
@@ -369,6 +373,7 @@ public final class BigIntegerMath {
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) {
BigDecimal pDec = new BigDecimal(p);
@@ -521,6 +526,7 @@ public final class BigIntegerMath {
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
+ @J2ktIncompatible
@GwtIncompatible // TODO
static boolean fitsInLong(BigInteger x) {
return x.bitLength() <= Long.SIZE - 1;
diff --git a/android/guava/src/com/google/common/math/DoubleMath.java b/android/guava/src/com/google/common/math/DoubleMath.java
index cdd0a4b39..36de5378f 100644
--- a/android/guava/src/com/google/common/math/DoubleMath.java
+++ b/android/guava/src/com/google/common/math/DoubleMath.java
@@ -32,6 +32,7 @@ import static java.lang.Math.rint;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Booleans;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -52,6 +53,7 @@ public final class DoubleMath {
* This method returns a value y such that rounding y DOWN (towards zero) gives the same result as
* rounding x according to the specified mode.
*/
+ @J2ktIncompatible
@GwtIncompatible // #isMathematicalInteger, com.google.common.math.DoubleUtils
static double roundIntermediate(double x, RoundingMode mode) {
if (!isFinite(x)) {
@@ -128,6 +130,7 @@ public final class DoubleMath {
* RoundingMode#UNNECESSARY}
* </ul>
*/
+ @J2ktIncompatible
@GwtIncompatible // #roundIntermediate
public static int roundToInt(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
@@ -153,6 +156,7 @@ public final class DoubleMath {
* RoundingMode#UNNECESSARY}
* </ul>
*/
+ @J2ktIncompatible
@GwtIncompatible // #roundIntermediate
public static long roundToLong(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
@@ -180,6 +184,7 @@ public final class DoubleMath {
* </ul>
*/
// #roundIntermediate, java.lang.Math.getExponent, com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static BigInteger roundToBigInteger(double x, RoundingMode mode) {
x = roundIntermediate(x, mode);
@@ -196,6 +201,7 @@ public final class DoubleMath {
* Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer
* {@code k}.
*/
+ @J2ktIncompatible
@GwtIncompatible // com.google.common.math.DoubleUtils
public static boolean isPowerOfTwo(double x) {
if (x > 0.0 && isFinite(x)) {
@@ -234,6 +240,7 @@ public final class DoubleMath {
* @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is
* infinite
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.Math.getExponent, com.google.common.math.DoubleUtils
@SuppressWarnings("fallthrough")
public static int log2(double x, RoundingMode mode) {
@@ -404,6 +411,7 @@ public final class DoubleMath {
*/
@Deprecated
// com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static double mean(double... values) {
checkArgument(values.length > 0, "Cannot take mean of 0 values");
@@ -484,6 +492,7 @@ public final class DoubleMath {
*/
@Deprecated
// com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static double mean(Iterable<? extends Number> values) {
return mean(values.iterator());
@@ -504,6 +513,7 @@ public final class DoubleMath {
*/
@Deprecated
// com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static double mean(Iterator<? extends Number> values) {
checkArgument(values.hasNext(), "Cannot take mean of 0 values");
@@ -518,6 +528,7 @@ public final class DoubleMath {
return mean;
}
+ @J2ktIncompatible
@GwtIncompatible // com.google.common.math.DoubleUtils
@CanIgnoreReturnValue
private static double checkFinite(double argument) {
diff --git a/android/guava/src/com/google/common/math/IntMath.java b/android/guava/src/com/google/common/math/IntMath.java
index 17a18c699..3fff5793c 100644
--- a/android/guava/src/com/google/common/math/IntMath.java
+++ b/android/guava/src/com/google/common/math/IntMath.java
@@ -25,9 +25,9 @@ import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.math.BigInteger;
@@ -63,7 +63,6 @@ public final class IntMath {
* int}, i.e. when {@code x > 2^30}
* @since 20.0
*/
- @Beta
public static int ceilingPowerOfTwo(int x) {
checkPositive("x", x);
if (x > MAX_SIGNED_POWER_OF_TWO) {
@@ -79,7 +78,6 @@ public final class IntMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static int floorPowerOfTwo(int x) {
checkPositive("x", x);
return Integer.highestOneBit(x);
@@ -155,6 +153,7 @@ public final class IntMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
+ @J2ktIncompatible
@GwtIncompatible // need BigIntegerMath to adequately test
@SuppressWarnings("fallthrough")
public static int log10(int x, RoundingMode mode) {
@@ -224,6 +223,7 @@ public final class IntMath {
*
* @throws IllegalArgumentException if {@code k < 0}
*/
+ @J2ktIncompatible
@GwtIncompatible // failing tests
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
@@ -532,7 +532,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedAdd(int a, int b) {
return Ints.saturatedCast((long) a + b);
}
@@ -543,7 +542,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedSubtract(int a, int b) {
return Ints.saturatedCast((long) a - b);
}
@@ -554,7 +552,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedMultiply(int a, int b) {
return Ints.saturatedCast((long) a * b);
}
@@ -565,7 +562,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
@@ -719,8 +715,8 @@ public final class IntMath {
* @throws IllegalArgumentException if {@code n} is negative
* @since 20.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
- @Beta
public static boolean isPrime(int n) {
return LongMath.isPrime(n);
}
diff --git a/android/guava/src/com/google/common/math/LinearTransformation.java b/android/guava/src/com/google/common/math/LinearTransformation.java
index 4cc1eb87d..51d3f32a3 100644
--- a/android/guava/src/com/google/common/math/LinearTransformation.java
+++ b/android/guava/src/com/google/common/math/LinearTransformation.java
@@ -18,8 +18,8 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.DoubleUtils.isFinite;
import static java.lang.Double.NaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
import javax.annotation.CheckForNull;
@@ -34,7 +34,7 @@ import javax.annotation.CheckForNull;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class LinearTransformation {
diff --git a/android/guava/src/com/google/common/math/LongMath.java b/android/guava/src/com/google/common/math/LongMath.java
index dd5ff0694..fa8271a1e 100644
--- a/android/guava/src/com/google/common/math/LongMath.java
+++ b/android/guava/src/com/google/common/math/LongMath.java
@@ -25,9 +25,9 @@ import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Longs;
import com.google.common.primitives.UnsignedLongs;
@@ -64,7 +64,6 @@ public final class LongMath {
* long}, i.e. when {@code x > 2^62}
* @since 20.0
*/
- @Beta
public static long ceilingPowerOfTwo(long x) {
checkPositive("x", x);
if (x > MAX_SIGNED_POWER_OF_TWO) {
@@ -80,7 +79,6 @@ public final class LongMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static long floorPowerOfTwo(long x) {
checkPositive("x", x);
@@ -95,6 +93,7 @@ public final class LongMath {
* <p>This differs from {@code Long.bitCount(x) == 1}, because {@code
* Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
*/
+ @SuppressWarnings("ShortCircuitBoolean")
public static boolean isPowerOfTwo(long x) {
return x > 0 & (x & (x - 1)) == 0;
}
@@ -142,10 +141,8 @@ public final class LongMath {
// floor(2^(logFloor + 0.5))
int logFloor = (Long.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
-
- default:
- throw new AssertionError("impossible");
}
+ throw new AssertionError("impossible");
}
/** The biggest half power of two that fits into an unsigned long */
@@ -158,6 +155,7 @@ public final class LongMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
@@ -180,11 +178,11 @@ public final class LongMath {
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
- default:
- throw new AssertionError();
}
+ throw new AssertionError();
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
static int log10Floor(long x) {
/*
@@ -210,6 +208,7 @@ public final class LongMath {
3, 2, 2, 2, 1, 1, 1, 0, 0, 0
};
+ @J2ktIncompatible
@GwtIncompatible // TODO
@VisibleForTesting
static final long[] powersOf10 = {
@@ -235,6 +234,7 @@ public final class LongMath {
};
// halfPowersOf10[i] = largest long less than 10^(i + 0.5)
+ @J2ktIncompatible
@GwtIncompatible // TODO
@VisibleForTesting
static final long[] halfPowersOf10 = {
@@ -266,6 +266,7 @@ public final class LongMath {
*
* @throws IllegalArgumentException if {@code k < 0}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static long pow(long b, int k) {
checkNonNegative("exponent", k);
@@ -309,8 +310,8 @@ public final class LongMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
* sqrt(x)} is not an integer
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
- @SuppressWarnings("fallthrough")
public static long sqrt(long x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInInt(x)) {
@@ -331,7 +332,7 @@ public final class LongMath {
* since (long) Math.sqrt(k * k) == k, as checked exhaustively in
* {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect}
*/
- long guess = (long) Math.sqrt(x);
+ long guess = (long) Math.sqrt((double) x);
// Note: guess is always <= FLOOR_SQRT_MAX_LONG.
long guessSquared = guess * guess;
// Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is
@@ -369,9 +370,8 @@ public final class LongMath {
* signed long, so lessThanBranchFree is safe for use.
*/
return sqrtFloor + lessThanBranchFree(halfSquare, x);
- default:
- throw new AssertionError();
}
+ throw new AssertionError();
}
/**
@@ -381,6 +381,7 @@ public final class LongMath {
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static long divide(long p, long q, RoundingMode mode) {
@@ -454,6 +455,7 @@ public final class LongMath {
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
* Remainder Operator</a>
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static int mod(long x, int m) {
// Cast is safe because the result is guaranteed in the range [0, m)
@@ -478,6 +480,7 @@ public final class LongMath {
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
* Remainder Operator</a>
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static long mod(long x, long m) {
if (m <= 0) {
@@ -543,7 +546,7 @@ public final class LongMath {
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
*/
- @GwtIncompatible // TODO
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedAdd(long a, long b) {
long result = a + b;
checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0, "checkedAdd", a, b);
@@ -555,7 +558,9 @@ public final class LongMath {
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedSubtract(long a, long b) {
long result = a - b;
checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0, "checkedSubtract", a, b);
@@ -567,6 +572,7 @@ public final class LongMath {
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
*/
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedMultiply(long a, long b) {
// Hacker's Delight, Section 2-12
int leadingZeros =
@@ -600,7 +606,9 @@ public final class LongMath {
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code
* long} arithmetic
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedPow(long b, int k) {
checkNonNegative("exponent", k);
if (b >= -2 & b <= 2) {
@@ -648,7 +656,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedAdd(long a, long b) {
long naiveSum = a + b;
if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) {
@@ -666,7 +674,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedSubtract(long a, long b) {
long naiveDifference = a - b;
if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) {
@@ -684,7 +692,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedMultiply(long a, long b) {
// see checkedMultiply for explanation
int leadingZeros =
@@ -714,7 +722,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedPow(long b, int k) {
checkNonNegative("exponent", k);
if (b >= -2 & b <= 2) {
@@ -741,7 +749,7 @@ public final class LongMath {
}
long accum = 1;
// if b is negative and k is odd then the limit is MIN otherwise the limit is MAX
- long limit = Long.MAX_VALUE + ((b >>> Long.SIZE - 1) & (k & 1));
+ long limit = Long.MAX_VALUE + ((b >>> (Long.SIZE - 1)) & (k & 1));
while (true) {
switch (k) {
case 0:
@@ -771,6 +779,7 @@ public final class LongMath {
*
* @throws IllegalArgumentException if {@code n < 0}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static long factorial(int n) {
checkNonNegative("n", n);
@@ -979,7 +988,7 @@ public final class LongMath {
}
/*
- * This bitmask is used as an optimization for cheaply testing for divisiblity by 2, 3, or 5.
+ * This bitmask is used as an optimization for cheaply testing for divisibility by 2, 3, or 5.
* Each bit is set to 1 for all remainders that indicate divisibility by 2, 3, or 5, so
* 1, 7, 11, 13, 17, 19, 23, 29 are set to 0. 30 and up don't matter because they won't be hit.
*/
@@ -999,8 +1008,8 @@ public final class LongMath {
* @throws IllegalArgumentException if {@code n} is negative
* @since 20.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
- @Beta
public static boolean isPrime(long n) {
if (n < 2) {
checkNonNegative("n", n);
@@ -1116,7 +1125,7 @@ public final class LongMath {
private long times2ToThe32Mod(long a, long m) {
int remainingPowersOf2 = 32;
do {
- int shift = Math.min(remainingPowersOf2, Long.numberOfLeadingZeros(a));
+ int shift = min(remainingPowersOf2, Long.numberOfLeadingZeros(a));
// shift is either the number of powers of 2 left to multiply a by, or the biggest shift
// possible while keeping a in an unsigned long.
a = UnsignedLongs.remainder(a << shift, m);
@@ -1243,6 +1252,7 @@ public final class LongMath {
* @since 30.0
*/
@SuppressWarnings("deprecation")
+ @J2ktIncompatible
@GwtIncompatible
public static double roundToDouble(long x, RoundingMode mode) {
// Logic adapted from ToDoubleRounder.
diff --git a/android/guava/src/com/google/common/math/MathPreconditions.java b/android/guava/src/com/google/common/math/MathPreconditions.java
index 37d608a82..d8b7b10bf 100644
--- a/android/guava/src/com/google/common/math/MathPreconditions.java
+++ b/android/guava/src/com/google/common/math/MathPreconditions.java
@@ -25,9 +25,9 @@ import java.math.RoundingMode;
* @author Louis Wasserman
*/
@GwtCompatible
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
final class MathPreconditions {
+ @CanIgnoreReturnValue
static int checkPositive(String role, int x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
@@ -35,6 +35,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static long checkPositive(String role, long x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
@@ -42,6 +43,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static BigInteger checkPositive(String role, BigInteger x) {
if (x.signum() <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
@@ -49,6 +51,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static int checkNonNegative(String role, int x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
@@ -56,6 +59,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static long checkNonNegative(String role, long x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
@@ -63,6 +67,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static BigInteger checkNonNegative(String role, BigInteger x) {
if (x.signum() < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
@@ -70,6 +75,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static double checkNonNegative(String role, double x) {
if (!(x >= 0)) { // not x < 0, to work with NaN.
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
diff --git a/android/guava/src/com/google/common/math/PairedStats.java b/android/guava/src/com/google/common/math/PairedStats.java
index 31ab9b719..c60a62b0a 100644
--- a/android/guava/src/com/google/common/math/PairedStats.java
+++ b/android/guava/src/com/google/common/math/PairedStats.java
@@ -21,8 +21,8 @@ import static java.lang.Double.NaN;
import static java.lang.Double.doubleToLongBits;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.io.Serializable;
@@ -37,7 +37,7 @@ import javax.annotation.CheckForNull;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class PairedStats implements Serializable {
diff --git a/android/guava/src/com/google/common/math/PairedStatsAccumulator.java b/android/guava/src/com/google/common/math/PairedStatsAccumulator.java
index 072ef13b3..9d365633a 100644
--- a/android/guava/src/com/google/common/math/PairedStatsAccumulator.java
+++ b/android/guava/src/com/google/common/math/PairedStatsAccumulator.java
@@ -19,8 +19,8 @@ import static com.google.common.primitives.Doubles.isFinite;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Doubles;
/**
@@ -30,7 +30,7 @@ import com.google.common.primitives.Doubles;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class PairedStatsAccumulator {
diff --git a/android/guava/src/com/google/common/math/ParametricNullness.java b/android/guava/src/com/google/common/math/ParametricNullness.java
index 8e57826e4..612fa934a 100644
--- a/android/guava/src/com/google/common/math/ParametricNullness.java
+++ b/android/guava/src/com/google/common/math/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/math/Quantiles.java b/android/guava/src/com/google/common/math/Quantiles.java
index 6ddea9bcf..78f310dd0 100644
--- a/android/guava/src/com/google/common/math/Quantiles.java
+++ b/android/guava/src/com/google/common/math/Quantiles.java
@@ -21,8 +21,8 @@ import static java.lang.Double.POSITIVE_INFINITY;
import static java.util.Arrays.sort;
import static java.util.Collections.unmodifiableMap;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Ints;
import java.math.RoundingMode;
@@ -126,7 +126,7 @@ import java.util.Map;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Quantiles {
diff --git a/android/guava/src/com/google/common/math/Stats.java b/android/guava/src/com/google/common/math/Stats.java
index c0837496d..0650a87f5 100644
--- a/android/guava/src/com/google/common/math/Stats.java
+++ b/android/guava/src/com/google/common/math/Stats.java
@@ -24,8 +24,8 @@ import static java.lang.Double.NaN;
import static java.lang.Double.doubleToLongBits;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.io.Serializable;
@@ -58,7 +58,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Stats implements Serializable {
@@ -122,9 +122,9 @@ public final class Stats implements Serializable {
* @param values a series of values
*/
public static Stats of(double... values) {
- StatsAccumulator acummulator = new StatsAccumulator();
- acummulator.addAll(values);
- return acummulator.snapshot();
+ StatsAccumulator accumulator = new StatsAccumulator();
+ accumulator.addAll(values);
+ return accumulator.snapshot();
}
/**
@@ -133,9 +133,9 @@ public final class Stats implements Serializable {
* @param values a series of values
*/
public static Stats of(int... values) {
- StatsAccumulator acummulator = new StatsAccumulator();
- acummulator.addAll(values);
- return acummulator.snapshot();
+ StatsAccumulator accumulator = new StatsAccumulator();
+ accumulator.addAll(values);
+ return accumulator.snapshot();
}
/**
@@ -145,9 +145,9 @@ public final class Stats implements Serializable {
* cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15))
*/
public static Stats of(long... values) {
- StatsAccumulator acummulator = new StatsAccumulator();
- acummulator.addAll(values);
- return acummulator.snapshot();
+ StatsAccumulator accumulator = new StatsAccumulator();
+ accumulator.addAll(values);
+ return accumulator.snapshot();
}
/** Returns the number of values. */
diff --git a/android/guava/src/com/google/common/math/StatsAccumulator.java b/android/guava/src/com/google/common/math/StatsAccumulator.java
index f7d7a6290..33406e7f7 100644
--- a/android/guava/src/com/google/common/math/StatsAccumulator.java
+++ b/android/guava/src/com/google/common/math/StatsAccumulator.java
@@ -20,8 +20,8 @@ import static com.google.common.primitives.Doubles.isFinite;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Iterator;
/**
@@ -32,7 +32,7 @@ import java.util.Iterator;
* @author Kevin Bourrillion
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class StatsAccumulator {
diff --git a/android/guava/src/com/google/common/math/ToDoubleRounder.java b/android/guava/src/com/google/common/math/ToDoubleRounder.java
index 2e7e7fae0..5bfcd12ca 100644
--- a/android/guava/src/com/google/common/math/ToDoubleRounder.java
+++ b/android/guava/src/com/google/common/math/ToDoubleRounder.java
@@ -18,12 +18,14 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.math.RoundingMode;
/**
* Helper type to implement rounding {@code X} to a representable {@code double} value according to
* a {@link RoundingMode}.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class ToDoubleRounder<X extends Number & Comparable<X>> {
diff --git a/android/guava/src/com/google/common/math/package-info.java b/android/guava/src/com/google/common/math/package-info.java
index 0408246e7..02580e1a4 100644
--- a/android/guava/src/com/google/common/math/package-info.java
+++ b/android/guava/src/com/google/common/math/package-info.java
@@ -13,9 +13,10 @@
*/
/**
- * Arithmetic functions operating on primitive values and {@link java.math.BigInteger} instances.
+ * Arithmetic functions operating on primitive values and on {@link java.math.BigInteger} and {@link
+ * java.math.BigDecimal} instances.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* <p>See the Guava User Guide article on <a
diff --git a/android/guava/src/com/google/common/net/HostSpecifier.java b/android/guava/src/com/google/common/net/HostSpecifier.java
index c57f3d975..65194112e 100644
--- a/android/guava/src/com/google/common/net/HostSpecifier.java
+++ b/android/guava/src/com/google/common/net/HostSpecifier.java
@@ -15,6 +15,7 @@
package com.google.common.net;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.net.InetAddress;
@@ -41,6 +42,7 @@ import javax.annotation.CheckForNull;
* @author Craig Berry
* @since 5.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class HostSpecifier {
diff --git a/android/guava/src/com/google/common/net/HttpHeaders.java b/android/guava/src/com/google/common/net/HttpHeaders.java
index 2ecbfaa8c..4c1f865b5 100644
--- a/android/guava/src/com/google/common/net/HttpHeaders.java
+++ b/android/guava/src/com/google/common/net/HttpHeaders.java
@@ -317,6 +317,13 @@ public final class HttpHeaders {
*/
public static final String KEEP_ALIVE = "Keep-Alive";
/**
+ * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/no-vary-search.md">{@code
+ * No-Vary-Seearch}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String NO_VARY_SEARCH = "No-Vary-Search";
+ /**
* The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code Origin-Trial}</a>
* header field name.
*
@@ -366,6 +373,16 @@ public final class HttpHeaders {
public static final String SOURCE_MAP = "SourceMap";
/**
+ * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/opt-in.md">{@code
+ * Supports-Loading-Mode}</a> header field name. This can be used to specify, for example, <a
+ * href="https://developer.chrome.com/docs/privacy-sandbox/fenced-frame/#server-opt-in">fenced
+ * frames</a>.
+ *
+ * @since 32.0.0
+ */
+ public static final String SUPPORTS_LOADING_MODE = "Supports-Loading-Mode";
+
+ /**
* The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">{@code
* Strict-Transport-Security}</a> header field name.
*
@@ -690,13 +707,49 @@ public final class HttpHeaders {
*/
public static final String SEC_CH_UA_MOBILE = "Sec-CH-UA-Mobile";
/**
+ * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-wow64">{@code
+ * Sec-CH-UA-WoW64}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_UA_WOW64 = "Sec-CH-UA-WoW64";
+ /**
* The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness">{@code
* Sec-CH-UA-Bitness}</a> header field name.
*
* @since 31.0
*/
public static final String SEC_CH_UA_BITNESS = "Sec-CH-UA-Bitness";
-
+ /**
+ * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factor">{@code
+ * Sec-CH-UA-Form-Factor}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_UA_FORM_FACTOR = "Sec-CH-UA-Form-Factor";
+ /**
+ * The HTTP <a
+ * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-width">{@code
+ * Sec-CH-Viewport-Width}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_VIEWPORT_WIDTH = "Sec-CH-Viewport-Width";
+ /**
+ * The HTTP <a
+ * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-height">{@code
+ * Sec-CH-Viewport-Height}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_VIEWPORT_HEIGHT = "Sec-CH-Viewport-Height";
+ /**
+ * The HTTP <a href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-dpr">{@code
+ * Sec-CH-DPR}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_DPR = "Sec-CH-DPR";
/**
* The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Dest}</a>
* header field name.
@@ -789,6 +842,20 @@ public final class HttpHeaders {
*/
public static final String SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version";
/**
+ * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code
+ * Sec-Browsing-Topics}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_BROWSING_TOPICS = "Sec-Browsing-Topics";
+ /**
+ * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code
+ * Observe-Browsing-Topics}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String OBSERVE_BROWSING_TOPICS = "Observe-Browsing-Topics";
+ /**
* The HTTP <a href="https://tools.ietf.org/html/rfc8586">{@code CDN-Loop}</a> header field name.
*
* @since 28.0
diff --git a/android/guava/src/com/google/common/net/InetAddresses.java b/android/guava/src/com/google/common/net/InetAddresses.java
index d3e68db8a..6d8309381 100644
--- a/android/guava/src/com/google/common/net/InetAddresses.java
+++ b/android/guava/src/com/google/common/net/InetAddresses.java
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.MoreObjects;
import com.google.common.hash.Hashing;
@@ -95,6 +96,7 @@ import javax.annotation.CheckForNull;
* @author Erik Kline
* @since 5.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class InetAddresses {
@@ -522,7 +524,7 @@ public final class InetAddresses {
* want to accept ASCII digits only, you can use something like {@code
* CharMatcher.ascii().matchesAllOf(ipString)}.
*
- * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
+ * @param hostAddr an RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
* @return an InetAddress representing the address in {@code hostAddr}
* @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6
* address surrounded by square brackets
@@ -1026,7 +1028,7 @@ public final class InetAddresses {
/**
* Converts a BigInteger to either an IPv4 or IPv6 address. If the IP is IPv4, it must be
- * constrainted to 32 bits, otherwise it is constrained to 128 bits.
+ * constrained to 32 bits, otherwise it is constrained to 128 bits.
*
* @param address the address represented as a big integer
* @param isIpv6 whether the created address should be IPv4 or IPv6
diff --git a/android/guava/src/com/google/common/net/InternetDomainName.java b/android/guava/src/com/google/common/net/InternetDomainName.java
index d71a9d5c3..d098bf4fb 100644
--- a/android/guava/src/com/google/common/net/InternetDomainName.java
+++ b/android/guava/src/com/google/common/net/InternetDomainName.java
@@ -27,6 +27,7 @@ import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.thirdparty.publicsuffix.PublicSuffixPatterns;
import com.google.thirdparty.publicsuffix.PublicSuffixType;
import java.util.List;
@@ -81,12 +82,18 @@ public final class InternetDomainName {
private static final Joiner DOT_JOINER = Joiner.on('.');
/**
- * Value of {@link #publicSuffixIndex} or {@link #registrySuffixIndex} which indicates that no
+ * Value of {@link #publicSuffixIndex()} or {@link #registrySuffixIndex()} which indicates that no
* relevant suffix was found.
*/
private static final int NO_SUFFIX_FOUND = -1;
/**
+ * Value of {@link #publicSuffixIndexCache} or {@link #registrySuffixIndexCache} which indicates
+ * that they were not initialized yet.
+ */
+ private static final int SUFFIX_NOT_INITIALIZED = -2;
+
+ /**
* Maximum parts (labels) in a domain name. This value arises from the 255-octet limit described
* in <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11 with the fact that the
* encoding of each part occupies at least two bytes (dot plus label externally, length byte plus
@@ -113,20 +120,26 @@ public final class InternetDomainName {
private final ImmutableList<String> parts;
/**
- * The index in the {@link #parts()} list at which the public suffix begins. For example, for the
- * domain name {@code myblog.blogspot.co.uk}, the value would be 1 (the index of the {@code
- * blogspot} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no public
- * suffix was found.
+ * Cached value of #publicSuffixIndex(). Do not use directly.
+ *
+ * <p>Since this field isn't {@code volatile}, if an instance of this class is shared across
+ * threads before it is initialized, then each thread is likely to compute their own copy of the
+ * value.
*/
- private final int publicSuffixIndex;
+ @SuppressWarnings("Immutable")
+ @LazyInit
+ private int publicSuffixIndexCache = SUFFIX_NOT_INITIALIZED;
/**
- * The index in the {@link #parts()} list at which the registry suffix begins. For example, for
- * the domain name {@code myblog.blogspot.co.uk}, the value would be 2 (the index of the {@code
- * co} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no registry suffix
- * was found.
+ * Cached value of #registrySuffixIndex(). Do not use directly.
+ *
+ * <p>Since this field isn't {@code volatile}, if an instance of this class is shared across
+ * threads before it is initialized, then each thread is likely to compute their own copy of the
+ * value.
*/
- private final int registrySuffixIndex;
+ @SuppressWarnings("Immutable")
+ @LazyInit
+ private int registrySuffixIndexCache = SUFFIX_NOT_INITIALIZED;
/** Constructor used to implement {@link #from(String)}, and from subclasses. */
InternetDomainName(String name) {
@@ -147,9 +160,36 @@ public final class InternetDomainName {
this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name));
checkArgument(parts.size() <= MAX_PARTS, "Domain has too many parts: '%s'", name);
checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name);
+ }
- this.publicSuffixIndex = findSuffixOfType(Optional.<PublicSuffixType>absent());
- this.registrySuffixIndex = findSuffixOfType(Optional.of(PublicSuffixType.REGISTRY));
+ /**
+ * The index in the {@link #parts()} list at which the public suffix begins. For example, for the
+ * domain name {@code myblog.blogspot.co.uk}, the value would be 1 (the index of the {@code
+ * blogspot} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no public
+ * suffix was found.
+ */
+ private int publicSuffixIndex() {
+ int publicSuffixIndexLocal = publicSuffixIndexCache;
+ if (publicSuffixIndexLocal == SUFFIX_NOT_INITIALIZED) {
+ publicSuffixIndexCache =
+ publicSuffixIndexLocal = findSuffixOfType(Optional.<PublicSuffixType>absent());
+ }
+ return publicSuffixIndexLocal;
+ }
+
+ /**
+ * The index in the {@link #parts()} list at which the registry suffix begins. For example, for
+ * the domain name {@code myblog.blogspot.co.uk}, the value would be 2 (the index of the {@code
+ * co} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no registry suffix
+ * was found.
+ */
+ private int registrySuffixIndex() {
+ int registrySuffixIndexLocal = registrySuffixIndexCache;
+ if (registrySuffixIndexLocal == SUFFIX_NOT_INITIALIZED) {
+ registrySuffixIndexCache =
+ registrySuffixIndexLocal = findSuffixOfType(Optional.of(PublicSuffixType.REGISTRY));
+ }
+ return registrySuffixIndexLocal;
}
/**
@@ -167,6 +207,12 @@ public final class InternetDomainName {
for (int i = 0; i < partsSize; i++) {
String ancestorName = DOT_JOINER.join(parts.subList(i, partsSize));
+ if (i > 0
+ && matchesType(
+ desiredType, Optional.fromNullable(PublicSuffixPatterns.UNDER.get(ancestorName)))) {
+ return i - 1;
+ }
+
if (matchesType(
desiredType, Optional.fromNullable(PublicSuffixPatterns.EXACT.get(ancestorName)))) {
return i;
@@ -178,10 +224,6 @@ public final class InternetDomainName {
if (PublicSuffixPatterns.EXCLUDED.containsKey(ancestorName)) {
return i + 1;
}
-
- if (matchesWildcardSuffixType(desiredType, ancestorName)) {
- return i;
- }
}
return NO_SUFFIX_FOUND;
@@ -329,7 +371,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean isPublicSuffix() {
- return publicSuffixIndex == 0;
+ return publicSuffixIndex() == 0;
}
/**
@@ -345,7 +387,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean hasPublicSuffix() {
- return publicSuffixIndex != NO_SUFFIX_FOUND;
+ return publicSuffixIndex() != NO_SUFFIX_FOUND;
}
/**
@@ -356,7 +398,7 @@ public final class InternetDomainName {
*/
@CheckForNull
public InternetDomainName publicSuffix() {
- return hasPublicSuffix() ? ancestor(publicSuffixIndex) : null;
+ return hasPublicSuffix() ? ancestor(publicSuffixIndex()) : null;
}
/**
@@ -372,7 +414,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean isUnderPublicSuffix() {
- return publicSuffixIndex > 0;
+ return publicSuffixIndex() > 0;
}
/**
@@ -388,7 +430,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean isTopPrivateDomain() {
- return publicSuffixIndex == 1;
+ return publicSuffixIndex() == 1;
}
/**
@@ -412,7 +454,7 @@ public final class InternetDomainName {
return this;
}
checkState(isUnderPublicSuffix(), "Not under a public suffix: %s", name);
- return ancestor(publicSuffixIndex - 1);
+ return ancestor(publicSuffixIndex() - 1);
}
/**
@@ -439,7 +481,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean isRegistrySuffix() {
- return registrySuffixIndex == 0;
+ return registrySuffixIndex() == 0;
}
/**
@@ -454,7 +496,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean hasRegistrySuffix() {
- return registrySuffixIndex != NO_SUFFIX_FOUND;
+ return registrySuffixIndex() != NO_SUFFIX_FOUND;
}
/**
@@ -465,7 +507,7 @@ public final class InternetDomainName {
*/
@CheckForNull
public InternetDomainName registrySuffix() {
- return hasRegistrySuffix() ? ancestor(registrySuffixIndex) : null;
+ return hasRegistrySuffix() ? ancestor(registrySuffixIndex()) : null;
}
/**
@@ -477,7 +519,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean isUnderRegistrySuffix() {
- return registrySuffixIndex > 0;
+ return registrySuffixIndex() > 0;
}
/**
@@ -492,7 +534,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean isTopDomainUnderRegistrySuffix() {
- return registrySuffixIndex == 1;
+ return registrySuffixIndex() == 1;
}
/**
@@ -515,7 +557,7 @@ public final class InternetDomainName {
return this;
}
checkState(isUnderRegistrySuffix(), "Not under a registry suffix: %s", name);
- return ancestor(registrySuffixIndex - 1);
+ return ancestor(registrySuffixIndex() - 1);
}
/** Indicates whether this domain is composed of two or more parts. */
@@ -592,18 +634,6 @@ public final class InternetDomainName {
}
/**
- * Does the domain name match one of the "wildcard" patterns (e.g. {@code "*.ar"})? If a {@code
- * desiredType} is specified, the wildcard pattern must also match that type.
- */
- private static boolean matchesWildcardSuffixType(
- Optional<PublicSuffixType> desiredType, String domain) {
- List<String> pieces = DOT_SPLITTER.limit(2).splitToList(domain);
- return pieces.size() == 2
- && matchesType(
- desiredType, Optional.fromNullable(PublicSuffixPatterns.UNDER.get(pieces.get(1))));
- }
-
- /**
* If a {@code desiredType} is specified, returns true only if the {@code actualType} is
* identical. Otherwise, returns true as long as {@code actualType} is present.
*/
diff --git a/android/guava/src/com/google/common/net/MediaType.java b/android/guava/src/com/google/common/net/MediaType.java
index a713d0b17..c7da53491 100644
--- a/android/guava/src/com/google/common/net/MediaType.java
+++ b/android/guava/src/com/google/common/net/MediaType.java
@@ -492,6 +492,13 @@ public final class MediaType {
public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
/**
+ * For <a href="https://tools.ietf.org/html/7519">JWT objects using the compact Serialization</a>.
+ *
+ * @since 32.0.0
+ */
+ public static final MediaType JWT = createConstant(APPLICATION_TYPE, "jwt");
+
+ /**
* The <a href="http://www.w3.org/TR/appmanifest/">Manifest for a web application</a>.
*
* @since 19.0
@@ -886,7 +893,7 @@ public final class MediaType {
* one.
*
* <p>If a charset must be specified that is not supported on this JVM (and thus is not
- * representable as a {@link Charset} instance, use {@link #withParameter}.
+ * representable as a {@link Charset} instance), use {@link #withParameter}.
*/
public MediaType withCharset(Charset charset) {
checkNotNull(charset);
diff --git a/android/guava/src/com/google/common/net/ParametricNullness.java b/android/guava/src/com/google/common/net/ParametricNullness.java
index 1ad2e27c0..83b9eb6fa 100644
--- a/android/guava/src/com/google/common/net/ParametricNullness.java
+++ b/android/guava/src/com/google/common/net/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/net/PercentEscaper.java b/android/guava/src/com/google/common/net/PercentEscaper.java
index 929014731..411834f8d 100644
--- a/android/guava/src/com/google/common/net/PercentEscaper.java
+++ b/android/guava/src/com/google/common/net/PercentEscaper.java
@@ -74,10 +74,10 @@ public final class PercentEscaper extends UnicodeEscaper {
* space character.
*
* <p>Not that it is allowed, but not necessarily desirable to specify {@code %} as a safe
- * character. This has the effect of creating an escaper which has no well defined inverse but it
+ * character. This has the effect of creating an escaper which has no well-defined inverse but it
* can be useful when escaping additional characters.
*
- * @param safeChars a non null string specifying additional safe characters for this escaper (the
+ * @param safeChars a non-null string specifying additional safe characters for this escaper (the
* ranges 0..9, a..z and A..Z are always safe and should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +} rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
diff --git a/android/guava/src/com/google/common/net/package-info.java b/android/guava/src/com/google/common/net/package-info.java
index d55642d94..6a74ecee4 100644
--- a/android/guava/src/com/google/common/net/package-info.java
+++ b/android/guava/src/com/google/common/net/package-info.java
@@ -13,10 +13,9 @@
*/
/**
- * This package contains utility methods and classes for working with net addresses (numeric IP and
- * domain names).
+ * Utility methods and classes for networking (such as IP addresses and domain names).
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* @author Craig Berry
diff --git a/android/guava/src/com/google/common/primitives/Booleans.java b/android/guava/src/com/google/common/primitives/Booleans.java
index 522049bfe..1af9e337d 100644
--- a/android/guava/src/com/google/common/primitives/Booleans.java
+++ b/android/guava/src/com/google/common/primitives/Booleans.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
@@ -80,7 +79,6 @@ public final class Booleans {
*
* @since 21.0
*/
- @Beta
public static Comparator<Boolean> trueFirst() {
return BooleanComparator.TRUE_FIRST;
}
@@ -93,7 +91,6 @@ public final class Booleans {
*
* @since 21.0
*/
- @Beta
public static Comparator<Boolean> falseFirst() {
return BooleanComparator.FALSE_FIRST;
}
@@ -361,9 +358,10 @@ public final class Booleans {
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
* set a value to {@code null} will result in a {@link NullPointerException}.
*
- * <p>The returned list maintains the values, but not the identities, of {@code Boolean} objects
- * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
- * the returned list is unspecified.
+ * <p>There are at most two distinct objects in this list, {@code (Boolean) true} and {@code
+ * (Boolean) false}. Java guarantees that those are always represented by the same objects.
+ *
+ * <p>The returned list is serializable.
*
* @param backingArray the array to back the list
* @return a list view of the array
@@ -510,7 +508,6 @@ public final class Booleans {
*
* @since 16.0
*/
- @Beta
public static int countTrue(boolean... values) {
int count = 0;
for (boolean value : values) {
@@ -551,4 +548,54 @@ public final class Booleans {
array[j] = tmp;
}
}
+
+ /**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Booleans.asList(array),
+ * distance)}, but is somewhat faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(boolean[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Booleans.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * somewhat faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(boolean[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
}
diff --git a/android/guava/src/com/google/common/primitives/Bytes.java b/android/guava/src/com/google/common/primitives/Bytes.java
index 62997f34a..b32ef8ec9 100644
--- a/android/guava/src/com/google/common/primitives/Bytes.java
+++ b/android/guava/src/com/google/common/primitives/Bytes.java
@@ -227,6 +227,8 @@ public final class Bytes {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
@@ -396,4 +398,54 @@ public final class Bytes {
array[j] = tmp;
}
}
+
+ /**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
+ * distance)}, but is somewhat faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(byte[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is somewhat
+ * faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(byte[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
}
diff --git a/android/guava/src/com/google/common/primitives/Chars.java b/android/guava/src/com/google/common/primitives/Chars.java
index 4a2e3a344..728c6e5e9 100644
--- a/android/guava/src/com/google/common/primitives/Chars.java
+++ b/android/guava/src/com/google/common/primitives/Chars.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
@@ -258,7 +257,6 @@ public final class Chars {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static char constrainToRange(char value, char min, char max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return value < min ? min : value < max ? value : max;
@@ -489,6 +487,56 @@ public final class Chars {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Chars.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(char[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Chars.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(char[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
* set a value to {@code null} will result in a {@link NullPointerException}.
@@ -497,6 +545,8 @@ public final class Chars {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
diff --git a/android/guava/src/com/google/common/primitives/Doubles.java b/android/guava/src/com/google/common/primitives/Doubles.java
index ce5df2e39..81bf104ce 100644
--- a/android/guava/src/com/google/common/primitives/Doubles.java
+++ b/android/guava/src/com/google/common/primitives/Doubles.java
@@ -22,9 +22,9 @@ import static com.google.common.base.Strings.lenientFormat;
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.POSITIVE_INFINITY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
import java.util.AbstractList;
@@ -253,7 +253,6 @@ public final class Doubles extends DoublesMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static double constrainToRange(double value, double min, double max) {
// avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984
// Reject NaN by testing for the good case (min <= max) instead of the bad (min > max).
@@ -318,7 +317,6 @@ public final class Doubles extends DoublesMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Double> stringConverter() {
return DoubleConverter.INSTANCE;
}
@@ -468,6 +466,56 @@ public final class Doubles extends DoublesMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(double[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(double[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code double}
* value in the manner of {@link Number#doubleValue}.
*
@@ -507,6 +555,8 @@ public final class Doubles extends DoublesMethodsForWeb {
* <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
* is used as a parameter to any of its methods.
*
+ * <p>The returned list is serializable.
+ *
* <p><b>Note:</b> when possible, you should represent your data as an {@link
* ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view.
*
@@ -655,7 +705,7 @@ public final class Doubles extends DoublesMethodsForWeb {
* inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs
* that pass this regex are valid -- only a performance hit is incurred, not a semantics bug.
*/
- @GwtIncompatible // regular expressions
+ @J2ktIncompatible @GwtIncompatible // regular expressions
static final
java.util.regex.Pattern
FLOATING_POINT_PATTERN = fpPattern();
@@ -701,7 +751,7 @@ public final class Doubles extends DoublesMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // regular expressions
@CheckForNull
public static Double tryParse(String string) {
diff --git a/android/guava/src/com/google/common/primitives/Floats.java b/android/guava/src/com/google/common/primitives/Floats.java
index b038cb289..d7f156b1e 100644
--- a/android/guava/src/com/google/common/primitives/Floats.java
+++ b/android/guava/src/com/google/common/primitives/Floats.java
@@ -22,9 +22,9 @@ import static com.google.common.base.Strings.lenientFormat;
import static java.lang.Float.NEGATIVE_INFINITY;
import static java.lang.Float.POSITIVE_INFINITY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
import java.util.AbstractList;
@@ -250,7 +250,6 @@ public final class Floats extends FloatsMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static float constrainToRange(float value, float min, float max) {
// avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984
// Reject NaN by testing for the good case (min <= max) instead of the bad (min > max).
@@ -315,7 +314,6 @@ public final class Floats extends FloatsMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Float> stringConverter() {
return FloatConverter.INSTANCE;
}
@@ -465,6 +463,56 @@ public final class Floats extends FloatsMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Floats.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(float[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Floats.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(float[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code float}
* value in the manner of {@link Number#floatValue}.
*
@@ -504,6 +552,8 @@ public final class Floats extends FloatsMethodsForWeb {
* <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
* is used as a parameter to any of its methods.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
@@ -660,7 +710,7 @@ public final class Floats extends FloatsMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // regular expressions
@CheckForNull
public static Float tryParse(String string) {
diff --git a/android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java b/android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
index 1627fab2b..1b4169c12 100644
--- a/android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
+++ b/android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
@@ -16,11 +16,9 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.AbstractList;
@@ -77,7 +75,6 @@ import javax.annotation.CheckForNull;
*
* @since 22.0
*/
-@Beta
@GwtCompatible
@Immutable
@ElementTypesAreNonnullByDefault
@@ -195,7 +192,6 @@ public final class ImmutableDoubleArray implements Serializable {
* A builder for {@link ImmutableDoubleArray} instances; obtained using {@link
* ImmutableDoubleArray#builder}.
*/
- @CanIgnoreReturnValue
public static final class Builder {
private double[] array;
private int count = 0; // <= array.length
@@ -208,6 +204,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code value} to the end of the values the built {@link ImmutableDoubleArray} will
* contain.
*/
+ @CanIgnoreReturnValue
public Builder add(double value) {
ensureRoomFor(1);
array[count] = value;
@@ -219,6 +216,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(double[] values) {
ensureRoomFor(values.length);
System.arraycopy(values, 0, array, count, values.length);
@@ -230,6 +228,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Iterable<Double> values) {
if (values instanceof Collection) {
return addAll((Collection<Double>) values);
@@ -244,6 +243,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Collection<Double> values) {
ensureRoomFor(values.size());
for (Double value : values) {
@@ -256,6 +256,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(ImmutableDoubleArray values) {
ensureRoomFor(values.length());
System.arraycopy(values.array, values.start, array, count, values.length());
@@ -294,7 +295,6 @@ public final class ImmutableDoubleArray implements Serializable {
* no data is copied as part of this step, but this may occupy more memory than strictly
* necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
*/
- @CheckReturnValue
public ImmutableDoubleArray build() {
return count == 0 ? EMPTY : new ImmutableDoubleArray(array, 0, count);
}
diff --git a/android/guava/src/com/google/common/primitives/ImmutableIntArray.java b/android/guava/src/com/google/common/primitives/ImmutableIntArray.java
index 8f972c49b..57c464c98 100644
--- a/android/guava/src/com/google/common/primitives/ImmutableIntArray.java
+++ b/android/guava/src/com/google/common/primitives/ImmutableIntArray.java
@@ -16,11 +16,9 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.AbstractList;
@@ -77,7 +75,6 @@ import javax.annotation.CheckForNull;
*
* @since 22.0
*/
-@Beta
@GwtCompatible
@Immutable
@ElementTypesAreNonnullByDefault
@@ -192,7 +189,6 @@ public final class ImmutableIntArray implements Serializable {
* A builder for {@link ImmutableIntArray} instances; obtained using {@link
* ImmutableIntArray#builder}.
*/
- @CanIgnoreReturnValue
public static final class Builder {
private int[] array;
private int count = 0; // <= array.length
@@ -205,6 +201,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code value} to the end of the values the built {@link ImmutableIntArray} will
* contain.
*/
+ @CanIgnoreReturnValue
public Builder add(int value) {
ensureRoomFor(1);
array[count] = value;
@@ -216,6 +213,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(int[] values) {
ensureRoomFor(values.length);
System.arraycopy(values, 0, array, count, values.length);
@@ -227,6 +225,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Iterable<Integer> values) {
if (values instanceof Collection) {
return addAll((Collection<Integer>) values);
@@ -241,6 +240,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Collection<Integer> values) {
ensureRoomFor(values.size());
for (Integer value : values) {
@@ -253,6 +253,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(ImmutableIntArray values) {
ensureRoomFor(values.length());
System.arraycopy(values.array, values.start, array, count, values.length());
@@ -291,7 +292,6 @@ public final class ImmutableIntArray implements Serializable {
* no data is copied as part of this step, but this may occupy more memory than strictly
* necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
*/
- @CheckReturnValue
public ImmutableIntArray build() {
return count == 0 ? EMPTY : new ImmutableIntArray(array, 0, count);
}
diff --git a/android/guava/src/com/google/common/primitives/ImmutableLongArray.java b/android/guava/src/com/google/common/primitives/ImmutableLongArray.java
index 4ebf5b406..cf417458b 100644
--- a/android/guava/src/com/google/common/primitives/ImmutableLongArray.java
+++ b/android/guava/src/com/google/common/primitives/ImmutableLongArray.java
@@ -16,11 +16,9 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.AbstractList;
@@ -77,7 +75,6 @@ import javax.annotation.CheckForNull;
*
* @since 22.0
*/
-@Beta
@GwtCompatible
@Immutable
@ElementTypesAreNonnullByDefault
@@ -194,7 +191,6 @@ public final class ImmutableLongArray implements Serializable {
* A builder for {@link ImmutableLongArray} instances; obtained using {@link
* ImmutableLongArray#builder}.
*/
- @CanIgnoreReturnValue
public static final class Builder {
private long[] array;
private int count = 0; // <= array.length
@@ -207,6 +203,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code value} to the end of the values the built {@link ImmutableLongArray} will
* contain.
*/
+ @CanIgnoreReturnValue
public Builder add(long value) {
ensureRoomFor(1);
array[count] = value;
@@ -218,6 +215,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(long[] values) {
ensureRoomFor(values.length);
System.arraycopy(values, 0, array, count, values.length);
@@ -229,6 +227,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Iterable<Long> values) {
if (values instanceof Collection) {
return addAll((Collection<Long>) values);
@@ -243,6 +242,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Collection<Long> values) {
ensureRoomFor(values.size());
for (Long value : values) {
@@ -255,6 +255,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(ImmutableLongArray values) {
ensureRoomFor(values.length());
System.arraycopy(values.array, values.start, array, count, values.length());
@@ -293,7 +294,6 @@ public final class ImmutableLongArray implements Serializable {
* no data is copied as part of this step, but this may occupy more memory than strictly
* necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
*/
- @CheckReturnValue
public ImmutableLongArray build() {
return count == 0 ? EMPTY : new ImmutableLongArray(array, 0, count);
}
diff --git a/android/guava/src/com/google/common/primitives/Ints.java b/android/guava/src/com/google/common/primitives/Ints.java
index e07bdd88d..cbd81fb12 100644
--- a/android/guava/src/com/google/common/primitives/Ints.java
+++ b/android/guava/src/com/google/common/primitives/Ints.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Converter;
@@ -267,7 +266,6 @@ public final class Ints extends IntsMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static int constrainToRange(int value, int min, int max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return Math.min(Math.max(value, min), max);
@@ -372,7 +370,6 @@ public final class Ints extends IntsMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Integer> stringConverter() {
return IntConverter.INSTANCE;
}
@@ -511,6 +508,82 @@ public final class Ints extends IntsMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(int[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(int[] array, int distance, int fromIndex, int toIndex) {
+ // There are several well-known algorithms for rotating part of an array (or, equivalently,
+ // exchanging two blocks of memory). This classic text by Gries and Mills mentions several:
+ // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf.
+ // (1) "Reversal", the one we have here.
+ // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0]
+ // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0].
+ // (All indices taken mod n.) If d and n are mutually prime, all elements will have been
+ // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc,
+ // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles
+ // in all.
+ // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a
+ // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we
+ // imagine a line separating the first block from the second, we can proceed by exchanging
+ // the smaller of these blocks with the far end of the other one. That leaves us with a
+ // smaller version of the same problem.
+ // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]:
+ // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de]
+ // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]:
+ // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]:
+ // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done.
+ // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each
+ // array slot is read and written exactly once. However, it can have very poor memory locality:
+ // benchmarking shows it can take 7 times longer than the other two in some cases. The other two
+ // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about
+ // twice as many reads and writes. But benchmarking shows that they usually perform better than
+ // Dolphin. Reversal is about as good as Successive on average, and it is much simpler,
+ // especially since we already have a `reverse` method.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code int} value
* in the manner of {@link Number#intValue}.
*
@@ -547,6 +620,8 @@ public final class Ints extends IntsMethodsForWeb {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray}
* instead, which has an {@link ImmutableIntArray#asList asList} view.
*
@@ -706,7 +781,6 @@ public final class Ints extends IntsMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 11.0
*/
- @Beta
@CheckForNull
public static Integer tryParse(String string) {
return tryParse(string, 10);
@@ -732,7 +806,6 @@ public final class Ints extends IntsMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 19.0
*/
- @Beta
@CheckForNull
public static Integer tryParse(String string, int radix) {
Long result = Longs.tryParse(string, radix);
diff --git a/android/guava/src/com/google/common/primitives/Longs.java b/android/guava/src/com/google/common/primitives/Longs.java
index 6f60656bc..ce6a6fa39 100644
--- a/android/guava/src/com/google/common/primitives/Longs.java
+++ b/android/guava/src/com/google/common/primitives/Longs.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
@@ -234,7 +233,6 @@ public final class Longs {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static long constrainToRange(long value, long min, long max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return Math.min(Math.max(value, min), max);
@@ -246,13 +244,15 @@ public final class Longs {
*
* @param arrays zero or more {@code long} arrays
* @return a single array containing all the values from the source arrays, in order
+ * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
+ * in an {@code int}
*/
public static long[] concat(long[]... arrays) {
- int length = 0;
+ long length = 0;
for (long[] array : arrays) {
length += array.length;
}
- long[] result = new long[length];
+ long[] result = new long[checkNoOverflow(length)];
int pos = 0;
for (long[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
@@ -261,6 +261,14 @@ public final class Longs {
return result;
}
+ private static int checkNoOverflow(long result) {
+ checkArgument(
+ result == (int) result,
+ "the total number of elements (%s) in the arrays must fit in an int",
+ result);
+ return (int) result;
+ }
+
/**
* Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
* {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code
@@ -361,7 +369,6 @@ public final class Longs {
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
- @Beta
@CheckForNull
public static Long tryParse(String string) {
return tryParse(string, 10);
@@ -378,7 +385,7 @@ public final class Longs {
* <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
* the change to {@link Long#parseLong(String, int)} for that version.
*
- * @param string the string representation of an long value
+ * @param string the string representation of a long value
* @param radix the radix to use when parsing
* @return the long value represented by {@code string} using {@code radix}, or {@code null} if
* {@code string} has a length of zero or cannot be parsed as a long value
@@ -387,7 +394,6 @@ public final class Longs {
* @throws NullPointerException if {@code string} is {@code null}
* @since 19.0
*/
- @Beta
@CheckForNull
public static Long tryParse(String string, int radix) {
if (checkNotNull(string).isEmpty()) {
@@ -467,7 +473,6 @@ public final class Longs {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Long> stringConverter() {
return LongConverter.INSTANCE;
}
@@ -607,6 +612,56 @@ public final class Longs {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(long[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(long[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code long} value
* in the manner of {@link Number#longValue}.
*
@@ -643,6 +698,8 @@ public final class Longs {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
* instead, which has an {@link ImmutableLongArray#asList asList} view.
*
diff --git a/android/guava/src/com/google/common/primitives/ParametricNullness.java b/android/guava/src/com/google/common/primitives/ParametricNullness.java
index 4289b9b16..c40ea499d 100644
--- a/android/guava/src/com/google/common/primitives/ParametricNullness.java
+++ b/android/guava/src/com/google/common/primitives/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/primitives/Primitives.java b/android/guava/src/com/google/common/primitives/Primitives.java
index 7ceed0365..cfd1eac46 100644
--- a/android/guava/src/com/google/common/primitives/Primitives.java
+++ b/android/guava/src/com/google/common/primitives/Primitives.java
@@ -16,7 +16,7 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.GwtCompatible;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -29,7 +29,7 @@ import java.util.Set;
* @author Kevin Bourrillion
* @since 1.0
*/
-@GwtIncompatible
+@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Primitives {
private Primitives() {}
diff --git a/android/guava/src/com/google/common/primitives/Shorts.java b/android/guava/src/com/google/common/primitives/Shorts.java
index 09e0f7cfc..85ffd3ba8 100644
--- a/android/guava/src/com/google/common/primitives/Shorts.java
+++ b/android/guava/src/com/google/common/primitives/Shorts.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Converter;
@@ -266,7 +265,6 @@ public final class Shorts extends ShortsMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static short constrainToRange(short value, short min, short max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return value < min ? min : value < max ? value : max;
@@ -372,7 +370,6 @@ public final class Shorts extends ShortsMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Short> stringConverter() {
return ShortConverter.INSTANCE;
}
@@ -513,6 +510,56 @@ public final class Shorts extends ShortsMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Shorts.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(short[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Shorts.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(short[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code short}
* value in the manner of {@link Number#shortValue}.
*
@@ -549,6 +596,8 @@ public final class Shorts extends ShortsMethodsForWeb {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
diff --git a/android/guava/src/com/google/common/primitives/UnsignedBytes.java b/android/guava/src/com/google/common/primitives/UnsignedBytes.java
index db4f489e4..0490c6714 100644
--- a/android/guava/src/com/google/common/primitives/UnsignedBytes.java
+++ b/android/guava/src/com/google/common/primitives/UnsignedBytes.java
@@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.nio.ByteOrder;
@@ -43,6 +43,7 @@ import sun.misc.Unsafe;
* @author Louis Wasserman
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class UnsignedBytes {
@@ -167,7 +168,6 @@ public final class UnsignedBytes {
*
* @since 13.0
*/
- @Beta
public static String toString(byte x) {
return toString(x, 10);
}
@@ -182,7 +182,6 @@ public final class UnsignedBytes {
* and {@link Character#MAX_RADIX}.
* @since 13.0
*/
- @Beta
public static String toString(byte x, int radix) {
checkArgument(
radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
@@ -201,7 +200,6 @@ public final class UnsignedBytes {
* Byte#parseByte(String)})
* @since 13.0
*/
- @Beta
@CanIgnoreReturnValue
public static byte parseUnsignedByte(String string) {
return parseUnsignedByte(string, 10);
@@ -219,7 +217,6 @@ public final class UnsignedBytes {
* Byte#parseByte(String)})
* @since 13.0
*/
- @Beta
@CanIgnoreReturnValue
public static byte parseUnsignedByte(String string, int radix) {
int parse = Integer.parseInt(checkNotNull(string), radix);
diff --git a/android/guava/src/com/google/common/primitives/UnsignedInteger.java b/android/guava/src/com/google/common/primitives/UnsignedInteger.java
index 0b30cef3f..52b05e4e7 100644
--- a/android/guava/src/com/google/common/primitives/UnsignedInteger.java
+++ b/android/guava/src/com/google/common/primitives/UnsignedInteger.java
@@ -22,6 +22,7 @@ import static com.google.common.primitives.UnsignedInts.toLong;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.math.BigInteger;
import javax.annotation.CheckForNull;
@@ -143,6 +144,7 @@ public final class UnsignedInteger extends Number implements Comparable<Unsigned
*
* @since 14.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Does not truncate correctly
public UnsignedInteger times(UnsignedInteger val) {
// TODO(lowasser): make this GWT-compatible
diff --git a/android/guava/src/com/google/common/primitives/UnsignedInts.java b/android/guava/src/com/google/common/primitives/UnsignedInts.java
index ec6474e20..0d556bab4 100644
--- a/android/guava/src/com/google/common/primitives/UnsignedInts.java
+++ b/android/guava/src/com/google/common/primitives/UnsignedInts.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
@@ -45,7 +44,6 @@ import java.util.Comparator;
* @author Louis Wasserman
* @since 11.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class UnsignedInts {
diff --git a/android/guava/src/com/google/common/primitives/UnsignedLongs.java b/android/guava/src/com/google/common/primitives/UnsignedLongs.java
index 31c51cc34..04631ee9d 100644
--- a/android/guava/src/com/google/common/primitives/UnsignedLongs.java
+++ b/android/guava/src/com/google/common/primitives/UnsignedLongs.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.math.BigInteger;
@@ -48,7 +47,6 @@ import java.util.Comparator;
* @author Colin Evans
* @since 10.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class UnsignedLongs {
diff --git a/android/guava/src/com/google/common/primitives/package-info.java b/android/guava/src/com/google/common/primitives/package-info.java
index 9504fa79b..ad38c1113 100644
--- a/android/guava/src/com/google/common/primitives/package-info.java
+++ b/android/guava/src/com/google/common/primitives/package-info.java
@@ -13,10 +13,10 @@
*/
/**
- * Static utilities for working with the eight primitive types and {@code void}, and value types for
- * treating them as unsigned.
+ * Static utilities for the eight primitive types and {@code void}, and value types for treating
+ * them as unsigned or storing them in immutable arrays.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* <p>See the Guava User Guide article on <a
@@ -24,40 +24,43 @@
*
* <h2>Contents</h2>
*
- * <h3>General static utilities</h3>
+ * <h3>Value types</h3>
*
* <ul>
- * <li>{@link com.google.common.primitives.Primitives}
+ * <li>{@link ImmutableDoubleArray}
+ * <li>{@link ImmutableIntArray}
+ * <li>{@link ImmutableLongrray}
+ * <li>{@link UnsignedInteger}
+ * <li>{@link UnsignedLong}
* </ul>
*
* <h3>Per-type static utilities</h3>
*
* <ul>
- * <li>{@link com.google.common.primitives.Booleans}
- * <li>{@link com.google.common.primitives.Bytes}
+ * <li>{@link Booleans}
+ * <li>{@link Bytes}
* <ul>
- * <li>{@link com.google.common.primitives.SignedBytes}
- * <li>{@link com.google.common.primitives.UnsignedBytes}
+ * <li>{@link SignedBytes}
+ * <li>{@link UnsignedBytes}
* </ul>
- * <li>{@link com.google.common.primitives.Chars}
- * <li>{@link com.google.common.primitives.Doubles}
- * <li>{@link com.google.common.primitives.Floats}
- * <li>{@link com.google.common.primitives.Ints}
+ * <li>{@link Chars}
+ * <li>{@link Doubles}
+ * <li>{@link Floats}
+ * <li>{@link Ints}
* <ul>
- * <li>{@link com.google.common.primitives.UnsignedInts}
+ * <li>{@link UnsignedInts}
* </ul>
- * <li>{@link com.google.common.primitives.Longs}
+ * <li>{@link Longs}
* <ul>
- * <li>{@link com.google.common.primitives.UnsignedLongs}
+ * <li>{@link UnsignedLongs}
* </ul>
- * <li>{@link com.google.common.primitives.Shorts}
+ * <li>{@link Shorts}
* </ul>
*
- * <h3>Value types</h3>
+ * <h3>General static utilities</h3>
*
* <ul>
- * <li>{@link com.google.common.primitives.UnsignedInteger}
- * <li>{@link com.google.common.primitives.UnsignedLong}
+ * <li>{@link Primitives}
* </ul>
*/
@ParametersAreNonnullByDefault
diff --git a/android/guava/src/com/google/common/reflect/IgnoreJRERequirement.java b/android/guava/src/com/google/common/reflect/IgnoreJRERequirement.java
new file mode 100644
index 000000000..8b03ca332
--- /dev/null
+++ b/android/guava/src/com/google/common/reflect/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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.reflect;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/android/guava/src/com/google/common/reflect/Invokable.java b/android/guava/src/com/google/common/reflect/Invokable.java
index 8e75aa856..236c29627 100644
--- a/android/guava/src/com/google/common/reflect/Invokable.java
+++ b/android/guava/src/com/google/common/reflect/Invokable.java
@@ -19,9 +19,11 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.DoNotCall;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
@@ -62,7 +64,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0 (no longer implements {@link AccessibleObject} or {@code GenericDeclaration} since
* 31.0)
*/
-@Beta
@ElementTypesAreNonnullByDefault
public abstract class Invokable<T, R> implements AnnotatedElement, Member {
private final AccessibleObject accessibleObject;
@@ -272,12 +273,17 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
* of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden {@code
* this} parameter of the enclosing class is excluded from the returned parameters.
*/
+ @IgnoreJRERequirement
public final ImmutableList<Parameter> getParameters() {
Type[] parameterTypes = getGenericParameterTypes();
Annotation[][] annotations = getParameterAnnotations();
+ @Nullable Object[] annotatedTypes =
+ ANNOTATED_TYPE_EXISTS ? getAnnotatedParameterTypes() : new Object[parameterTypes.length];
ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
for (int i = 0; i < parameterTypes.length; i++) {
- builder.add(new Parameter(this, i, TypeToken.of(parameterTypes[i]), annotations[i]));
+ builder.add(
+ new Parameter(
+ this, i, TypeToken.of(parameterTypes[i]), annotations[i], annotatedTypes[i]));
}
return builder.build();
}
@@ -337,6 +343,10 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
abstract Type[] getGenericParameterTypes();
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
+ abstract AnnotatedType[] getAnnotatedParameterTypes();
+
/** This should never return a type that's not a subtype of Throwable. */
abstract Type[] getGenericExceptionTypes();
@@ -344,6 +354,22 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
abstract Type getGenericReturnType();
+ /**
+ * Returns the {@link AnnotatedType} for the return type.
+ *
+ * <p>This method will fail if run under an Android VM.
+ *
+ * @since NEXT for guava-android (available since 14.0 in guava-jre)
+ * @deprecated This method does not work under Android VMs. It is safe to use from guava-jre, but
+ * this copy in guava-android is not safe to use.
+ */
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @DoNotCall("fails under Android VMs; do not use from guava-android")
+ @Deprecated
+ @IgnoreJRERequirement
+ @Beta
+ public abstract AnnotatedType getAnnotatedReturnType();
+
static class MethodInvokable<T> extends Invokable<T, Object> {
final Method method;
@@ -371,6 +397,21 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
}
@Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
+ AnnotatedType[] getAnnotatedParameterTypes() {
+ return method.getAnnotatedParameterTypes();
+ }
+
+ @Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker", "DoNotCall"})
+ @DoNotCall
+ @IgnoreJRERequirement
+ public AnnotatedType getAnnotatedReturnType() {
+ return method.getAnnotatedReturnType();
+ }
+
+ @Override
Type[] getGenericExceptionTypes() {
return method.getGenericExceptionTypes();
}
@@ -448,6 +489,21 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
}
@Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
+ AnnotatedType[] getAnnotatedParameterTypes() {
+ return constructor.getAnnotatedParameterTypes();
+ }
+
+ @Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker", "DoNotCall"})
+ @DoNotCall
+ @IgnoreJRERequirement
+ public AnnotatedType getAnnotatedReturnType() {
+ return constructor.getAnnotatedReturnType();
+ }
+
+ @Override
Type[] getGenericExceptionTypes() {
return constructor.getGenericExceptionTypes();
}
@@ -510,4 +566,15 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
}
}
}
+
+ private static final boolean ANNOTATED_TYPE_EXISTS = initAnnotatedTypeExists();
+
+ private static boolean initAnnotatedTypeExists() {
+ try {
+ Class.forName("java.lang.reflect.AnnotatedType");
+ } catch (ClassNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
}
diff --git a/android/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java b/android/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
index 9542e0a7e..7690d2eef 100644
--- a/android/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
+++ b/android/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
@@ -27,47 +27,45 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A mutable type-to-instance map. See also {@link ImmutableTypeToInstanceMap}.
*
- * <p>This implementation <i>does</i> support null values, despite how it is annotated; see
- * discussion at {@link TypeToInstanceMap}.
- *
* @author Ben Yu
* @since 13.0
*/
@ElementTypesAreNonnullByDefault
-public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B>
- implements TypeToInstanceMap<B> {
+public final class MutableTypeToInstanceMap<B extends @Nullable Object>
+ extends ForwardingMap<TypeToken<? extends @NonNull B>, B> implements TypeToInstanceMap<B> {
- private final Map<TypeToken<? extends B>, B> backingMap = Maps.newHashMap();
+ private final Map<TypeToken<? extends @NonNull B>, B> backingMap = Maps.newHashMap();
@Override
@CheckForNull
- public <T extends B> T getInstance(Class<T> type) {
+ public <T extends @NonNull B> T getInstance(Class<T> type) {
return trustedGet(TypeToken.of(type));
}
@Override
@CheckForNull
- public <T extends B> T getInstance(TypeToken<T> type) {
+ public <T extends @NonNull B> T getInstance(TypeToken<T> type) {
return trustedGet(type.rejectTypeVariables());
}
@Override
@CanIgnoreReturnValue
@CheckForNull
- public <T extends B> T putInstance(Class<T> type, T value) {
+ public <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value) {
return trustedPut(TypeToken.of(type), value);
}
@Override
@CanIgnoreReturnValue
@CheckForNull
- public <T extends B> T putInstance(TypeToken<T> type, T value) {
- return trustedPut(type.rejectTypeVariables(), value);
+ public <T extends B> T putInstance(TypeToken<@NonNull T> type, @ParametricNullness T value) {
+ return this.<T>trustedPut(type.rejectTypeVariables(), value);
}
/**
@@ -81,7 +79,7 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
- public B put(TypeToken<? extends B> key, B value) {
+ public B put(TypeToken<? extends @NonNull B> key, @ParametricNullness B value) {
throw new UnsupportedOperationException("Please use putInstance() instead.");
}
@@ -94,37 +92,39 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
- public void putAll(Map<? extends TypeToken<? extends B>, ? extends B> map) {
+ public void putAll(Map<? extends TypeToken<? extends @NonNull B>, ? extends B> map) {
throw new UnsupportedOperationException("Please use putInstance() instead.");
}
@Override
- public Set<Entry<TypeToken<? extends B>, B>> entrySet() {
+ public Set<Entry<TypeToken<? extends @NonNull B>, B>> entrySet() {
return UnmodifiableEntry.transformEntries(super.entrySet());
}
@Override
- protected Map<TypeToken<? extends B>, B> delegate() {
+ protected Map<TypeToken<? extends @NonNull B>, B> delegate() {
return backingMap;
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@CheckForNull
- private <T extends B> T trustedPut(TypeToken<T> type, T value) {
+ private <T extends B> T trustedPut(TypeToken<@NonNull T> type, @ParametricNullness T value) {
return (T) backingMap.put(type, value);
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@CheckForNull
- private <T extends B> T trustedGet(TypeToken<T> type) {
+ private <T extends @NonNull B> T trustedGet(TypeToken<T> type) {
return (T) backingMap.get(type);
}
- private static final class UnmodifiableEntry<K, V> extends ForwardingMapEntry<K, V> {
+ private static final class UnmodifiableEntry<K, V extends @Nullable Object>
+ extends ForwardingMapEntry<K, V> {
private final Entry<K, V> delegate;
- static <K, V> Set<Entry<K, V>> transformEntries(Set<Entry<K, V>> entries) {
+ static <K, V extends @Nullable Object> Set<Entry<K, V>> transformEntries(
+ Set<Entry<K, V>> entries) {
return new ForwardingSet<Map.Entry<K, V>>() {
@Override
protected Set<Entry<K, V>> delegate() {
@@ -157,7 +157,8 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
};
}
- private static <K, V> Iterator<Entry<K, V>> transformEntries(Iterator<Entry<K, V>> entries) {
+ private static <K, V extends @Nullable Object> Iterator<Entry<K, V>> transformEntries(
+ Iterator<Entry<K, V>> entries) {
return Iterators.transform(entries, UnmodifiableEntry::new);
}
@@ -171,7 +172,8 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
}
@Override
- public V setValue(V value) {
+ @ParametricNullness
+ public V setValue(@ParametricNullness V value) {
throw new UnsupportedOperationException();
}
}
diff --git a/android/guava/src/com/google/common/reflect/Parameter.java b/android/guava/src/com/google/common/reflect/Parameter.java
index a5be09d41..c69ae734c 100644
--- a/android/guava/src/com/google/common/reflect/Parameter.java
+++ b/android/guava/src/com/google/common/reflect/Parameter.java
@@ -15,26 +15,24 @@
package com.google.common.reflect;
import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
+import com.google.errorprone.annotations.DoNotCall;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.AnnotatedType;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Represents a method or constructor parameter.
*
- * <p><b>Note:</b> Since Java 8 introduced {@link java.lang.reflect.Parameter} to represent method
- * and constructor parameters, this class is no longer necessary. We intend to deprecate it in a
- * future version.
- *
* @author Ben Yu
* @since 14.0
*/
-@Beta
@ElementTypesAreNonnullByDefault
public final class Parameter implements AnnotatedElement {
@@ -43,12 +41,26 @@ public final class Parameter implements AnnotatedElement {
private final TypeToken<?> type;
private final ImmutableList<Annotation> annotations;
+ /**
+ * An {@link AnnotatedType} instance, or {@code null} under Android VMs (possible only when using
+ * the Android flavor of Guava). The field is declared with a type of {@code Object} to avoid
+ * compatibility problems on Android VMs. The corresponding accessor method, however, can have the
+ * more specific return type as long as users are careful to guard calls to it with version checks
+ * or reflection: Android VMs ignore the types of elements that aren't used.
+ */
+ private final @Nullable Object annotatedType;
+
Parameter(
- Invokable<?, ?> declaration, int position, TypeToken<?> type, Annotation[] annotations) {
+ Invokable<?, ?> declaration,
+ int position,
+ TypeToken<?> type,
+ Annotation[] annotations,
+ @Nullable Object annotatedType) {
this.declaration = declaration;
this.position = position;
this.type = type;
this.annotations = ImmutableList.copyOf(annotations);
+ this.annotatedType = annotatedType;
}
/** Returns the type of the parameter. */
@@ -83,29 +95,34 @@ public final class Parameter implements AnnotatedElement {
return getDeclaredAnnotations();
}
- /** @since 18.0 */
- // @Override on JDK8
+ /**
+ * @since 18.0
+ */
+ @Override
public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
return getDeclaredAnnotationsByType(annotationType);
}
/** @since 18.0 */
- // @Override on JDK8
@Override
public Annotation[] getDeclaredAnnotations() {
return annotations.toArray(new Annotation[0]);
}
- /** @since 18.0 */
- // @Override on JDK8
+ /**
+ * @since 18.0
+ */
+ @Override
@CheckForNull
public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationType) {
checkNotNull(annotationType);
return FluentIterable.from(annotations).filter(annotationType).first().orNull();
}
- /** @since 18.0 */
- // @Override on JDK8
+ /**
+ * @since 18.0
+ */
+ @Override
public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationType) {
@Nullable
A[] result = FluentIterable.from(annotations).filter(annotationType).toArray(annotationType);
@@ -114,6 +131,24 @@ public final class Parameter implements AnnotatedElement {
return cast;
}
+ /**
+ * Returns the {@link AnnotatedType} of the parameter.
+ *
+ * <p>This method will fail if run under an Android VM.
+ *
+ * @since NEXT for guava-android (available since 25.1 in guava-jre)
+ * @deprecated This method does not work under Android VMs. It is safe to use from guava-jre, but
+ * this copy in guava-android is not safe to use.
+ */
+ @Beta
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @Deprecated
+ @DoNotCall("fails under Android VMs; do not use from guava-android")
+ @IgnoreJRERequirement
+ public AnnotatedType getAnnotatedType() {
+ return requireNonNull((AnnotatedType) annotatedType);
+ }
+
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof Parameter) {
diff --git a/android/guava/src/com/google/common/reflect/ParametricNullness.java b/android/guava/src/com/google/common/reflect/ParametricNullness.java
index b6331ac26..372a53bb6 100644
--- a/android/guava/src/com/google/common/reflect/ParametricNullness.java
+++ b/android/guava/src/com/google/common/reflect/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/reflect/Reflection.java b/android/guava/src/com/google/common/reflect/Reflection.java
index 954496348..09e966d12 100644
--- a/android/guava/src/com/google/common/reflect/Reflection.java
+++ b/android/guava/src/com/google/common/reflect/Reflection.java
@@ -54,7 +54,7 @@ public final class Reflection {
*
* <p>WARNING: Normally it's a smell if a class needs to be explicitly initialized, because static
* state hurts system maintainability and testability. In cases when you have no choice while
- * inter-operating with a legacy framework, this method helps to keep the code less ugly.
+ * interoperating with a legacy framework, this method helps to keep the code less ugly.
*
* @throws ExceptionInInitializerError if an exception is thrown during initialization of a class
*/
diff --git a/android/guava/src/com/google/common/reflect/TypeResolver.java b/android/guava/src/com/google/common/reflect/TypeResolver.java
index 32517eb87..e9c3a1d19 100644
--- a/android/guava/src/com/google/common/reflect/TypeResolver.java
+++ b/android/guava/src/com/google/common/reflect/TypeResolver.java
@@ -42,7 +42,7 @@ import javax.annotation.CheckForNull;
*
* <p>Note that usually type mappings are already implied by the static type hierarchy (for example,
* the {@code E} type variable declared by class {@code List} naturally maps to {@code String} in
- * the context of {@code class MyStringList implements List<String>}. In such case, prefer to use
+ * the context of {@code class MyStringList implements List<String>}). In such case, prefer to use
* {@link TypeToken#resolveType} since it's simpler and more type safe. This class should only be
* used when the type mapping isn't implied by the static type hierarchy, but provided through other
* means such as an annotation or external configuration file.
@@ -426,7 +426,7 @@ public final class TypeResolver {
if (var.equalsType(t)) {
// cycle detected, remove the entire cycle from the mapping so that
// each type variable resolves deterministically to itself.
- // Otherwise, a F -> T cycle will end up resolving both F and T
+ // Otherwise, an F -> T cycle will end up resolving both F and T
// nondeterministically to either F or T.
for (Type x = arg; x != null; x = mappings.remove(TypeVariableKey.forLookup(x))) {}
return;
diff --git a/android/guava/src/com/google/common/reflect/TypeToInstanceMap.java b/android/guava/src/com/google/common/reflect/TypeToInstanceMap.java
index 8a418df2a..fe61a2cc5 100644
--- a/android/guava/src/com/google/common/reflect/TypeToInstanceMap.java
+++ b/android/guava/src/com/google/common/reflect/TypeToInstanceMap.java
@@ -18,6 +18,8 @@ import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Map;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A map, each entry of which maps a {@link TypeToken} to an instance of that type. In addition to
@@ -34,16 +36,14 @@ import javax.annotation.CheckForNull;
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries for primitive types,
* and a primitive type and its corresponding wrapper type may map to different values.
*
- * <p>This class's support for {@code null} requires some explanation. For details, see {@link
- * ClassToInstanceMap}. Its explanation applies equally well to {@code TypeToInstanceMap}.
- *
* @param <B> the common supertype that all entries must share; often this is simply {@link Object}
* @author Ben Yu
* @since 13.0
*/
@DoNotMock("Use ImmutableTypeToInstanceMap or MutableTypeToInstanceMap")
@ElementTypesAreNonnullByDefault
-public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
+public interface TypeToInstanceMap<B extends @Nullable Object>
+ extends Map<TypeToken<? extends @NonNull B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no entry for this class
@@ -54,7 +54,7 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
* getInstance(TypeToken.of(Foo.class))}.
*/
@CheckForNull
- <T extends B> T getInstance(Class<T> type);
+ <T extends @NonNull B> T getInstance(Class<T> type);
/**
* Returns the value the specified type is mapped to, or {@code null} if no entry for this type is
@@ -62,7 +62,7 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
* may have been bound to a subtype.
*/
@CheckForNull
- <T extends B> T getInstance(TypeToken<T> type);
+ <T extends @NonNull B> T getInstance(TypeToken<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate this value with any
@@ -76,7 +76,7 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
*/
@CanIgnoreReturnValue
@CheckForNull
- <T extends B> T putInstance(Class<T> type, T value);
+ <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value);
/**
* Maps the specified type to the specified value. Does <i>not</i> associate this value with any
@@ -87,5 +87,5 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
*/
@CanIgnoreReturnValue
@CheckForNull
- <T extends B> T putInstance(TypeToken<T> type, T value);
+ <T extends B> T putInstance(TypeToken<@NonNull T> type, @ParametricNullness T value);
}
diff --git a/android/guava/src/com/google/common/reflect/TypeToken.java b/android/guava/src/com/google/common/reflect/TypeToken.java
index fea1d53a2..6ac3385e8 100644
--- a/android/guava/src/com/google/common/reflect/TypeToken.java
+++ b/android/guava/src/com/google/common/reflect/TypeToken.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
@@ -32,6 +31,7 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
@@ -89,7 +89,7 @@ import javax.annotation.CheckForNull;
*
* <p>{@code TypeToken} is serializable when no type variable is contained in the type.
*
- * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class except
+ * <p>Note to Guice users: {@code TypeToken} is similar to Guice's {@code TypeLiteral} class except
* that it is serializable and offers numerous additional utility methods.
*
* @author Bob Lee
@@ -104,10 +104,10 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
private final Type runtimeType;
/** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */
- @CheckForNull private transient TypeResolver invariantTypeResolver;
+ @LazyInit @CheckForNull private transient TypeResolver invariantTypeResolver;
/** Resolver for resolving covariant types with {@link #runtimeType} as context. */
- @CheckForNull private transient TypeResolver covariantTypeResolver;
+ @LazyInit @CheckForNull private transient TypeResolver covariantTypeResolver;
/**
* Constructs a new type token of {@code T}.
@@ -590,7 +590,6 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
*
* @since 14.0
*/
- @Beta
public final Invokable<T, Object> method(Method method) {
checkArgument(
this.someRawTypeIsSubclassOf(method.getDeclaringClass()),
@@ -630,7 +629,6 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
*
* @since 14.0
*/
- @Beta
public final Invokable<T, T> constructor(Constructor<?> constructor) {
checkArgument(
constructor.getDeclaringClass() == getRawType(),
@@ -1316,7 +1314,7 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
}
/**
- * Collects parent types from a sub type.
+ * Collects parent types from a subtype.
*
* @param <K> The type "kind". Either a TypeToken, or Class.
*/
diff --git a/android/guava/src/com/google/common/reflect/Types.java b/android/guava/src/com/google/common/reflect/Types.java
index e69b42a8e..7a1357d66 100644
--- a/android/guava/src/com/google/common/reflect/Types.java
+++ b/android/guava/src/com/google/common/reflect/Types.java
@@ -160,7 +160,7 @@ final class Types {
}
/**
- * Returns human readable string representation of {@code type}.
+ * Returns a human-readable string representation of {@code type}.
*
* <p>The format is subject to change.
*/
diff --git a/android/guava/src/com/google/common/reflect/package-info.java b/android/guava/src/com/google/common/reflect/package-info.java
index 6b6047169..1fc793e2a 100644
--- a/android/guava/src/com/google/common/reflect/package-info.java
+++ b/android/guava/src/com/google/common/reflect/package-info.java
@@ -13,8 +13,8 @@
*/
/**
- * This package contains utilities to work with Java reflection. It is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Utilities for reflection. This package is a part of the open-source <a
+ * href="https://github.com/google/guava">Guava</a> library.
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java b/android/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
index 76eada214..e5df53835 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
@@ -19,6 +19,7 @@ import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.MoreExecutors.rejectionPropagatingExecutor;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.util.concurrent.Platform.isInstanceOfThrowableClass;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
@@ -107,7 +108,7 @@ abstract class AbstractCatchingFuture<
+ e.getClass()
+ " without a cause");
}
- } catch (Throwable e) { // this includes cancellation exception
+ } catch (RuntimeException | Error e) { // this includes cancellation exception
throwable = e;
}
@@ -132,6 +133,7 @@ abstract class AbstractCatchingFuture<
try {
fallbackResult = doFallback(localFallback, castThrowable);
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
setException(t);
return;
} finally {
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java b/android/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
index 0dbafd3f8..b06647ea3 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
@@ -14,9 +14,10 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
+
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Supplier;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
@@ -33,6 +34,7 @@ import java.util.logging.Logger;
* @since 1.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractExecutionThreadService implements Service {
private static final Logger logger =
@@ -43,49 +45,41 @@ public abstract class AbstractExecutionThreadService implements Service {
new AbstractService() {
@Override
protected final void doStart() {
- Executor executor =
- MoreExecutors.renamingDecorator(
- executor(),
- new Supplier<String>() {
- @Override
- public String get() {
- return serviceName();
- }
- });
+ Executor executor = MoreExecutors.renamingDecorator(executor(), () -> serviceName());
executor.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- startUp();
- notifyStarted();
- // If stopAsync() is called while starting we may be in the STOPPING state in
- // which case we should skip right down to shutdown.
- if (isRunning()) {
+ () -> {
+ try {
+ startUp();
+ notifyStarted();
+ // If stopAsync() is called while starting we may be in the STOPPING state in
+ // which case we should skip right down to shutdown.
+ if (isRunning()) {
+ try {
+ AbstractExecutionThreadService.this.run();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
try {
- AbstractExecutionThreadService.this.run();
- } catch (Throwable t) {
- try {
- shutDown();
- } catch (Exception ignored) {
- // TODO(lukes): if guava ever moves to java7, this would be a good
- // candidate for a suppressed exception, or maybe we could generalize
- // Closer.Suppressor
- logger.log(
- Level.WARNING,
- "Error while attempting to shut down the service after failure.",
- ignored);
- }
- notifyFailed(t);
- return;
+ shutDown();
+ } catch (Exception ignored) {
+ restoreInterruptIfIsInterruptedException(ignored);
+ // TODO(lukes): if guava ever moves to java7, this would be a good
+ // candidate for a suppressed exception, or maybe we could generalize
+ // Closer.Suppressor
+ logger.log(
+ Level.WARNING,
+ "Error while attempting to shut down the service after failure.",
+ ignored);
}
+ notifyFailed(t);
+ return;
}
-
- shutDown();
- notifyStopped();
- } catch (Throwable t) {
- notifyFailed(t);
}
+
+ shutDown();
+ notifyStopped();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -147,7 +141,6 @@ public abstract class AbstractExecutionThreadService implements Service {
* implementing {@code stopping}. Note, however, that {@code stopping} does not run at exactly the
* same times as {@code triggerShutdown}.
*/
- @Beta
protected void triggerShutdown() {}
/**
@@ -161,12 +154,7 @@ public abstract class AbstractExecutionThreadService implements Service {
* to the string returned by {@link #serviceName}
*/
protected Executor executor() {
- return new Executor() {
- @Override
- public void execute(Runnable command) {
- MoreExecutors.newThread(serviceName(), command).start();
- }
- };
+ return command -> MoreExecutors.newThread(serviceName(), command).start();
}
@Override
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractFuture.java b/android/guava/src/com/google/common/util/concurrent/AbstractFuture.java
index 3e08045d9..6dc7a6b39 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractFuture.java
@@ -15,14 +15,12 @@
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedNull;
import static java.lang.Integer.toHexString;
import static java.lang.System.identityHashCode;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
@@ -159,7 +157,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
try {
helper = new UnsafeAtomicHelper();
- } catch (Throwable unsafeFailure) {
+ } catch (RuntimeException | Error unsafeFailure) {
thrownUnsafeFailure = unsafeFailure;
// catch absolutely everything and fall through to our 'SafeAtomicHelper'
// The access control checks that ARFU does means the caller class has to be AbstractFuture
@@ -172,7 +170,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
newUpdater(AbstractFuture.class, Waiter.class, "waiters"),
newUpdater(AbstractFuture.class, Listener.class, "listeners"),
newUpdater(AbstractFuture.class, Object.class, "value"));
- } catch (Throwable atomicReferenceFieldUpdaterFailure) {
+ } catch (RuntimeException | Error atomicReferenceFieldUpdaterFailure) {
// Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause
// getDeclaredField to throw a NoSuchFieldException when the field is definitely there.
// For these users fallback to a suboptimal implementation, based on synchronized. This will
@@ -357,7 +355,13 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
}
Object valueToSet = getFutureValue(future);
if (ATOMIC_HELPER.casValue(owner, this, valueToSet)) {
- complete(owner);
+ complete(
+ owner,
+ /*
+ * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so
+ * don't invoke interruptTask.
+ */
+ false);
}
}
}
@@ -401,7 +405,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
// Timed Get
// There are a few design constraints to consider
// * We want to be responsive to small timeouts, unpark() has non trivial latency overheads (I
- // have observed 12 micros on 64 bit linux systems to wake up a parked thread). So if the
+ // have observed 12 micros on 64-bit linux systems to wake up a parked thread). So if the
// timeout is small we shouldn't park(). This needs to be traded off with the cpu overhead of
// spinning, so we use SPIN_THRESHOLD_NANOS which is what AbstractQueuedSynchronizer uses for
// similar purposes.
@@ -657,12 +661,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
while (true) {
if (ATOMIC_HELPER.casValue(abstractFuture, localValue, valueToSet)) {
rValue = true;
- // We call interruptTask before calling complete(), which is consistent with
- // FutureTask
- if (mayInterruptIfRunning) {
- abstractFuture.interruptTask();
- }
- complete(abstractFuture);
+ complete(abstractFuture, mayInterruptIfRunning);
if (localValue instanceof SetFuture) {
// propagate cancellation to the future set in setfuture, this is racy, and we don't
// care if we are successful or not.
@@ -780,7 +779,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
protected boolean set(@ParametricNullness V value) {
Object valueToSet = value == null ? NULL : value;
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
- complete(this);
+ complete(this, /*callInterruptTask=*/ false);
return true;
}
return false;
@@ -805,7 +804,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
protected boolean setException(Throwable throwable) {
Object valueToSet = new Failure(checkNotNull(throwable));
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
- complete(this);
+ complete(this, /*callInterruptTask=*/ false);
return true;
}
return false;
@@ -848,7 +847,13 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
if (future.isDone()) {
Object value = getFutureValue(future);
if (ATOMIC_HELPER.casValue(this, null, value)) {
- complete(this);
+ complete(
+ this,
+ /*
+ * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so
+ * don't invoke interruptTask.
+ */
+ false);
return true;
}
return false;
@@ -859,14 +864,14 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
// since all we are doing is unpacking a completed future which should be fast.
try {
future.addListener(valueToSet, DirectExecutor.INSTANCE);
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
// addListener has thrown an exception! SetFuture.run can't throw any exceptions so this
// must have been caused by addListener itself. The most likely explanation is a
// misconfigured mock. Try to switch to Failure.
Failure failure;
try {
failure = new Failure(t);
- } catch (Throwable oomMostLikely) {
+ } catch (RuntimeException | Error oomMostLikely) {
failure = Failure.FALLBACK_INSTANCE;
}
// Note: The only way this CAS could fail is if cancel() has raced with us. That is ok.
@@ -961,7 +966,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
cancellation));
}
return new Cancellation(false, cancellation);
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
return new Failure(t);
}
}
@@ -990,7 +995,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
}
/** Unblocks all threads and runs all listeners. */
- private static void complete(AbstractFuture<?> param) {
+ private static void complete(AbstractFuture<?> param, boolean callInterruptTask) {
// Declare a "true" local variable so that the Checker Framework will infer nullness.
AbstractFuture<?> future = param;
@@ -998,6 +1003,18 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
outer:
while (true) {
future.releaseWaiters();
+ /*
+ * We call interruptTask() immediately before afterDone() so that migrating between the two
+ * can be a no-op.
+ */
+ if (callInterruptTask) {
+ future.interruptTask();
+ /*
+ * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so don't
+ * invoke interruptTask on any subsequent futures.
+ */
+ callInterruptTask = false;
+ }
// We call this before the listeners in order to avoid needing to manage a separate stack data
// structure for them. Also, some implementations rely on this running prior to listeners
// so that the cleanup work is visible to listeners.
@@ -1029,7 +1046,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
continue outer;
}
}
- // other wise the future we were trying to set is already done.
+ // otherwise the future we were trying to set is already done.
} else {
/*
* requireNonNull is safe because the listener stack never contains TOMBSTONE until after
@@ -1053,7 +1070,6 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
*
* @since 20.0
*/
- @Beta
@ForOverride
protected void afterDone() {}
@@ -1120,7 +1136,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
@CheckForNull
private Listener clearListeners(@CheckForNull Listener onto) {
// We need to
- // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that to
+ // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that
// to synchronize with us
// 2. reverse the linked list, because despite our rather clear contract, people depend on us
// executing listeners in the order they were added
@@ -1152,7 +1168,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
} else if (isDone()) {
addDoneString(builder);
} else {
- addPendingString(builder); // delegates to addDoneString if future completes mid-way
+ addPendingString(builder); // delegates to addDoneString if future completes midway
}
return builder.append("]").toString();
}
@@ -1280,10 +1296,10 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
}
private abstract static class AtomicHelper {
- /** Non volatile write of the thread to the {@link Waiter#thread} field. */
+ /** Non-volatile write of the thread to the {@link Waiter#thread} field. */
abstract void putThread(Waiter waiter, Thread newValue);
- /** Non volatile write of the waiter to the {@link Waiter#next} field. */
+ /** Non-volatile write of the waiter to the {@link Waiter#next} field. */
abstract void putNext(Waiter waiter, @CheckForNull Waiter newValue);
/** Performs a CAS operation on the {@link #waiters} field. */
@@ -1353,9 +1369,10 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread"));
WAITER_NEXT_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("next"));
UNSAFE = unsafe;
- } catch (Exception e) {
- throwIfUnchecked(e);
+ } catch (NoSuchFieldException e) {
throw new RuntimeException(e);
+ } catch (RuntimeException e) {
+ throw e;
}
}
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractIdleService.java b/android/guava/src/com/google/common/util/concurrent/AbstractIdleService.java
index 05bc4b9a7..0bf690a56 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractIdleService.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractIdleService.java
@@ -14,7 +14,10 @@
package com.google.common.util.concurrent;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
+
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Supplier;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
@@ -25,12 +28,13 @@ import java.util.concurrent.TimeoutException;
/**
* Base class for services that do not need a thread while "running" but may need one during startup
* and shutdown. Subclasses can implement {@link #startUp} and {@link #shutDown} methods, each which
- * run in a executor which by default uses a separate thread for each method.
+ * run in an executor which by default uses a separate thread for each method.
*
* @author Chris Nokleberg
* @since 1.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractIdleService implements Service {
@@ -54,15 +58,13 @@ public abstract class AbstractIdleService implements Service {
protected final void doStart() {
MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- startUp();
- notifyStarted();
- } catch (Throwable t) {
- notifyFailed(t);
- }
+ () -> {
+ try {
+ startUp();
+ notifyStarted();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -71,15 +73,13 @@ public abstract class AbstractIdleService implements Service {
protected final void doStop() {
MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- shutDown();
- notifyStopped();
- } catch (Throwable t) {
- notifyFailed(t);
- }
+ () -> {
+ try {
+ shutDown();
+ notifyStopped();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -107,12 +107,7 @@ public abstract class AbstractIdleService implements Service {
* stopped, and should return promptly.
*/
protected Executor executor() {
- return new Executor() {
- @Override
- public void execute(Runnable command) {
- MoreExecutors.newThread(threadNameSupplier.get(), command).start();
- }
- };
+ return command -> MoreExecutors.newThread(threadNameSupplier.get(), command).start();
}
@Override
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java b/android/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java
index fd5c5c911..113665b91 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java
@@ -14,9 +14,10 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.CheckReturnValue;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.RunnableFuture;
@@ -33,37 +34,46 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Chris Povirk
* @since 14.0
*/
-@Beta
-@CanIgnoreReturnValue
+@CheckReturnValue
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractListeningExecutorService extends AbstractExecutorService
implements ListeningExecutorService {
- /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
+ /**
+ * @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0)
+ */
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
protected final <T extends @Nullable Object> RunnableFuture<T> newTaskFor(
Runnable runnable, @ParametricNullness T value) {
return TrustedListenableFutureTask.create(runnable, value);
}
- /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
+ /**
+ * @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0)
+ */
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
protected final <T extends @Nullable Object> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return TrustedListenableFutureTask.create(callable);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public ListenableFuture<?> submit(Runnable task) {
return (ListenableFuture<?>) super.submit(task);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public <T extends @Nullable Object> ListenableFuture<T> submit(
Runnable task, @ParametricNullness T result) {
return (ListenableFuture<T>) super.submit(task, result);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public <T extends @Nullable Object> ListenableFuture<T> submit(Callable<T> task) {
return (ListenableFuture<T>) super.submit(task);
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java b/android/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
index 7288ba53d..0b7d34e6b 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
@@ -18,10 +18,11 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.immediateCancelledFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Supplier;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.WeakOuter;
@@ -98,6 +99,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractScheduledService implements Service {
private static final Logger logger = Logger.getLogger(AbstractScheduledService.class.getName());
@@ -202,9 +204,11 @@ public abstract class AbstractScheduledService implements Service {
}
AbstractScheduledService.this.runOneIteration();
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
try {
shutDown();
} catch (Exception ignored) {
+ restoreInterruptIfIsInterruptedException(ignored);
logger.log(
Level.WARNING,
"Error while attempting to shut down the service after failure.",
@@ -224,32 +228,28 @@ public abstract class AbstractScheduledService implements Service {
@Override
protected final void doStart() {
executorService =
- MoreExecutors.renamingDecorator(
- executor(),
- new Supplier<String>() {
- @Override
- public String get() {
- return serviceName() + " " + state();
- }
- });
+ MoreExecutors.renamingDecorator(executor(), () -> serviceName() + " " + state());
executorService.execute(
- new Runnable() {
- @Override
- public void run() {
- lock.lock();
- try {
- startUp();
- runningTask = scheduler().schedule(delegate, executorService, task);
- notifyStarted();
- } catch (Throwable t) {
- notifyFailed(t);
- if (runningTask != null) {
- // prevent the task from running if possible
- runningTask.cancel(false);
- }
- } finally {
- lock.unlock();
+ () -> {
+ lock.lock();
+ try {
+ startUp();
+ /*
+ * requireNonNull is safe because executorService is never cleared after the
+ * assignment above.
+ */
+ requireNonNull(executorService);
+ runningTask = scheduler().schedule(delegate, executorService, task);
+ notifyStarted();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
+ if (runningTask != null) {
+ // prevent the task from running if possible
+ runningTask.cancel(false);
}
+ } finally {
+ lock.unlock();
}
});
}
@@ -261,27 +261,25 @@ public abstract class AbstractScheduledService implements Service {
requireNonNull(executorService);
runningTask.cancel(false);
executorService.execute(
- new Runnable() {
- @Override
- public void run() {
+ () -> {
+ try {
+ lock.lock();
try {
- lock.lock();
- try {
- if (state() != State.STOPPING) {
- // This means that the state has changed since we were scheduled. This implies
- // that an execution of runOneIteration has thrown an exception and we have
- // transitioned to a failed state, also this means that shutDown has already
- // been called, so we do not want to call it again.
- return;
- }
- shutDown();
- } finally {
- lock.unlock();
+ if (state() != State.STOPPING) {
+ // This means that the state has changed since we were scheduled. This implies
+ // that an execution of runOneIteration has thrown an exception and we have
+ // transitioned to a failed state, also this means that shutDown has already
+ // been called, so we do not want to call it again.
+ return;
}
- notifyStopped();
- } catch (Throwable t) {
- notifyFailed(t);
+ shutDown();
+ } finally {
+ lock.unlock();
}
+ notifyStopped();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -347,7 +345,7 @@ public abstract class AbstractScheduledService implements Service {
}
final ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl());
- // Add a listener to shutdown the executor after the service is stopped. This ensures that the
+ // Add a listener to shut down the executor after the service is stopped. This ensures that the
// JVM shutdown will not be prevented from exiting after this service has stopped or failed.
// Technically this listener is added after start() was called so it is a little gross, but it
// is called within doStart() so we know that the service cannot terminate or fail concurrently
@@ -553,6 +551,7 @@ public abstract class AbstractScheduledService implements Service {
try {
schedule = CustomScheduler.this.getNextSchedule();
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
service.notifyFailed(t);
return new FutureAsCancellable(immediateCancelledFuture());
}
@@ -565,7 +564,7 @@ public abstract class AbstractScheduledService implements Service {
lock.lock();
try {
toReturn = initializeOrUpdateCancellationDelegate(schedule);
- } catch (Throwable e) {
+ } catch (RuntimeException | Error e) {
// If an exception is thrown by the subclass then we need to make sure that the service
// notices and transitions to the FAILED state. We do it by calling notifyFailed directly
// because the service does not monitor the state of the future so if the exception is not
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractService.java b/android/guava/src/com/google/common/util/concurrent/AbstractService.java
index 1cf31bf91..6ead7b4de 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractService.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractService.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import static com.google.common.util.concurrent.Service.State.FAILED;
import static com.google.common.util.concurrent.Service.State.NEW;
import static com.google.common.util.concurrent.Service.State.RUNNING;
@@ -25,8 +26,8 @@ import static com.google.common.util.concurrent.Service.State.STOPPING;
import static com.google.common.util.concurrent.Service.State.TERMINATED;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.util.concurrent.Monitor.Guard;
import com.google.common.util.concurrent.Service.State; // javadoc needs this
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -49,6 +50,7 @@ import javax.annotation.CheckForNull;
* @since 1.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractService implements Service {
private static final ListenerCallQueue.Event<Listener> STARTING_EVENT =
@@ -236,7 +238,6 @@ public abstract class AbstractService implements Service {
*
* @since 27.0
*/
- @Beta
@ForOverride
protected void doCancelStart() {}
@@ -249,6 +250,7 @@ public abstract class AbstractService implements Service {
enqueueStartingEvent();
doStart();
} catch (Throwable startupFailure) {
+ restoreInterruptIfIsInterruptedException(startupFailure);
notifyFailed(startupFailure);
} finally {
monitor.leave();
@@ -288,6 +290,7 @@ public abstract class AbstractService implements Service {
throw new AssertionError("isStoppable is incorrectly implemented, saw: " + previous);
}
} catch (Throwable shutdownFailure) {
+ restoreInterruptIfIsInterruptedException(shutdownFailure);
notifyFailed(shutdownFailure);
} finally {
monitor.leave();
@@ -316,7 +319,7 @@ public abstract class AbstractService implements Service {
monitor.leave();
}
} else {
- // It is possible due to races the we are currently in the expected state even though we
+ // It is possible due to races that we are currently in the expected state even though we
// timed out. e.g. if we weren't event able to grab the lock within the timeout we would never
// even check the guard. I don't think we care too much about this use case but it could lead
// to a confusing error message.
@@ -343,7 +346,7 @@ public abstract class AbstractService implements Service {
monitor.leave();
}
} else {
- // It is possible due to races the we are currently in the expected state even though we
+ // It is possible due to races that we are currently in the expected state even though we
// timed out. e.g. if we weren't event able to grab the lock within the timeout we would never
// even check the guard. I don't think we care too much about this use case but it could lead
// to a confusing error message.
diff --git a/android/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java b/android/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
index dd6879159..5581b5fae 100644
--- a/android/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.MoreExecutors.rejectionPropagatingExecutor;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
@@ -121,6 +122,7 @@ abstract class AbstractTransformFuture<
try {
transformResult = doTransform(localFunction, sourceResult);
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
// This exception is irrelevant in this thread, but useful for the client.
setException(t);
return;
diff --git a/android/guava/src/com/google/common/util/concurrent/AggregateFuture.java b/android/guava/src/com/google/common/util/concurrent/AggregateFuture.java
index 6d2ed9c8e..ec96cbb89 100644
--- a/android/guava/src/com/google/common/util/concurrent/AggregateFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/AggregateFuture.java
@@ -268,7 +268,7 @@ abstract class AggregateFuture<InputT extends @Nullable Object, OutputT extends
collectOneValue(index, getDone(future));
} catch (ExecutionException e) {
handleException(e.getCause());
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
handleException(t);
}
}
@@ -357,7 +357,7 @@ abstract class AggregateFuture<InputT extends @Nullable Object, OutputT extends
* We've seen this, so we've seen its causes, too. No need to re-add them. (There's one case
* where this isn't true, but we ignore it: If we record an exception, then someone calls
* initCause() on it, and then we examine it again, we'll conclude that we've seen the whole
- * chain before when it fact we haven't. But this should be rare.)
+ * chain before when in fact we haven't. But this should be rare.)
*/
return false;
}
diff --git a/android/guava/src/com/google/common/util/concurrent/AggregateFutureState.java b/android/guava/src/com/google/common/util/concurrent/AggregateFutureState.java
index ee23ca021..7bdec0135 100644
--- a/android/guava/src/com/google/common/util/concurrent/AggregateFutureState.java
+++ b/android/guava/src/com/google/common/util/concurrent/AggregateFutureState.java
@@ -61,7 +61,7 @@ abstract class AggregateFutureState<OutputT extends @Nullable Object>
new SafeAtomicHelper(
newUpdater(AggregateFutureState.class, Set.class, "seenExceptions"),
newUpdater(AggregateFutureState.class, "remaining"));
- } catch (Throwable reflectionFailure) {
+ } catch (RuntimeException | Error reflectionFailure) {
// Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause
// getDeclaredField to throw a NoSuchFieldException when the field is definitely there.
// For these users fallback to a suboptimal implementation, based on synchronized. This will
diff --git a/android/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java b/android/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
index fc8deed3b..b03fba527 100644
--- a/android/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
+++ b/android/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
@@ -17,6 +17,7 @@ import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.ImmutableLongArray;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.atomic.AtomicLongArray;
@@ -44,6 +45,7 @@ import java.util.concurrent.atomic.AtomicLongArray;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public class AtomicDoubleArray implements java.io.Serializable {
private static final long serialVersionUID = 0L;
diff --git a/android/guava/src/com/google/common/util/concurrent/AtomicLongMap.java b/android/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
index bac02c143..33f08298c 100644
--- a/android/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
+++ b/android/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
@@ -16,11 +16,12 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
@@ -43,6 +44,8 @@ import javax.annotation.CheckForNull;
* <p>Instances of this class may be used by multiple threads concurrently. All operations are
* atomic unless otherwise noted.
*
+ * <p>Instances of this class are serializable if the keys are serializable.
+ *
* <p><b>Note:</b> If your values are always positive and less than 2^31, you may wish to use a
* {@link com.google.common.collect.Multiset} such as {@link
* com.google.common.collect.ConcurrentHashMultiset} instead.
@@ -54,6 +57,7 @@ import javax.annotation.CheckForNull;
* @since 11.0
*/
@GwtCompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class AtomicLongMap<K> implements Serializable {
private final ConcurrentHashMap<K, AtomicLong> map;
@@ -290,7 +294,6 @@ public final class AtomicLongMap<K> implements Serializable {
*
* @since 20.0
*/
- @Beta
@CanIgnoreReturnValue
public boolean removeIfZero(K key) {
return remove(key, 0);
@@ -326,7 +329,7 @@ public final class AtomicLongMap<K> implements Serializable {
return sum;
}
- @CheckForNull private transient Map<K, Long> asMap;
+ @LazyInit @CheckForNull private transient Map<K, Long> asMap;
/** Returns a live, read-only view of the map backing this {@code AtomicLongMap}. */
public Map<K, Long> asMap() {
diff --git a/android/guava/src/com/google/common/util/concurrent/Callables.java b/android/guava/src/com/google/common/util/concurrent/Callables.java
index 3b52c2e98..6a586bb2e 100644
--- a/android/guava/src/com/google/common/util/concurrent/Callables.java
+++ b/android/guava/src/com/google/common/util/concurrent/Callables.java
@@ -16,9 +16,9 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Supplier;
import java.util.concurrent.Callable;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -47,7 +47,7 @@ public final class Callables {
*
* @since 20.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible
public static <T extends @Nullable Object> AsyncCallable<T> asAsyncCallable(
Callable<T> callable, ListeningExecutorService listeningExecutorService) {
@@ -64,6 +64,7 @@ public final class Callables {
* @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
* for each invocation of the wrapped callable.
*/
+ @J2ktIncompatible
@GwtIncompatible // threads
static <T extends @Nullable Object> Callable<T> threadRenaming(
Callable<T> callable, Supplier<String> nameSupplier) {
@@ -91,6 +92,7 @@ public final class Callables {
* @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
* for each invocation of the wrapped callable.
*/
+ @J2ktIncompatible
@GwtIncompatible // threads
static Runnable threadRenaming(Runnable task, Supplier<String> nameSupplier) {
checkNotNull(nameSupplier);
@@ -110,6 +112,7 @@ public final class Callables {
}
/** Tries to set name of the given {@link Thread}, returns true if successful. */
+ @J2ktIncompatible
@GwtIncompatible // threads
private static boolean trySetName(String threadName, Thread currentThread) {
/*
diff --git a/android/guava/src/com/google/common/util/concurrent/ClosingFuture.java b/android/guava/src/com/google/common/util/concurrent/ClosingFuture.java
index b8aec0337..43157c7a4 100644
--- a/android/guava/src/com/google/common/util/concurrent/ClosingFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/ClosingFuture.java
@@ -36,8 +36,8 @@ import static java.util.logging.Level.FINER;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ClosingFuture.Combiner.AsyncCombiningCallable;
@@ -191,6 +191,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/
// TODO(dpb): Consider reusing one CloseableList for the entire pipeline, modulo combinations.
@DoNotMock("Use ClosingFuture.from(Futures.immediate*Future)")
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
// TODO(dpb): GWT compatibility.
public final class ClosingFuture<V extends @Nullable Object> {
@@ -253,7 +254,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -271,7 +272,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -289,7 +290,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to an input, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -307,7 +308,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to an input, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -350,7 +351,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Starts closing all closeable objects captured during the {@link ClosingFuture}'s asynchronous
* operation on the {@link Executor}s specified by calls to {@link
- * DeferredCloser#eventuallyClose(Closeable, Executor)}.
+ * DeferredCloser#eventuallyClose(Object, Executor)}.
*
* <p>If any such calls specified {@link MoreExecutors#directExecutor()}, those objects will be
* closed synchronously.
@@ -412,14 +413,14 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Starts a {@link ClosingFuture} pipeline with a {@link ListenableFuture}.
*
- * <p>If {@code future} succeeds, its value will be closed (using {@code closingExecutor)} when
+ * <p>If {@code future} succeeds, its value will be closed (using {@code closingExecutor)}) when
* the pipeline is done, even if the pipeline is canceled or fails.
*
* <p>Cancelling the pipeline will not cancel {@code future}, so that the pipeline can access its
* value in order to close it.
*
* @param future the future to create the {@code ClosingFuture} from. For discussion of the
- * future's result type {@code C}, see {@link DeferredCloser#eventuallyClose(Closeable,
+ * future's result type {@code C}, see {@link DeferredCloser#eventuallyClose(Object,
* Executor)}.
* @param closingExecutor the future's result will be closed on this executor
* @deprecated Creating {@link Future}s of closeable types is dangerous in general because the
@@ -728,7 +729,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #transform(ClosingFunction,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor) closer.eventuallyClose()}
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
* for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
@@ -809,7 +810,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
*
* <ul>
* <li>It does not need to capture any {@link Closeable} objects by calling {@link
- * DeferredCloser#eventuallyClose(Closeable, Executor)}.
+ * DeferredCloser#eventuallyClose(Object, Executor)}.
* <li>It returns a {@link ListenableFuture}.
* </ul>
*
@@ -926,7 +927,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
* {@code ClosingFuture}. If possible, prefer calling {@link #catching(Class,
* ClosingFunction, Executor)} instead, with a function that returns the next value
* directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor) closer.eventuallyClose()}
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
* for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
@@ -1241,10 +1242,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*
* @param peeker used to get the value of any of the input futures
*/
@@ -1261,10 +1262,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a {@link ClosingFuture} result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*
* @param peeker used to get the value of any of the input futures
*/
@@ -1343,9 +1344,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1379,16 +1379,11 @@ public final class ClosingFuture<V extends @Nullable Object> {
: Futures.whenAllComplete(inputFutures());
}
- private static final Function<ClosingFuture<?>, FluentFuture<?>> INNER_FUTURE =
- new Function<ClosingFuture<?>, FluentFuture<?>>() {
- @Override
- public FluentFuture<?> apply(ClosingFuture<?> future) {
- return future.future;
- }
- };
private ImmutableList<FluentFuture<?>> inputFutures() {
- return FluentIterable.from(inputs).transform(INNER_FUTURE).toList();
+ return FluentIterable.from(inputs)
+ .<FluentFuture<?>>transform(future -> future.future)
+ .toList();
}
}
@@ -1417,10 +1412,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to two inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
@@ -1441,10 +1436,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to two inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
@@ -1517,9 +1512,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1574,10 +1568,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to three inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(
@@ -1605,10 +1599,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to three inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer,
@@ -1691,9 +1685,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1758,10 +1751,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to four inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(
@@ -1793,10 +1786,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to four inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer,
@@ -1886,9 +1879,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1959,10 +1951,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to five inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(
@@ -1997,10 +1989,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to five inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer,
@@ -2097,9 +2089,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -2151,14 +2142,11 @@ public final class ClosingFuture<V extends @Nullable Object> {
}
try {
executor.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- closeable.close();
- } catch (IOException | RuntimeException e) {
- logger.log(WARNING, "thrown by close()", e);
- }
+ () -> {
+ try {
+ closeable.close();
+ } catch (IOException | RuntimeException e) {
+ logger.log(WARNING, "thrown by close()", e);
}
});
} catch (RejectedExecutionException e) {
diff --git a/android/guava/src/com/google/common/util/concurrent/CollectionFuture.java b/android/guava/src/com/google/common/util/concurrent/CollectionFuture.java
index c106c157e..062aee7a7 100644
--- a/android/guava/src/com/google/common/util/concurrent/CollectionFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/CollectionFuture.java
@@ -32,7 +32,7 @@ abstract class CollectionFuture<V extends @Nullable Object, C extends @Nullable
extends AggregateFuture<V, C> {
/*
* We access this field racily but safely. For discussion of a similar situation, see the comments
- * on the fields of TimeoutFuture. This field is slightly different than the fields discussed
+ * on the fields of TimeoutFuture. This field is slightly different from the fields discussed
* there: cancel() never reads this field, only writes to it. That makes the race here completely
* harmless, rather than just 99.99% harmless.
*/
@@ -102,9 +102,9 @@ abstract class CollectionFuture<V extends @Nullable Object, C extends @Nullable
/** The result of a successful {@code Future}. */
private static final class Present<V extends @Nullable Object> {
- V value;
+ @ParametricNullness final V value;
- Present(V value) {
+ Present(@ParametricNullness V value) {
this.value = value;
}
}
diff --git a/android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java b/android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
index decb5f1b1..0ec799cc4 100644
--- a/android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
+++ b/android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
@@ -17,8 +17,8 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
@@ -27,7 +27,6 @@ import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.Weak;
import java.util.ArrayList;
import java.util.Arrays;
@@ -160,8 +159,7 @@ import javax.annotation.CheckForNull;
* @author Darick Tong
* @since 13.0
*/
-@Beta
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class CycleDetectingLockFactory {
@@ -173,7 +171,6 @@ public class CycleDetectingLockFactory {
*
* @since 13.0
*/
- @Beta
public interface Policy {
/**
@@ -193,7 +190,6 @@ public class CycleDetectingLockFactory {
*
* @since 13.0
*/
- @Beta
public enum Policies implements Policy {
/**
* When potential deadlock is detected, this policy results in the throwing of the {@code
@@ -394,7 +390,6 @@ public class CycleDetectingLockFactory {
* @param <E> The Enum type representing the explicit lock ordering.
* @since 13.0
*/
- @Beta
public static final class WithExplicitOrdering<E extends Enum<E>>
extends CycleDetectingLockFactory {
@@ -534,7 +529,6 @@ public class CycleDetectingLockFactory {
*
* @since 13.0
*/
- @Beta
public static final class PotentialDeadlockException extends ExampleStackTrace {
private final ExampleStackTrace conflictingStackTrace;
diff --git a/android/guava/src/com/google/common/util/concurrent/ExecutionError.java b/android/guava/src/com/google/common/util/concurrent/ExecutionError.java
index deaff15a4..303383039 100644
--- a/android/guava/src/com/google/common/util/concurrent/ExecutionError.java
+++ b/android/guava/src/com/google/common/util/concurrent/ExecutionError.java
@@ -33,7 +33,7 @@ public class ExecutionError extends Error {
/*
* Ideally, this class would have exposed only constructors that require a non-null cause. We
* might try to move in that direction, but there are complications. See
- * https://github.com/jspecify/nullness-checker-for-checker-framework/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
+ * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
*/
/** Creates a new instance with {@code null} as its detail message. */
diff --git a/android/guava/src/com/google/common/util/concurrent/ExecutionList.java b/android/guava/src/com/google/common/util/concurrent/ExecutionList.java
index 96fc51ca8..645817c4a 100644
--- a/android/guava/src/com/google/common/util/concurrent/ExecutionList.java
+++ b/android/guava/src/com/google/common/util/concurrent/ExecutionList.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.concurrent.Executor;
import java.util.logging.Level;
@@ -39,6 +40,7 @@ import javax.annotation.CheckForNull;
* @author Sven Mawson
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ExecutionList {
diff --git a/android/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java b/android/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java
index 80c777934..c335711c0 100644
--- a/android/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java
+++ b/android/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java
@@ -25,8 +25,10 @@ import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.Objects.requireNonNull;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
+import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -54,7 +56,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* (However, cancellation can prevent an <i>unstarted</i> task from running.) Therefore, the
* next task will wait for any running callable (or pending {@code Future} returned by an
* {@code AsyncCallable}) to complete, without interrupting it (and without calling {@code
- * cancel} on the {@code Future}). So beware: <i>Even if you cancel every precededing {@code
+ * cancel} on the {@code Future}). So beware: <i>Even if you cancel every preceding {@code
* Future} returned by this class, the next task may still have to wait.</i>.
* <li>Once an {@code AsyncCallable} returns a {@code Future}, this class considers that task to
* be "done" as soon as <i>that</i> {@code Future} completes in any way. Notably, a {@code
@@ -84,6 +86,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 26.0
*/
@ElementTypesAreNonnullByDefault
+@J2ktIncompatible
public final class ExecutionSequencer {
private ExecutionSequencer() {}
@@ -250,7 +253,7 @@ public final class ExecutionSequencer {
taskFuture.cancel(false);
}
};
- // Adding the listener to both futures guarantees that newFuture will aways be set. Adding to
+ // Adding the listener to both futures guarantees that newFuture will always be set. Adding to
// taskFuture guarantees completion if the callable is invoked, and adding to outputFuture
// propagates cancellation if the callable has not yet been invoked.
outputFuture.addListener(listener, directExecutor());
diff --git a/android/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java b/android/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
index ddc944018..1c16cfb14 100644
--- a/android/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
+++ b/android/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
@@ -15,9 +15,10 @@
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -34,11 +35,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jens Nyman
* @since 1.0
*/
-@Beta
-@CanIgnoreReturnValue
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class FakeTimeLimiter implements TimeLimiter {
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public <T> T newProxy(
T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit) {
@@ -48,6 +49,7 @@ public final class FakeTimeLimiter implements TimeLimiter {
return target; // ha ha
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
@ParametricNullness
public <T extends @Nullable Object> T callWithTimeout(
@@ -59,16 +61,14 @@ public final class FakeTimeLimiter implements TimeLimiter {
} catch (RuntimeException e) {
throw new UncheckedExecutionException(e);
} catch (Exception e) {
+ restoreInterruptIfIsInterruptedException(e);
throw new ExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
- } catch (Throwable e) {
- // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend
- // Exception, so we'll treat it like an Exception.
- throw new ExecutionException(e);
}
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
@ParametricNullness
public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
@@ -86,10 +86,6 @@ public final class FakeTimeLimiter implements TimeLimiter {
throw new UncheckedExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
- } catch (Throwable e) {
- // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend
- // Exception, so we'll treat it like a RuntimeException.
- throw new UncheckedExecutionException(e);
}
}
diff --git a/android/guava/src/com/google/common/util/concurrent/FluentFuture.java b/android/guava/src/com/google/common/util/concurrent/FluentFuture.java
index 683944c9e..77b40b0fc 100644
--- a/android/guava/src/com/google/common/util/concurrent/FluentFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/FluentFuture.java
@@ -16,9 +16,9 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
@@ -182,8 +182,8 @@ public abstract class FluentFuture<V extends @Nullable Object>
* {@code get()} throws a different kind of exception, that exception itself.
* @param executor the executor that runs {@code fallback} if the input fails
*/
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
- @Beta
public final <X extends Throwable> FluentFuture<V> catching(
Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor) {
return (FluentFuture<V>) Futures.catching(this, exceptionType, fallback, executor);
@@ -247,8 +247,8 @@ public abstract class FluentFuture<V extends @Nullable Object>
* {@code get()} throws a different kind of exception, that exception itself.
* @param executor the executor that runs {@code fallback} if the input fails
*/
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
- @Beta
public final <X extends Throwable> FluentFuture<V> catchingAsync(
Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) {
return (FluentFuture<V>) Futures.catchingAsync(this, exceptionType, fallback, executor);
@@ -264,9 +264,9 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @param unit the time unit of the time parameter
* @param scheduledExecutor The executor service to enforce the timeout.
*/
+ @J2ktIncompatible
@GwtIncompatible // ScheduledExecutorService
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
- @Beta
public final FluentFuture<V> withTimeout(
long timeout, TimeUnit unit, ScheduledExecutorService scheduledExecutor) {
return (FluentFuture<V>) Futures.withTimeout(this, timeout, unit, scheduledExecutor);
@@ -311,7 +311,6 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @return A future that holds result of the function (if the input succeeded) or the original
* input's failure (if not)
*/
- @Beta
public final <T extends @Nullable Object> FluentFuture<T> transformAsync(
AsyncFunction<? super V, T> function, Executor executor) {
return (FluentFuture<T>) Futures.transformAsync(this, function, executor);
@@ -349,7 +348,6 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @param executor Executor to run the function in.
* @return A future that holds result of the transformation.
*/
- @Beta
public final <T extends @Nullable Object> FluentFuture<T> transform(
Function<? super V, T> function, Executor executor) {
return (FluentFuture<T>) Futures.transform(this, function, executor);
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java b/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java
index d0d72a815..13aa80b51 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java
@@ -17,6 +17,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ForwardingDeque;
import java.util.Collection;
import java.util.concurrent.BlockingDeque;
@@ -44,6 +45,7 @@ import javax.annotation.CheckForNull;
* @author Emily Soldal
* @since 21.0 (since 14.0 as {@link com.google.common.collect.ForwardingBlockingDeque})
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingDeque<E> extends ForwardingDeque<E>
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java b/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
index dc8511d94..79ec94a1e 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ForwardingQueue;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
@@ -36,7 +37,7 @@ import javax.annotation.CheckForNull;
* @param <E> the type of elements held in this collection
* @since 4.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
@@ -48,21 +49,25 @@ public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
@Override
protected abstract BlockingQueue<E> delegate();
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
return delegate().drainTo(c, maxElements);
}
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c) {
return delegate().drainTo(c);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return delegate().offer(e, timeout, unit);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
@CheckForNull
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
@@ -79,6 +84,7 @@ public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
return delegate().remainingCapacity();
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public E take() throws InterruptedException {
return delegate().take();
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingCondition.java b/android/guava/src/com/google/common/util/concurrent/ForwardingCondition.java
index d17f98cf2..885cca7fc 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingCondition.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingCondition.java
@@ -14,11 +14,13 @@
package com.google.common.util.concurrent;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
/** Forwarding wrapper around a {@code Condition}. */
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
abstract class ForwardingCondition implements Condition {
abstract Condition delegate();
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java b/android/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
index ed78b8685..986278daf 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
@@ -15,8 +15,10 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ForwardingObject;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.CheckReturnValue;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
@@ -32,10 +34,14 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* should override one or more methods to modify the behavior of the backing executor service as
* desired per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
+ * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
+ * default} methods. Instead, it inherits their default implementations. When those implementations
+ * invoke methods, they invoke methods on the {@code ForwardingExecutorService}.
+ *
* @author Kurt Alfred Kluever
* @since 10.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingExecutorService extends ForwardingObject
@@ -46,6 +52,7 @@ public abstract class ForwardingExecutorService extends ForwardingObject
@Override
protected abstract ExecutorService delegate();
+ @CheckReturnValue
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return delegate().awaitTermination(timeout, unit);
@@ -93,6 +100,7 @@ public abstract class ForwardingExecutorService extends ForwardingObject
}
@Override
+ @CanIgnoreReturnValue
public List<Runnable> shutdownNow() {
return delegate().shutdownNow();
}
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingFuture.java b/android/guava/src/com/google/common/util/concurrent/ForwardingFuture.java
index 47002b03a..635c4f6eb 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingFuture.java
@@ -34,7 +34,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Sven Mawson
* @since 1.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
@GwtCompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingFuture<V extends @Nullable Object> extends ForwardingObject
@@ -46,6 +45,7 @@ public abstract class ForwardingFuture<V extends @Nullable Object> extends Forwa
protected abstract Future<? extends V> delegate();
@Override
+ @CanIgnoreReturnValue
public boolean cancel(boolean mayInterruptIfRunning) {
return delegate().cancel(mayInterruptIfRunning);
}
@@ -61,12 +61,14 @@ public abstract class ForwardingFuture<V extends @Nullable Object> extends Forwa
}
@Override
+ @CanIgnoreReturnValue
@ParametricNullness
public V get() throws InterruptedException, ExecutionException {
return delegate().get();
}
@Override
+ @CanIgnoreReturnValue
@ParametricNullness
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java b/android/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
index 386809194..ccd2dd7b1 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
@@ -16,7 +16,6 @@ package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -30,7 +29,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Shardul Deo
* @since 4.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
@GwtCompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingListenableFuture<V extends @Nullable Object>
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java b/android/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
index fe25b867a..25dbf0de7 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
@@ -15,7 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -25,10 +25,14 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* executor service as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
+ * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
+ * default} methods. Instead, it inherits their default implementations. When those implementations
+ * invoke methods, they invoke methods on the {@code ForwardingListeningExecutorService}.
+ *
* @author Isaac Shum
* @since 10.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingListeningExecutorService extends ForwardingExecutorService
diff --git a/android/guava/src/com/google/common/util/concurrent/ForwardingLock.java b/android/guava/src/com/google/common/util/concurrent/ForwardingLock.java
index db2026ab4..558b6e3de 100644
--- a/android/guava/src/com/google/common/util/concurrent/ForwardingLock.java
+++ b/android/guava/src/com/google/common/util/concurrent/ForwardingLock.java
@@ -14,11 +14,13 @@
package com.google.common.util.concurrent;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/** Forwarding wrapper around a {@code Lock}. */
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
abstract class ForwardingLock implements Lock {
abstract Lock delegate();
diff --git a/android/guava/src/com/google/common/util/concurrent/Futures.java b/android/guava/src/com/google/common/util/concurrent/Futures.java
index 6bd68b4b5..39b6dfeb7 100644
--- a/android/guava/src/com/google/common/util/concurrent/Futures.java
+++ b/android/guava/src/com/google/common/util/concurrent/Futures.java
@@ -20,9 +20,9 @@ import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
@@ -104,7 +104,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
// (hypothetical) unsafe read by our caller. Note: adding 'volatile' does not fix this issue,
// it would just add an edge such that if done() observed non-null, then it would also
// definitely observe all earlier writes, but we still have no guarantee that done() would see
- // the inital write (just stronger guarantees if it does).
+ // the initial write (just stronger guarantees if it does).
//
// See: http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013800.html
// For a (long) discussion about this specific issue and the general futility of life.
@@ -223,6 +223,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @throws RejectedExecutionException if the task cannot be scheduled for execution
* @since 23.0
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
// TODO(cpovirk): Return ListenableScheduledFuture?
@@ -232,16 +233,12 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
TimeUnit timeUnit,
ScheduledExecutorService executorService) {
TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
- final Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
- task.addListener(
- new Runnable() {
- @Override
- public void run() {
- // Don't want to interrupt twice
- scheduled.cancel(false);
- }
- },
- directExecutor());
+ Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
+ /*
+ * Even when the user interrupts the task, we pass `false` to `cancel` so that we don't
+ * interrupt a second time after the interruption performed by TrustedListenableFutureTask.
+ */
+ task.addListener(() -> scheduled.cancel(false), directExecutor());
return task;
}
@@ -281,7 +278,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @param executor the executor that runs {@code fallback} if {@code input} fails
* @since 19.0
*/
- @Beta
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catching(
ListenableFuture<? extends V> input,
@@ -346,7 +343,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @param executor the executor that runs {@code fallback} if {@code input} fails
* @since 19.0 (similar functionality in 14.0 as {@code withFallback})
*/
- @Beta
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catchingAsync(
ListenableFuture<? extends V> input,
@@ -363,12 +360,11 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* <p>The delegate future is interrupted and cancelled if it times out.
*
* @param delegate The future to delegate to.
- * @param time when to timeout the future
* @param unit the time unit of the time parameter
* @param scheduledExecutor The executor service to enforce the timeout.
* @since 19.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
@@ -414,7 +410,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* input's failure (if not)
* @since 19.0 (in 11.0 as {@code transform})
*/
- @Beta
public static <I extends @Nullable Object, O extends @Nullable Object>
ListenableFuture<O> transformAsync(
ListenableFuture<I> input,
@@ -452,7 +447,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return A future that holds result of the transformation.
* @since 9.0 (in 2.0 as {@code compose})
*/
- @Beta
public static <I extends @Nullable Object, O extends @Nullable Object>
ListenableFuture<O> transform(
ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
@@ -479,7 +473,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return A future that returns the result of the transformation.
* @since 10.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static <I extends @Nullable Object, O extends @Nullable Object> Future<O> lazyTransform(
final Future<I> input, final Function<? super I, ? extends O> function) {
@@ -516,7 +510,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
private O applyTransformation(I input) throws ExecutionException {
try {
return function.apply(input);
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
throw new ExecutionException(t);
}
}
@@ -539,7 +533,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
ListenableFuture<? extends V>... futures) {
@@ -567,7 +560,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
ListenableFuture<List<@Nullable V>> nullable =
@@ -586,7 +578,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
ListenableFuture<? extends V>... futures) {
@@ -601,7 +592,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
@@ -614,7 +604,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
ListenableFuture<? extends V>... futures) {
@@ -628,7 +617,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
@@ -660,8 +648,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
- @CanIgnoreReturnValue // TODO(cpovirk): Consider removing, especially if we provide run(Runnable)
@GwtCompatible
public static final class FutureCombiner<V extends @Nullable Object> {
private final boolean allMustSucceed;
@@ -686,6 +672,12 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* ExecutionException} that gets thrown by the returned combined future.
*
* <p>Canceling this future will attempt to cancel all the component futures.
+ *
+ * @return a future whose result is based on {@code combiner} (or based on the input futures
+ * passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
+ * FutureCombiner}). Even if you don't care about the value of the future, you should
+ * typically check whether it failed: See <a
+ * href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
*/
public <C extends @Nullable Object> ListenableFuture<C> callAsync(
AsyncCallable<C> combiner, Executor executor) {
@@ -705,8 +697,13 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* ExecutionException} that gets thrown by the returned combined future.
*
* <p>Canceling this future will attempt to cancel all the component futures.
+ *
+ * @return a future whose result is based on {@code combiner} (or based on the input futures
+ * passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
+ * FutureCombiner}). Even if you don't care about the value of the future, you should
+ * typically check whether it failed: See <a
+ * href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Remove this
public <C extends @Nullable Object> ListenableFuture<C> call(
Callable<C> combiner, Executor executor) {
return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
@@ -722,6 +719,11 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* <p>Canceling this Future will attempt to cancel all the component futures.
*
* @since 23.6
+ * @return a future whose result is based on {@code combiner} (or based on the input futures
+ * passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
+ * FutureCombiner}). Even though the future never produces a value other than {@code null},
+ * you should typically check whether it failed: See <a
+ * href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
*/
public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
return call(
@@ -807,7 +809,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
ListenableFuture<? extends V>... futures) {
@@ -844,7 +845,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), false);
@@ -884,14 +884,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
for (int i = 0; i < copy.length; i++) {
final int localI = i;
- copy[i].addListener(
- new Runnable() {
- @Override
- public void run() {
- state.recordInputCompletion(delegates, localI);
- }
- },
- directExecutor());
+ copy[i].addListener(() -> state.recordInputCompletion(delegates, localI), directExecutor());
}
@SuppressWarnings("unchecked")
@@ -1190,8 +1183,8 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* does not have a suitable constructor
* @since 19.0 (in 10.0 as {@code get})
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // reflection
@ParametricNullness
public static <V extends @Nullable Object, X extends Exception> V getChecked(
@@ -1242,8 +1235,8 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* does not have a suitable constructor
* @since 19.0 (in 10.0 as {@code get} and with different parameter order)
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // reflection
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@ParametricNullness
diff --git a/android/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java b/android/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
index 04564f3a0..9be9e21e8 100644
--- a/android/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
+++ b/android/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
@@ -19,6 +19,7 @@ import static java.lang.Thread.currentThread;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
@@ -38,6 +39,7 @@ import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Static methods used to implement {@link Futures#getChecked(Future, Class)}. */
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class FuturesGetChecked {
@@ -182,7 +184,7 @@ final class FuturesGetChecked {
try {
Exception unused = newWithCause(exceptionClass, new Exception());
return true;
- } catch (Exception e) {
+ } catch (RuntimeException | Error e) {
return false;
}
}
@@ -215,12 +217,8 @@ final class FuturesGetChecked {
private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST =
Ordering.natural()
.onResultOf(
- new Function<Constructor<?>, Boolean>() {
- @Override
- public Boolean apply(Constructor<?> input) {
- return asList(input.getParameterTypes()).contains(String.class);
- }
- })
+ (Function<Constructor<?>, Boolean>)
+ input -> asList(input.getParameterTypes()).contains(String.class))
.reverse();
@CheckForNull
diff --git a/android/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java b/android/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
index d29a673dd..fdbe50909 100644
--- a/android/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
+++ b/android/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -23,6 +24,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* FluentFuture.catching} family of methods. Those versions have slightly different signatures.
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible // Super-sourced
@ElementTypesAreNonnullByDefault
abstract class GwtFluentFutureCatchingSpecialization<V extends @Nullable Object>
extends AbstractFuture<V> {
diff --git a/android/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java b/android/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
index 95131cec3..35adfdb67 100644
--- a/android/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
+++ b/android/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
/**
* Hidden superclass of {@link Futures} that provides us a place to declare special GWT versions of
@@ -23,6 +24,7 @@ import com.google.common.annotations.GwtCompatible;
* different signatures.
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible // Super-sourced
@ElementTypesAreNonnullByDefault
abstract class GwtFuturesCatchingSpecialization {
/*
diff --git a/android/guava/src/com/google/common/util/concurrent/ImmediateFuture.java b/android/guava/src/com/google/common/util/concurrent/ImmediateFuture.java
index 8b1c17ae4..f09816c4e 100644
--- a/android/guava/src/com/google/common/util/concurrent/ImmediateFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/ImmediateFuture.java
@@ -23,6 +23,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Implementation of {@link Futures#immediateFuture}. */
@@ -98,7 +99,8 @@ class ImmediateFuture<V extends @Nullable Object> implements ListenableFuture<V>
}
static final class ImmediateCancelledFuture<V extends @Nullable Object> extends TrustedFuture<V> {
- static final @Nullable ImmediateCancelledFuture<Object> INSTANCE =
+ @CheckForNull
+ static final ImmediateCancelledFuture<Object> INSTANCE =
AbstractFuture.GENERATE_CANCELLATION_CAUSES ? null : new ImmediateCancelledFuture<>();
ImmediateCancelledFuture() {
diff --git a/android/guava/src/com/google/common/util/concurrent/InterruptibleTask.java b/android/guava/src/com/google/common/util/concurrent/InterruptibleTask.java
index bcec00730..6f33c5032 100644
--- a/android/guava/src/com/google/common/util/concurrent/InterruptibleTask.java
+++ b/android/guava/src/com/google/common/util/concurrent/InterruptibleTask.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedCastNullableTToT;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
@@ -74,6 +75,7 @@ abstract class InterruptibleTask<T extends @Nullable Object>
result = runInterruptibly();
}
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
error = t;
} finally {
// Attempt to set the task as done so that further attempts to interrupt will fail.
@@ -231,6 +233,11 @@ abstract class InterruptibleTask<T extends @Nullable Object>
super.setExclusiveOwnerThread(thread);
}
+ @VisibleForTesting
+ Thread getOwner() {
+ return super.getExclusiveOwnerThread();
+ }
+
@Override
public String toString() {
return task.toString();
diff --git a/android/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java b/android/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
index 0b0db4573..33403c978 100644
--- a/android/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
+++ b/android/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
@@ -17,8 +17,9 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -31,10 +32,13 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* that, whenever possible, it is strongly preferred to modify those libraries to return {@code
* ListenableFuture} directly.
*
+ * <p>For interoperability between {@code ListenableFuture} and <b>{@code CompletableFuture}</b>,
+ * consider <a href="https://github.com/lukas-krecan/future-converter">Future Converter</a>.
+ *
* @author Sven Mawson
* @since 10.0 (replacing {@code Futures.makeListenable}, which existed in 1.0)
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class JdkFutureAdapters {
@@ -158,9 +162,10 @@ public final class JdkFutureAdapters {
* to return a proper ListenableFuture instead of using listenInPoolThread.
*/
getUninterruptibly(delegate);
- } catch (Throwable e) {
- // ExecutionException / CancellationException / RuntimeException / Error
+ } catch (ExecutionException | RuntimeException | Error e) {
+ // (including CancellationException)
// The task is presumably done, run the listeners.
+ // TODO(cpovirk): Do *something* in case of Error (and maybe RuntimeException)?
}
executionList.execute();
});
diff --git a/android/guava/src/com/google/common/util/concurrent/ListenableFuture.java b/android/guava/src/com/google/common/util/concurrent/ListenableFuture.java
index a8d9dd4de..cdc2ee110 100644
--- a/android/guava/src/com/google/common/util/concurrent/ListenableFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/ListenableFuture.java
@@ -36,10 +36,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
* asynchronous operations. You can chain them together manually with calls to methods like {@link
- * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)
- * Futures.transform}, but you will often find it easier to use a framework. Frameworks automate the
- * process, often adding features like monitoring, debugging, and cancellation. Examples of
- * frameworks include:
+ * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor) Futures.transform}
+ * (or {@link FluentFuture#transform(com.google.common.base.Function, Executor)
+ * FluentFuture.transform}), but you will often find it easier to use a framework. Frameworks
+ * automate the process, often adding features like monitoring, debugging, and cancellation.
+ * Examples of frameworks include:
*
* <ul>
* <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
diff --git a/android/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java b/android/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java
index 678a6c671..161fa895f 100644
--- a/android/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java
+++ b/android/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java
@@ -18,6 +18,7 @@ import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -40,6 +41,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Sven Mawson
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class ListenableFutureTask<V extends @Nullable Object> extends FutureTask<V>
diff --git a/android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java b/android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
index ed8c9065a..4ef7ed36c 100644
--- a/android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
+++ b/android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.collect.Queues;
import com.google.errorprone.annotations.concurrent.GuardedBy;
@@ -52,6 +53,7 @@ import java.util.logging.Logger;
* the listeners can be delayed slightly so that locks can be dropped. Also, because {@link
* #dispatch} is expected to be called concurrently, it is idempotent.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class ListenerCallQueue<L> {
@@ -147,7 +149,7 @@ final class ListenerCallQueue<L> {
this.executor = checkNotNull(executor);
}
- /** Enqueues a event to be run. */
+ /** Enqueues an event to be run. */
synchronized void add(ListenerCallQueue.Event<L> event, Object label) {
waitQueue.add(event);
labelQueue.add(label);
diff --git a/android/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java b/android/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java
index a6be949e5..3b5fad2e2 100644
--- a/android/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java
+++ b/android/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -29,6 +30,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Chris Povirk
* @since 10.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ListeningScheduledExecutorService
diff --git a/android/guava/src/com/google/common/util/concurrent/Monitor.java b/android/guava/src/com/google/common/util/concurrent/Monitor.java
index d8da62de2..5542b0bd5 100644
--- a/android/guava/src/com/google/common/util/concurrent/Monitor.java
+++ b/android/guava/src/com/google/common/util/concurrent/Monitor.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Longs;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.Weak;
@@ -196,6 +197,7 @@ import javax.annotation.CheckForNull;
* @author Martin Buchholz
* @since 10.0
*/
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress.
@ElementTypesAreNonnullByDefault
@@ -1011,7 +1013,7 @@ public final class Monitor {
private boolean isSatisfied(Guard guard) {
try {
return guard.isSatisfied();
- } catch (Throwable throwable) {
+ } catch (RuntimeException | Error throwable) {
signalAllWaiters();
throw throwable;
}
diff --git a/android/guava/src/com/google/common/util/concurrent/MoreExecutors.java b/android/guava/src/com/google/common/util/concurrent/MoreExecutors.java
index 791a417c6..dba374014 100644
--- a/android/guava/src/com/google/common/util/concurrent/MoreExecutors.java
+++ b/android/guava/src/com/google/common/util/concurrent/MoreExecutors.java
@@ -16,10 +16,11 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
@@ -78,7 +79,7 @@ public final class MoreExecutors {
* @param timeUnit unit of time for the time parameter
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static ExecutorService getExitingExecutorService(
@@ -99,7 +100,7 @@ public final class MoreExecutors {
* @param executor the executor to modify to make sure it exits when the application is finished
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
return new Application().getExitingExecutorService(executor);
@@ -118,7 +119,7 @@ public final class MoreExecutors {
* @param timeUnit unit of time for the time parameter
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static ScheduledExecutorService getExitingScheduledExecutorService(
@@ -140,7 +141,7 @@ public final class MoreExecutors {
* @param executor the executor to modify to make sure it exits when the application is finished
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor) {
@@ -158,7 +159,7 @@ public final class MoreExecutors {
* JVM
* @param timeUnit unit of time for the time parameter
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static void addDelayedShutdownHook(
@@ -167,6 +168,7 @@ public final class MoreExecutors {
}
/** Represents the current application to register shutdown hooks. */
+ @J2ktIncompatible
@GwtIncompatible // TODO
@VisibleForTesting
static class Application {
@@ -227,6 +229,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static void useDaemonThreadFactory(ThreadPoolExecutor executor) {
executor.setThreadFactory(
@@ -237,6 +240,7 @@ public final class MoreExecutors {
}
// See newDirectExecutorService javadoc for behavioral notes.
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static final class DirectExecutorService extends AbstractListeningExecutorService {
/** Lock used whenever accessing the state variables (runningTasks, shutdown) of the executor */
@@ -365,6 +369,7 @@ public final class MoreExecutors {
*
* @since 18.0 (present as MoreExecutors.sameThreadExecutor() since 10.0)
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ListeningExecutorService newDirectExecutorService() {
return new DirectExecutorService();
@@ -386,10 +391,10 @@ public final class MoreExecutors {
* complete, the listener runs immediately in that thread.
* <li>When a thread attaches a listener to a {@code ListenableFuture} that's
* <em>in</em>complete and the {@code ListenableFuture} later completes normally, the
- * listener runs in the the thread that completes the {@code ListenableFuture}.
+ * listener runs in the thread that completes the {@code ListenableFuture}.
* <li>When a listener is attached to a {@code ListenableFuture} and the {@code
- * ListenableFuture} gets cancelled, the listener runs immediately in the the thread
- * that cancelled the {@code Future}.
+ * ListenableFuture} gets cancelled, the listener runs immediately in the thread that
+ * cancelled the {@code Future}.
* </ol>
* Given all these possibilities, it is frequently possible for listeners to execute in UI
* threads, RPC network threads, or other latency-sensitive threads. In those cases, slow
@@ -479,6 +484,7 @@ public final class MoreExecutors {
*
* @since 23.3 (since 23.1 as {@code sequentialExecutor})
*/
+ @J2ktIncompatible
@GwtIncompatible
public static Executor newSequentialExecutor(Executor delegate) {
return new SequentialExecutor(delegate);
@@ -499,6 +505,7 @@ public final class MoreExecutors {
*
* @since 10.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ListeningExecutorService listeningDecorator(ExecutorService delegate) {
return (delegate instanceof ListeningExecutorService)
@@ -524,6 +531,7 @@ public final class MoreExecutors {
*
* @since 10.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ListeningScheduledExecutorService listeningDecorator(
ScheduledExecutorService delegate) {
@@ -532,6 +540,7 @@ public final class MoreExecutors {
: new ScheduledListeningDecorator(delegate);
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static class ListeningDecorator extends AbstractListeningExecutorService {
private final ExecutorService delegate;
@@ -576,6 +585,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static final class ScheduledListeningDecorator extends ListeningDecorator
implements ListeningScheduledExecutorService {
@@ -654,6 +664,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static final class NeverSuccessfulListenableFutureTask
extends AbstractFuture.TrustedFuture<@Nullable Void> implements Runnable {
@@ -667,9 +678,9 @@ public final class MoreExecutors {
public void run() {
try {
delegate.run();
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
setException(t);
- throw Throwables.propagate(t);
+ throw t;
}
}
@@ -696,6 +707,7 @@ public final class MoreExecutors {
* implementations.
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @J2ktIncompatible
@GwtIncompatible
@ParametricNullness
static <T extends @Nullable Object> T invokeAnyImpl(
@@ -777,6 +789,7 @@ public final class MoreExecutors {
/**
* Submits the task and adds a listener that adds the future to {@code queue} when it completes.
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static <T extends @Nullable Object> ListenableFuture<T> submitAndAddQueueListener(
ListeningExecutorService executorService,
@@ -804,7 +817,7 @@ public final class MoreExecutors {
*
* @since 14.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static ThreadFactory platformThreadFactory() {
if (!isAppEngineWithApiClasses()) {
@@ -831,6 +844,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static boolean isAppEngineWithApiClasses() {
if (System.getProperty("com.google.appengine.runtime.environment") == null) {
@@ -866,11 +880,13 @@ public final class MoreExecutors {
* Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} unless
* changing the name is forbidden by the security manager.
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static Thread newThread(String name, Runnable runnable) {
checkNotNull(name);
checkNotNull(runnable);
- Thread result = platformThreadFactory().newThread(runnable);
+ // TODO(b/139726489): Confirm that null is impossible here.
+ Thread result = requireNonNull(platformThreadFactory().newThread(runnable));
try {
result.setName(name);
} catch (SecurityException e) {
@@ -893,6 +909,7 @@ public final class MoreExecutors {
* @param executor The executor to decorate
* @param nameSupplier The source of names for each task
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) {
checkNotNull(executor);
@@ -916,6 +933,7 @@ public final class MoreExecutors {
* @param service The executor to decorate
* @param nameSupplier The source of names for each task
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static ExecutorService renamingDecorator(
final ExecutorService service, final Supplier<String> nameSupplier) {
@@ -945,6 +963,7 @@ public final class MoreExecutors {
* @param service The executor to decorate
* @param nameSupplier The source of names for each task
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static ScheduledExecutorService renamingDecorator(
final ScheduledExecutorService service, final Supplier<String> nameSupplier) {
@@ -987,8 +1006,8 @@ public final class MoreExecutors {
* if the call timed out or was interrupted
* @since 17.0
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean shutdownAndAwaitTermination(
diff --git a/android/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java b/android/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java
index 3038ab7bd..905726597 100644
--- a/android/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java
+++ b/android/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java
@@ -16,6 +16,7 @@ package com.google.common.util.concurrent;
import static java.lang.Math.min;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.locks.LockSupport;
import javax.annotation.CheckForNull;
@@ -23,6 +24,7 @@ import javax.annotation.CheckForNull;
* Works around an android bug, where parking for more than INT_MAX seconds can produce an abort
* signal on 32 bit devices running Android Q.
*/
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
final class OverflowAvoidingLockSupport {
// Represents the max nanoseconds representable on a linux timespec with a 32 bit tv_sec
diff --git a/android/guava/src/com/google/common/util/concurrent/ParametricNullness.java b/android/guava/src/com/google/common/util/concurrent/ParametricNullness.java
index a745bf7bb..e8fcce6ee 100644
--- a/android/guava/src/com/google/common/util/concurrent/ParametricNullness.java
+++ b/android/guava/src/com/google/common/util/concurrent/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/util/concurrent/Platform.java b/android/guava/src/com/google/common/util/concurrent/Platform.java
index cfb96a0ad..92d2d12db 100644
--- a/android/guava/src/com/google/common/util/concurrent/Platform.java
+++ b/android/guava/src/com/google/common/util/concurrent/Platform.java
@@ -14,6 +14,9 @@
package com.google.common.util.concurrent;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.lang.Thread.currentThread;
+
import com.google.common.annotations.GwtCompatible;
import javax.annotation.CheckForNull;
@@ -26,5 +29,12 @@ final class Platform {
return expectedClass.isInstance(t);
}
+ static void restoreInterruptIfIsInterruptedException(Throwable t) {
+ checkNotNull(t); // to satisfy NullPointerTester
+ if (t instanceof InterruptedException) {
+ currentThread().interrupt();
+ }
+ }
+
private Platform() {}
}
diff --git a/android/guava/src/com/google/common/util/concurrent/RateLimiter.java b/android/guava/src/com/google/common/util/concurrent/RateLimiter.java
index 9bcf11816..d51ab2b79 100644
--- a/android/guava/src/com/google/common/util/concurrent/RateLimiter.java
+++ b/android/guava/src/com/google/common/util/concurrent/RateLimiter.java
@@ -22,6 +22,7 @@ import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.SmoothRateLimiter.SmoothBursty;
@@ -91,6 +92,7 @@ import javax.annotation.CheckForNull;
// TODO(user): switch to nano precision. A natural unit of cost is "bytes", and a micro precision
// would mean a maximum rate of "1MB/s", which might be small in some cases.
@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class RateLimiter {
diff --git a/android/guava/src/com/google/common/util/concurrent/Runnables.java b/android/guava/src/com/google/common/util/concurrent/Runnables.java
index 5503f68ae..f5b27f8af 100644
--- a/android/guava/src/com/google/common/util/concurrent/Runnables.java
+++ b/android/guava/src/com/google/common/util/concurrent/Runnables.java
@@ -14,7 +14,6 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
@@ -22,7 +21,6 @@ import com.google.common.annotations.GwtCompatible;
*
* @since 16.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Runnables {
diff --git a/android/guava/src/com/google/common/util/concurrent/SequentialExecutor.java b/android/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
index d0b600be8..c842d7e07 100644
--- a/android/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
+++ b/android/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
@@ -22,6 +22,7 @@ import static com.google.common.util.concurrent.SequentialExecutor.WorkerRunning
import static java.lang.System.identityHashCode;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.RetainedWith;
@@ -47,6 +48,7 @@ import javax.annotation.CheckForNull;
* If an {@code Error} is thrown, the error will propagate and execution will stop until it is
* restarted by a call to {@link #execute}.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class SequentialExecutor implements Executor {
diff --git a/android/guava/src/com/google/common/util/concurrent/Service.java b/android/guava/src/com/google/common/util/concurrent/Service.java
index 0999a30ae..b04d88ac4 100644
--- a/android/guava/src/com/google/common/util/concurrent/Service.java
+++ b/android/guava/src/com/google/common/util/concurrent/Service.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.concurrent.Executor;
@@ -52,6 +53,7 @@ import java.util.concurrent.TimeoutException;
* @since 9.0 (in 1.0 as {@code com.google.common.base.Service})
*/
@DoNotMock("Create an AbstractIdleService")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface Service {
diff --git a/android/guava/src/com/google/common/util/concurrent/ServiceManager.java b/android/guava/src/com/google/common/util/concurrent/ServiceManager.java
index 5177b5ac0..dd4828cb8 100644
--- a/android/guava/src/com/google/common/util/concurrent/ServiceManager.java
+++ b/android/guava/src/com/google/common/util/concurrent/ServiceManager.java
@@ -31,6 +31,7 @@ import static com.google.common.util.concurrent.Service.State.TERMINATED;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Stopwatch;
@@ -117,6 +118,7 @@ import java.util.logging.Logger;
* @author Luke Sandberg
* @since 14.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ServiceManager implements ServiceManagerBridge {
diff --git a/android/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java b/android/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java
index 7ae430e3d..71fe01c0b 100644
--- a/android/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java
+++ b/android/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java
@@ -17,6 +17,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.util.concurrent.Service.State;
@@ -25,6 +26,7 @@ import com.google.common.util.concurrent.Service.State;
* servicesByState()}, to ensure binary compatibility with older Guava versions that specified
* {@code servicesByState()} to return {@code ImmutableMultimap}.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
interface ServiceManagerBridge {
diff --git a/android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java b/android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
index c6ade6a3a..5d8df0777 100644
--- a/android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
+++ b/android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
@@ -16,9 +16,10 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -45,7 +46,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jens Nyman
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class SimpleTimeLimiter implements TimeLimiter {
@@ -111,6 +112,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
return interfaceType.cast(object);
}
+ @ParametricNullness
private <T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
throws Exception {
@@ -121,16 +123,12 @@ public final class SimpleTimeLimiter implements TimeLimiter {
Future<T> future = executor.submit(callable);
try {
- if (amInterruptible) {
- try {
- return future.get(timeoutDuration, timeoutUnit);
- } catch (InterruptedException e) {
- future.cancel(true);
- throw e;
- }
- } else {
- return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
- }
+ return amInterruptible
+ ? future.get(timeoutDuration, timeoutUnit)
+ : getUninterruptibly(future, timeoutDuration, timeoutUnit);
+ } catch (InterruptedException e) {
+ future.cancel(true);
+ throw e;
} catch (ExecutionException e) {
throw throwCause(e, true /* combineStackTraces */);
} catch (TimeoutException e) {
@@ -141,6 +139,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
@CanIgnoreReturnValue
@Override
+ @ParametricNullness
public <T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException, ExecutionException {
@@ -163,6 +162,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
@CanIgnoreReturnValue
@Override
+ @ParametricNullness
public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, ExecutionException {
@@ -173,7 +173,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
Future<T> future = executor.submit(callable);
try {
- return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
+ return getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
@@ -213,7 +213,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
Future<?> future = executor.submit(runnable);
try {
- Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
+ getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
diff --git a/android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java b/android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
index ca7890590..6f21ab6a3 100644
--- a/android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
+++ b/android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
@@ -18,9 +18,11 @@ import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.math.LongMath;
import java.util.concurrent.TimeUnit;
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class SmoothRateLimiter extends RateLimiter {
diff --git a/android/guava/src/com/google/common/util/concurrent/Striped.java b/android/guava/src/com/google/common/util/concurrent/Striped.java
index 2ea61cb32..37fa2fd7e 100644
--- a/android/guava/src/com/google/common/util/concurrent/Striped.java
+++ b/android/guava/src/com/google/common/util/concurrent/Striped.java
@@ -16,8 +16,8 @@ package com.google.common.util.concurrent;
import static com.google.common.collect.Lists.newArrayList;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
@@ -82,7 +82,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Dimitris Andreou
* @since 13.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class Striped<L> {
diff --git a/android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java b/android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
index 091f56e79..80727c59a 100644
--- a/android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
+++ b/android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
@@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
import java.util.concurrent.Executors;
@@ -45,7 +45,7 @@ import javax.annotation.CheckForNull;
* @author Kurt Alfred Kluever
* @since 4.0
*/
-@CanIgnoreReturnValue
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ThreadFactoryBuilder {
@@ -69,6 +69,7 @@ public final class ThreadFactoryBuilder {
* "rpc-pool-1"}, {@code "rpc-pool-2"}, etc.
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setNameFormat(String nameFormat) {
String unused = format(nameFormat, 0); // fail fast if the format is bad or null
this.nameFormat = nameFormat;
@@ -81,6 +82,7 @@ public final class ThreadFactoryBuilder {
* @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
@@ -89,9 +91,13 @@ public final class ThreadFactoryBuilder {
/**
* Sets the priority for new threads created with this ThreadFactory.
*
+ * <p><b>Warning:</b> relying on the thread scheduler is <a
+ * href="http://errorprone.info/bugpattern/ThreadPriorityCheck">discouraged</a>.
+ *
* @param priority the priority for new Threads created with this ThreadFactory
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setPriority(int priority) {
// Thread#setPriority() already checks for validity. These error messages
// are nicer though and will fail-fast.
@@ -116,6 +122,7 @@ public final class ThreadFactoryBuilder {
* this ThreadFactory
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setUncaughtExceptionHandler(
UncaughtExceptionHandler uncaughtExceptionHandler) {
this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler);
@@ -131,6 +138,7 @@ public final class ThreadFactoryBuilder {
* @return this for the builder pattern
* @see MoreExecutors
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) {
this.backingThreadFactory = checkNotNull(backingThreadFactory);
return this;
@@ -143,7 +151,6 @@ public final class ThreadFactoryBuilder {
*
* @return the fully constructed {@link ThreadFactory}
*/
- @CheckReturnValue
public ThreadFactory build() {
return doBuild(this);
}
@@ -164,6 +171,8 @@ public final class ThreadFactoryBuilder {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = backingThreadFactory.newThread(runnable);
+ // TODO(b/139735208): Figure out what to do when the factory returns null.
+ requireNonNull(thread);
if (nameFormat != null) {
// requireNonNull is safe because we create `count` if (and only if) we have a nameFormat.
thread.setName(format(nameFormat, requireNonNull(count).getAndIncrement()));
diff --git a/android/guava/src/com/google/common/util/concurrent/TimeLimiter.java b/android/guava/src/com/google/common/util/concurrent/TimeLimiter.java
index 0883bccee..35695ad02 100644
--- a/android/guava/src/com/google/common/util/concurrent/TimeLimiter.java
+++ b/android/guava/src/com/google/common/util/concurrent/TimeLimiter.java
@@ -14,8 +14,9 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
+
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.concurrent.Callable;
@@ -31,8 +32,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jens Nyman
* @since 1.0
*/
-@Beta
@DoNotMock("Use FakeTimeLimiter")
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings("GoodTime") // should have java.time.Duration overloads
@ElementTypesAreNonnullByDefault
@@ -99,6 +100,7 @@ public interface TimeLimiter {
* @since 22.0
*/
@CanIgnoreReturnValue
+ @ParametricNullness
<T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException, ExecutionException;
@@ -123,6 +125,7 @@ public interface TimeLimiter {
* @since 22.0
*/
@CanIgnoreReturnValue
+ @ParametricNullness
<T extends @Nullable Object> T callUninterruptiblyWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, ExecutionException;
diff --git a/android/guava/src/com/google/common/util/concurrent/TimeoutFuture.java b/android/guava/src/com/google/common/util/concurrent/TimeoutFuture.java
index ed8a7bfdb..aca623054 100644
--- a/android/guava/src/com/google/common/util/concurrent/TimeoutFuture.java
+++ b/android/guava/src/com/google/common/util/concurrent/TimeoutFuture.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -34,6 +35,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* in an {@link ExecutionException}) if the specified duration expires. The delegate future is
* interrupted and cancelled if it times out.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class TimeoutFuture<V extends @Nullable Object> extends FluentFuture.TrustedFuture<V> {
diff --git a/android/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java b/android/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
index a1add8bcb..1dc1094d4 100644
--- a/android/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
+++ b/android/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static java.util.logging.Level.SEVERE;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
@@ -28,6 +29,7 @@ import java.util.logging.Logger;
* @author Gregory Kick
* @since 8.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class UncaughtExceptionHandlers {
@@ -68,7 +70,7 @@ public final class UncaughtExceptionHandlers {
try {
logger.log(
SEVERE, String.format(Locale.ROOT, "Caught an exception in %s. Shutting down.", t), e);
- } catch (Throwable errorInLogging) {
+ } catch (RuntimeException | Error errorInLogging) {
// If logging fails, e.g. due to missing memory, at least try to log the
// message and the cause for the failed logging.
System.err.println(e.getMessage());
diff --git a/android/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java b/android/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
index 713f4a69e..a0ec427ee 100644
--- a/android/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
+++ b/android/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
@@ -38,7 +38,7 @@ public class UncheckedExecutionException extends RuntimeException {
/*
* Ideally, this class would have exposed only constructors that require a non-null cause. We
* might try to move in that direction, but there are complications. See
- * https://github.com/jspecify/nullness-checker-for-checker-framework/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
+ * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
*/
/** Creates a new instance with {@code null} as its detail message. */
diff --git a/android/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java b/android/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
index 8e30fca37..181de101f 100644
--- a/android/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
+++ b/android/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
@@ -23,6 +24,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class UncheckedTimeoutException extends RuntimeException {
diff --git a/android/guava/src/com/google/common/util/concurrent/Uninterruptibles.java b/android/guava/src/com/google/common/util/concurrent/Uninterruptibles.java
index c2c6f7ca8..8428f67d7 100644
--- a/android/guava/src/com/google/common/util/concurrent/Uninterruptibles.java
+++ b/android/guava/src/com/google/common/util/concurrent/Uninterruptibles.java
@@ -19,6 +19,7 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.BlockingQueue;
@@ -50,6 +51,7 @@ public final class Uninterruptibles {
// methods is identical, save for method being invoked.
/** Invokes {@code latch.}{@link CountDownLatch#await() await()} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void awaitUninterruptibly(CountDownLatch latch) {
boolean interrupted = false;
@@ -73,7 +75,7 @@ public final class Uninterruptibles {
* Invokes {@code latch.}{@link CountDownLatch#await(long, TimeUnit) await(timeout, unit)}
* uninterruptibly.
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean awaitUninterruptibly(CountDownLatch latch, long timeout, TimeUnit unit) {
@@ -104,6 +106,7 @@ public final class Uninterruptibles {
*
* @since 23.6
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean awaitUninterruptibly(Condition condition, long timeout, TimeUnit unit) {
@@ -128,6 +131,7 @@ public final class Uninterruptibles {
}
/** Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void joinUninterruptibly(Thread toJoin) {
boolean interrupted = false;
@@ -151,6 +155,7 @@ public final class Uninterruptibles {
* Invokes {@code unit.}{@link TimeUnit#timedJoin(Thread, long) timedJoin(toJoin, timeout)}
* uninterruptibly.
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static void joinUninterruptibly(Thread toJoin, long timeout, TimeUnit unit) {
@@ -232,6 +237,7 @@ public final class Uninterruptibles {
* @throws TimeoutException if the wait timed out
*/
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@ParametricNullness
@@ -259,6 +265,7 @@ public final class Uninterruptibles {
}
/** Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static <E> E takeUninterruptibly(BlockingQueue<E> queue) {
boolean interrupted = false;
@@ -285,6 +292,7 @@ public final class Uninterruptibles {
* @throws IllegalArgumentException if some property of the specified element prevents it from
* being added to the given queue
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) {
boolean interrupted = false;
@@ -306,6 +314,7 @@ public final class Uninterruptibles {
// TODO(user): Support Sleeper somehow (wrapper or interface method)?
/** Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
@@ -336,6 +345,7 @@ public final class Uninterruptibles {
*
* @since 18.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean tryAcquireUninterruptibly(
@@ -349,6 +359,7 @@ public final class Uninterruptibles {
*
* @since 18.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean tryAcquireUninterruptibly(
@@ -380,6 +391,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean tryLockUninterruptibly(Lock lock, long timeout, TimeUnit unit) {
@@ -409,6 +421,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void awaitTerminationUninterruptibly(ExecutorService executor) {
// TODO(cpovirk): We could optimize this to avoid calling nanoTime() at all.
@@ -421,6 +434,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime")
public static boolean awaitTerminationUninterruptibly(
diff --git a/android/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java b/android/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
index 5a3c3927a..d6684b809 100644
--- a/android/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
+++ b/android/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
@@ -16,8 +16,10 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
@@ -41,7 +43,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Chris Nokleberg
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class WrappingExecutorService implements ExecutorService {
@@ -67,6 +69,7 @@ abstract class WrappingExecutorService implements ExecutorService {
try {
wrapped.call();
} catch (Exception e) {
+ restoreInterruptIfIsInterruptedException(e);
throwIfUnchecked(e);
throw new RuntimeException(e);
}
@@ -143,6 +146,7 @@ abstract class WrappingExecutorService implements ExecutorService {
}
@Override
+ @CanIgnoreReturnValue
public final List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
diff --git a/android/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java b/android/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
index 48f23c12c..d533fc632 100644
--- a/android/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
+++ b/android/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
@@ -15,7 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -30,7 +30,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Luke Sandberg
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class WrappingScheduledExecutorService extends WrappingExecutorService
diff --git a/android/guava/src/com/google/common/util/concurrent/package-info.java b/android/guava/src/com/google/common/util/concurrent/package-info.java
index a2533c1fc..7df382a54 100644
--- a/android/guava/src/com/google/common/util/concurrent/package-info.java
+++ b/android/guava/src/com/google/common/util/concurrent/package-info.java
@@ -15,14 +15,13 @@
/**
* Concurrency utilities.
*
- * <p>Commonly used types include {@link com.google.common.util.concurrent.ListenableFuture} and
- * {@link com.google.common.util.concurrent.Service}.
+ * <p>Commonly used types include {@link ClosingFuture}, {@link ListenableFuture}, and {@link
+ * Service}.
*
- * <p>Commonly used utilities include {@link com.google.common.util.concurrent.Futures}, {@link
- * com.google.common.util.concurrent.MoreExecutors}, and {@link
- * com.google.common.util.concurrent.ThreadFactoryBuilder}.
+ * <p>Commonly used utilities include {@link Futures}, {@link MoreExecutors}, {@link
+ * ThreadFactoryBuilder}, and {@link Uninterruptibles}.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/android/guava/src/com/google/common/xml/ParametricNullness.java b/android/guava/src/com/google/common/xml/ParametricNullness.java
index e4e5d12f0..439707a2e 100644
--- a/android/guava/src/com/google/common/xml/ParametricNullness.java
+++ b/android/guava/src/com/google/common/xml/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/android/guava/src/com/google/common/xml/package-info.java b/android/guava/src/com/google/common/xml/package-info.java
index bd4c95216..869327627 100644
--- a/android/guava/src/com/google/common/xml/package-info.java
+++ b/android/guava/src/com/google/common/xml/package-info.java
@@ -17,7 +17,7 @@
* for
* XML.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/android/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java b/android/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java
index c987065e4..e728822a8 100644
--- a/android/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java
+++ b/android/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java
@@ -42,7 +42,13 @@ public final class PublicSuffixPatterns {
/** If a hostname is contained as a key in this map, it is a public suffix. */
public static final ImmutableMap<String, PublicSuffixType> EXACT =
TrieParser.parseTrie(
- "a&0&0trk9--nx?27qjf--nx?e9ebgn--nx?nbb0c7abgm--nx??1&2oa08--nx?apg6qpcbgm--nx?hbbgm--nx?rdceqa08--nx??2&8ugbgm--nx?eyh3la2ckx--nx?qbd9--nx??3&2wqq1--nx?60a0y8--nx??4x1d77xrck--nx?6&1f4a3abgm--nx?2yqyn--nx?5b06t--nx?axq--nx?ec7q--nx?lbgw--nx??883xnn--nx?9d2c24--nx?a&a?it??b!.&gro?lim?moc?sr,t&en?opsgolb,?ude?vog??abila?c?ihsot?m?n??c!.&b&a?m?n??c&b?g?q??ep?fn?k&s?y??ln?no?oc,p&i-on,ohsdaerpsym,?sn?t&n?opsgolb,?un?ysrab,?i&ma?r&emarp?fa??sroc??naiva?s??d&ats?n&eit?oh??om?sa?tl??eg?f&c?ob??g!emo?naripi?oy??hskihs?i&cnal?dem?hs?k!on??sa!.snduolc,??jnin?k&aso?dov?ede?usto??l!.&c,gro?moc?ofni?r&ep?nb,?t&en?ni??ude?vog??irgnahs?le&nisiuc?rbmuder???m!.&ca?gro?oc?sserp?ten?vog??ahokoy?e00sf7vqn--nx?m??n!.&ac?cc?eman?gro?ibom?loohcs?moc?ni?o&c?fni?rp??r&d?o??s&u?w??vt?xm??av?is?olecrab?tea??p!.&bog?ca?d&em?ls??g&ni?ro??mo&c?n??oba?ten?ude??c?g7hyabgm--nx?ra!.&461e?6pi?iru?nru?rdda-ni?siri???s??q!.&eman?gro?hcs?lim?moc?t&en?opsgolb,?ude?vog???r&az?emac?f4a3abgm--nx?n!d5uhf8le58r4w--nx??u&kas?tan???s!.&bup?dem?gro?hcs?moc?ten?ude?vog??ac!.uban.iu,?iv??t&ad?elhta?led?oyot??u!.&a&cinniv?emirc?i&hzhziropaz?stynniv??s&edo?sedo??tlay?vatlop??bs?cc,d&argovorik?o!roghzu??tl,?e&hzhziropaz?nvir?t??f&i?ni,?g&l?ro??hk?i&stvinrehc?ykstynlemhk??k&c?m?s&nagul?t&enod?ul??v&iknarf-onavi?orteporp&end?ind?????l&iponret?opotsa&bes?ves??p??m&k?oc?s?yrk??n&c?d?i?osrehk?v?ylov??o&c,nvor??p&d?p,z??r&c?imotihz?k?ymotyhz??sk?t&en?l?z??ude?v:c?e&alokin?ik??i&alokym?hinrehc?krahk?vl?yk??k?l?o&g!inrehc??krahk??r?,xc,y&ikstinlemhk?mus?s&akrehc?sakrehc?tvonrehc???z&ib,u????v!aj?bb?et?iv??waniko?x&a?iacal??yogan?z&.&bew?c&a?i&n?rga???gro?l&im?oohcs??m&on?t??o&c!.topsgolb,?gn??radnorg?sin?t&en?la??ude?vog?wal??zip???b&00ave5a9iabgm--nx?1&25qhx--nx?68quv--nx?e2kc1--nx??2xtbgm--nx?3&b2kcc--nx?jca1d--nx??4&6&1rfz--nx?qif--nx??96rzc--nx??7w9u16qlj--nx?88uvor--nx?a&0dc4xbgm--nx?c?her?n?ra?t??b!.&erots?gro?moc?o&c?fni??ten?ude?v&og?t??zib??a??c&j?s??d&hesa08--nx?mi??g?l!.&gro?moc?ten?ude?vog??m??s!.&gro?moc?ten?ude?vog???tc-retarebsnegmrev--nx?u&lc!.&elej,snduolc,y&nop,srab,??smas??p!.ysrab,??wp-gnutarebsnegmrev--nx??c&1&1q54--nx?hbgw--nx??2e9c2czf--nx?4&4ub1km--nx?a1e--nx?byj9q--nx?erd5a9b1kcb--nx??8&4xx2g--nx?c9jrb2h--nx??9jr&b&2h--nx?54--nx?9s--nx??c&eg--nx?h3--nx?s2--nx???a!.&gro?lim?moc?rrd,ten?ude?vog??3a09--nx!.&ca1o--nx?gva1c--nx?h&ca1o--nx?za09--nx??ta1d--nx?ua08--nx???da??b&a?b?ci?f76a0c7ylqbgm--nx?sh??c!.&eugaelysatnaf,gnipparcs,liamwt,nwaps.secnatsni,revres-emag,s&nduolc,otohpym,seccaptf,?xsc,?0atf7b45--nx?a1l--nx??e!.&21k?bog?dem?esab,gro?l&aiciffo,im??moc?nif?o&fni?rp??ten?ude?vog??beuq?n?smoc??fdh?i&l&buperananab?ohtac??n&agro?ilc?osanap??sum?tic??l!.&gro?moc?oc?ten?ude?vog?yo,?l??m!.&mt?ossa??p1akcq--nx??n!.&mon?ossa??i?p??relcel?s!.&gro?moc?ten?ude?vog???t!.&e&m,w,?hc,?s?w??v!.&e0,gro?lim?moc?ten?ude?v&g:.d,,og????wp?yn??d&2urzc--nx?3&1wrpk--nx?c&4b11--nx?9jrcpf--nx???5xq55--nx?697uto--nx?75yrpk--nx?9ctdvkce--nx?a!.mon?d?er?olnwod??b2babgm--nx?c!.vog?g9a2g2b0ae0chclc--nx??e&m!bulc??r!k??sopxe?timil?w??fc?g!.&ude?vog???h&d3tbgm--nx?p?t??i!.&ased?bew?ca?etrof,golbw,hcs?lim?o&c!.topsgolb,?g??palf,r&egolb,o??sepnop?ten?ym?zib??b?ordna?p?rdam??l&iub?og?row??m!.&ed,ot,pj,t&a,opsgolb,???n&a&b?l!.citats:.&setis,ved,?,raas???ob?uf??o&of?rp??r&a&c&tiderc?yalcrab??ugnav??ef506w4b--nx?k!.&oc,ude,?jh3a1habgm--nx??of??s!.&dem?gro?moc?ofni?ten?ude?v&og?t???m!kcrem???t!.topsgolb,excwkcc--nx?l??uolc!.&a&bura-vnej.&1ti,abura.rue.1ti,?tcepsrep,xo:.&ku,nt,?,?b&dnevar,ewilek:.sc,,?citsalej.piv,drayknil,elej,gnitsohdnert.&ed,hc,?letemirp:.ku,,m&edaid,ialcer.&ac,ku,su,??n&evueluk,woru,?r&epolroov,o&pav,tnemele,??tenraxa.1-se,ululetoj,xelpciffart,yawocne.ue,??za5cbgn--nx??e&1&53wlf--nx?7a1hbbgm--nx?ta3kg--nx??2a6a1b6b1i--nx?3ma0e1cvr--nx?418txh--nx?707b0e3--nx?a!.&ca?gro?hcs?lim?oc?t&en?opsgolb,?vog??09--nx??b!.&ca?gnitsohbew,nevueluk.yxorpze,pohsdaerpsym,snoitulostsohretni.duolc,topsgolb,?ortal?ut!uoy???c&0krbd4--nx?a&lp!.oc,?ps!.&lla4sx,rebu,tsafym,?artxe??sla??i!ffo??n&a&d?iler?nif?rusni!efil?srelevart???eics!.oby,??rofria??d!.&1sndnyd,42pi-nyd,7erauqs,amil4,b&ow-nrefeilgitsng--nx,rb-ni,vz-nelletsebgitsng--nx,?decalpb,e&daregtmueart,mohsnd,nihcamyek,?hcierebsnoissuksid,keegnietsi,lsd-ni,moc,n&-i-g-o-l,aw-ym,e&lletsebgitsnüg,sgnutiel,?i&emtsi,lreb-n&i,yd,??norblieh-sh.ti.segap,oitatsksid-ygolonys,pv&-n&i,yd,?nyd,?refeilgitsnüg,?orp-ytinummoc,p&h21,iog:ol,,ohsdaerpsym,?r&e&ntrapdeeps.remotsuc,su&-lautriv,lautriv,?t&adpusnd,tub-ni,uor-ym,?vres&-e&bucl,mohym,?bew-emoh:.nyd,,luhcs,??ogiv-&niem,ym,??s&d-&onys,ygolonys,?nd&-&dd,nufiat,sehcsimanyd,tenretni,yard,?isoc.nyd,ps,yard,?oper-&nvs,tig,?sndd:.&nyd,sndnyd,?,?topsgolb,vresi-&niem,tset,?xi2,y&awetag-&llawerif,ym,?srab,tic-amil,?zten&mitbel,sadtretteuf,??art!.oby,?i&sdoow?ug??nil?on--nx??e!.&bil?dem?eif?gro?irp?kiir?moc!.topsgolb,?pia?ude?vog??ei?ffoc?gg?r&f?ged???f&a&c?s??il??g!.&gro?lim?moc?t&en?vp??ude?vog??a&f?gtrom?p!.&3xlh,detalsnart,grebedoc,kselp,sndp,tengam,xlh,y&cvrp,kcor,???rots?yov??elloc?na&hcxe?ro??roeg?ug??i!.&pohsdaerpsym,topsgolb,vog??tilop?v&bba?om???j!.&fo,gro?oc?ten???k!.&c&a?s??e&m?n??ibom?o&c!.topsgolb,?fni?g??ro??i&b?l?n???l&a&dmrif?s!.rof,rof???b&a?i&b?dua???c&aro?ric??dnik?g!oog??i&bom?ms??l&asal?erauqa??ppa?uhcs?yts!efil???m!.&4&32i,p&ct,v,??66c,ailisarb,b&dnevar,g-raegelif,?ca?duolcsd,e&d-raegelif,i&-raegelif,lpad:.tsohlacol,,?pcm,?g&ro?s-raegelif,?hctilg,k&catsegde,uoc,?noitatsksid,o&bmoy,c!ku,?t&nigol,poh,??p&ion,j-raegelif,ohbew,?qbw,r&aegelif,idcm,ofsnd,?s&dym,ndd,ti!bt,?umhol,?t&en?s&acdnuos,ohon,??u&a-raegelif,de??v&irp?og??y&golonys,olpedew,srab,??a&g?n!.&reh.togrof,sih.togrof,???em?i&rp?twohs??orhc?w??n!goloc?i&lno!.&egats-oree,oree,ysrab,??w??o!.&derno:.gnigats,,ecivres,knilemoh,r&ednu,of,??hp?latipac?ts&der?e&gdirb?rif???z!.&66duolc,amil,sh,???ruoblem??om?p!.&bog?gro?lim?mo&c?n??t&en?opsgolb,?ude??irg?yks??r!.&mo&c?n??ossa?topsgolb,?a&c!htlaeh??pmoc?wtfos??bc?eh?if?ots!.&e&rawpohs,saberots,?yflles,??taeht?u&ces?sni?t&inruf?necca??za???s!.&a!bap.us,?b!ibnal?rofmok??c!a??d!b?n&arb?ubroflanummok???e?f!noc,?g!ro??h!f??i!trap??k!shf??l?m!oc,t??n!mygskurbrutan??o?p!ohsdaerpsym,p??r!owebdluocti,?s!serp?yspoi,?t!opsgolb,?u?vhf?w?x!uvmok??y?z??a&c?el?hc??i&er?urc??nesemoh?roh?uoh??t&a&d?ts&e!laer??lla???is!.&e&lej,nilnigol,r&etnim,ocevon,?winmo,?k&rowtenoilof,wnf,?laicosnepo,n&eyb,oyc,?spvtsaf,thrs,xulel,ysrab,?bew??ov?ra?t&ioled?ol??utitsni??u&lb?qi&nilc?tuob???v!.&21e?b&ew?ib?og??ce&r?t??erots?gro?lim?m&o&c?n??rif??o&c?fni??rar?stra?t&en?ni??ude?vog??as?e3gerb2h--nx?i&l!.xlh,?rd?ssergorp??ol??w&kct--nx?r??xul?y!.&gro?lim?moc?ten?ude?vog????f&0f3rkcg--nx?198xim--nx?280xim--nx?7vqn--nx?a!.&gro?moc?ten?ude?vog???b!.vog?wa9bgm--nx??c!.topsgolb,a1p--nx!.&a14--nx,b8lea1j--nx,c&avc0aaa08--nx,ma09--nx,?f&a1a09--nx,ea1j--nx,?gva1c--nx,nha1h--nx,pda1j--nx,zila1h--nx,??ns??ea1j--nx?g?iam?l&a1d--nx?og??n!.&bew?cer?erots?m&oc?rif??ofni?re&hto?p??stra?ten???orp?p!.&gro?moc?ude???rus?t!w??vd7ckaabgm--nx?w??g&2&4wq55--nx?8zrf6--nx??3&44sd3--nx?91w6j--nx!.&a5wqmg--nx?d&22svcw--nx?5xq55--nx??gla0do--nx?m1qtxm--nx?vta0cu--nx????455ses--nx?5mzt5--nx?69vqhr--nx?7&8a4d5a4prebgm--nx?rb2c--nx??a!.&gro?mo&c?n??oc?ten??vd??b!.&0?1?2?3?4?5?6?7?8?9?a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t!opsgolb,?u?v?w?x?y!srab,?z???c!b?za9a0cbgm--nx??e!.&eman?gro?ics?lim?moc!.topsgolb,?nue?ten?ude?vog??a??g!.&ayc,gro?lenap:.nomead,,oc?saak,ten???i&a?v??k!.&g&olb,ro??ku,lim?moc?oi,pj,su,ten?ude?v&og?t,???m!.&drp?gro?lim?m&o&c?n??t??oc?ude?vog??pk??n!.&dtl,eman?gro?hcs?i!bom??l&im?oc,?m&oc!.topsgolb,?rif,?neg,ogn,ten?ude?vog??aw?i!b!mulp??car?d&art?dew??h&sif?tolc??k&iv?oo&b?c???ls?n&aelc?iart??p!pohs??re&enigne?tac??t&ad?ekram!.&htiw,morf,??hgil?lusnoc?neg?ov?soh!.tfarcnepo,??vi&g?l???o!s??u&rehcisrev?smas?tarebsnegömrev???o&d?lb?og!.&duolc,etalsnart,???r&2n084qlj--nx?ebmoolb?o!.&77ndc.c:sr,,a&remacytirucesym,t&neimip,sivretla,?z,?bew-llams,d&ab-yrev-si,e&sufnocsim,vas-si,?nuof-si,oog-yrev-si,uolc&arfniarodef,mw,??e&a,cin-yrev-si,grof&loot,peh,?l&as-4-ffuts,poeparodef,?m&-morf,agevres,ohruoyslles,?n&ozdop,uma.elet,?r&ehwongniogyldlob,iwym,uces-77ndc.nigiro.lss,?t&adidnac-a-si,is&-ybboh,golb,???fehc-a-si,golbymdaer,k&eeg-a&-si,si,?h,nut,?l&i&amwt,ve-yrev-si,?lawerif&-ym,ym,?sd-ni,?m&acssecca,edom-elbac,?n&af&blm,cfu,egelloc,lfn,s&citlec-a-si,niurb-a-si,tap-a-si,?xos-a-si,?ibptth,o&itatsksid,rviop,?pv-ni,?o&jodsnd,tp&az,oh,??p&i&-on,fles,?o&hbew,tksedeerf,?tf&e&moh,vres,?ym,??r&e&gatop,ppepteews,su-xunil-a-si,?gmtrec,vdmac,?s&a&ila&nyd,snd,?nymsd,?b&alfmw,bevres,?d&ikcet.3s,ylimaf,?eirfotatophcuoc,j,koob-daer,ltbup,nd&-won,deerf,emoh,golb,kcud,mood,nyd:.&emoh,og,?,ps,rvd,tog,uolc,?s&a-skcik,ndd,?tnemhcattaomb,u,?t&ce&jorparodef.&duolc,gts.so.ppa,so.ppa,?riderbew,?e&ews-yrev-si,nretni&ehtfodne,fodne,??hgink-a-si,oi-allizom,s&ixetn&od,seod,?o&h-emag,l-si,?rifyam,??ue:.&a&-q,c,?cm,dc,e&b,d,e,i,m,s,?g&b,n,?hc,i&f,s,?k&d,m,s,u,?l&a,i,n,p,?n&c,i,?o&n,r,ssa,?pj,r&f,g,h,k,t,?s&e,i:rap,,u,?t&a,en,i,l,m,ni,p,?u&a,de,h,l,r,?vl,y&c,m,?z&c,n,??,vresnyd,x&inuemoh,unilemoh,?y&limafxut,srab,???ub&mah?oj???s!.&delacsne,gro?moc?rep?t&en?opsgolb,?ude?vog??gb639j43us5--nx??t?u!.&c&a?s??en?gro?moc?o&c?g??ro?topsgolb,??v!.ta,a1c--nx??wsa08--nx??h&0ee5a3ld2ckx--nx?4wc3o--nx!.&a&2xyc3o--nx?3j0hc3m--nx?ve4b3c0oc21--nx??id1kzuc3h--nx?l8bxi8ifc21--nx?rb0ef1c21--nx???8&8yvfe--nx?a7maabgm--nx??b!.&gro?moc?ten?ude?vog??mg??c!.&7erauqs,amil4,duolc-drayknil,gniksnd,p&h21,ohsdaerpsym,?sndtog,topsgolb,wolf.e&a.1pla,nigneppa,?xi2,ytic-amil,?aoc?et?ir!euz??r&aes!errecnac??uhc??sob?taw!s???d0sbgp--nx?f&2lpbgm--nx?k??g!.&gro?lim?moc?ude?vog???m!a1j--nx??ocir?p!.&gro?i?lim?moc?ogn?ten?ude?vog???s!.&g&nabhsah,ro??l&im?xv,?m&oc?roftalp.&cb,su,tne,ue,??pib,ten?vog?won,yolpedew,?a&c?nom??i&d?f?ri???t!.&ca?enilno,im?ni?o&c?g??pohs,ro?ten??iaf!.oby,?laeh!.arh,?orxer?ra&ba?e???vo!.lopdren,?zb??i&3tupk--nx?7a0oi--nx?a!.&ffo?gro?moc?ten?uwu,?1p--nx?bud?dnuyh?tnihc??b!.&gro?moc?oc?ro?ude??ahduba?o!m!.&duolcsd,ysrab,???s??c!.&ayb-tropora--nx?ca?d&e?m??esserp?gro?ln,moc?nif,o&c?g?ssa??ro?t&en?ni?roporéa??ude?vuog??cug?t??d&dk?ua??e&bhf--nx?piat??f!.&aw5-nenikkh--nx,dnala?i&ki,spak,?mroftalpduolc.if,nenikkäh,pohsdaerpsym,retnecatad.&omed,saap,?topsgolb,yd,?onas??g!.&d&om?tl??gro?moc?ude?vog???h&c&atih?ra??s&abodoy?ibustim???juohs?k!.&gro?moc?ofni?ten?ude?vog?zib??b4gc--nx?iw?nisleh?s?uzus??l!.&aac,topsgolb,?drahcir?iamsi??maim?n!.&b&ew?og??ca?gro?lim?mo&c?n??ni?o&c?fni??pp?t&en?ni??ude?zib??airpic?i&hgrobmal?m??re??om?rarref?s!.&egaptig,ppatig,topsgolb,?ed??t&aresam?i&c?nifni??rahb?tagub??ut?v!.&21k?gro?moc?oc?ten???wik?xa&rp?t??yf??j&6pqgza9iabgm--nx?8da1tabbgl--nx?b!.&ossa?topsgolb,uaerrab?vuog???d?f!.&ca?eman?gro?lim?moc?o&fni?rp??ten?vog?zib???nj?s?t!.&bew?c&a?in??eman?gro?lim?moc?o&c?g??t&en?ni?set??ude?vog?zib???yqx94qit--nx??k&8uxp3--nx?924tcf--nx?arfel?c&a&bdeef?lb??ebdnul?ilc?reme??d!.&erots,ger,mrif,oc,pohsdaerpsym,topsgolb,zib,?t??e&es?samet??h!.&a&4ya0cu--nx?5wqmg--nx??b3qa0do--nx?cni,d&2&2svcw--nx?3rvcl--nx??5xq55--nx?tl,?g&a0nt--nx?la0do--nx?ro??i&050qmg--nx?7a0oi--nx?xa0km--nx??m&1qtxm--nx?oc??npqic--nx?saaces,t&en?opsgolb,?ude?v&di?og?ta0cu--nx??xva0fz--nx?人&个?個?箇??司公?府政?絡&網?网??織&組?组??织&組?组??络&網?网??育&敎?教???n??i&tsob?vdnas??l!.&bew?c&a?os??dtl?gro?hcs?letoh?moc?nssa?ogn?prg?t&en?ni??ude?vog??at?cd?is??m!.&eman?fni?gro?moc?t&en?opsgolb,?ude?vog???n&ab!cfdh?etats?mmoc?t&en?fos??u??i!l!.&noyc,pepym,??p???oob?p!.&b&ew?og??gro?kog?m&af?oc??nog?ofni?pog?sog?ten?ude?vog?zib???row!.&morf,ot,?ten!.&htumiza,nolt,o&c,vra,??doof???s!.topsgolb,?t?u!.&c&a?lp??d&om?tl??e&cilop?m??gro!.&gul:g,,sgul,yr&ettoly&lkeew,tiniffa,?tneelffar,???lenap-tnednepedni,n&noc,oissimmoc-&layor,tnednepedni,??o&c!.&bunsorter.tsuc,e&lddiwg,n&ilnoysrab,ozgniebllew,??krametyb.&hd,mv,?omida,p&i-on,ohsdaerpsym,?t&fihsreyal.j,opsgolb,?vres-hn,ysrab,??rpoc,?psoh,shn?t&en?nmyp,seuqni-tnednepedni,?vog!.&eci&ffoemoh,vres,?ipa,??weiver-tnednepedni,y&riuqni-&cilbup,tnednepedni,?srab,????l&04sr4w--nx?a!.&gro?lim?moc?t&en?opsgolb,?ude?vog??bolg?c?ed?g!el??i&c&nanif!.oc,lpl??os??romem?tnedurp??n&if?oitanretni??t&i&gid!.sppaduolc:.nodnol,,?p&ac?soh???ned?ot??utum!nretsewhtron???c!.&bog?lim?oc?topsgolb,vog???dil?e&datic?n&ahc?nahc!gnikooc?levart?rehtaew???t!ria?tam??vart??f&8f&pbgo--nx?tbgm--nx??a?n??g!.&gro?moc?oc?ten?ude?xx,zib,??h&d?op??i!.&21k?ca?fdi?gro?inum?oc!.&egapvar,redrotibat,topsgolb,??ten?vog??a&f?m&e?g?toh???m?r??l&a&b&esab?t&eksab!.&sua,zn,??oof???c?mt??e&d?hs??ihmailliw?j??m!.&esserp?gro?moc?ten?ude?v&og?uog????n!.&no&med,rtsic,?oc,pohsdaerpsym,retsulc-gnitsoh,topsgolb,yalphk,?o??o&a?btuf?l!.gmo,?o&c!.&ed,rotnemele,??hcs??rit?u??p!.&a&cin&diws?gel??d&g,ortso?urawon??i&dem?mraw?nydg,?k&elo&guld?rtso??slopolam?tsu?ytsyrut??l&ip?o&kzs?w&-awolats?oksnok????n&erapohs,img?zcel,?rog&-ai&bab?nelej??j?z??syn?tsaim?w&a&l&eib?i?o??zsraw??o&namil?tainop,??z&eiwolaib?mol???c&e&iw&alselob?o&nsos?rtso???le&im?zrogz???orw,p??d&em,ia?ragrats?uolc&inu,sds,??e&c&i&lrog?w&ilg,o&hc&arats?orp??klop?tak????yzreibok??i&csjuoniws?ksromop?saldop??l&ahdop?opo??napokaz,tatselaer?z&romop?swozam???g&alble?ezrbo&lok?nrat??ro??hcyzrblaw?i&csomohcurein?grat?klawus??k&e&rut?walcolw??in&byr?diws,sark,?le?o&nas?tsylaib??rob&el?lam??s&als?jazel?nadg,puls?rowezrp???l&colw?e&r?vart??i&am?m???m&o&c?dar?n?tyb??s&g?iruot??t!a???n&a&gaz?nzop,?i&bul?cezczs?lbul,molow?nok?zd&eb?obeiws???uleiw?y&tzslo?z&rtek?seic????o&c,fni?k&celo?zdolk??lkan?n&leim?pek?t&uk?yzczs??z&copo?eing?rowaj???rga?tua?w&ejarg?ogarm???p&e&eb,lks!emoh,??klwwortso?ohs!-ecremmoce,daerpsym,??romophcaz?sos?t&aiwop?en?opos,ra,sezc??ude?v&irp?og!.&a&p?s!w???bni&p?w??ci?dtiw?essp?fiw?g&imu?u??hiiw?m&igu?rio?u!o???nds?o&ks?p!pu??s?wtsorats??p&a?sp!mk?pk?wk??u&m?p??wk?z??r&ksw?s??s&i?oiw?u?zu??talusnok?w&gzr?i&p?rg?w??m?opu?u!imzw???zouw????w&a&l&corw?sizdow??w??o&golg?k&ark,ul?zsurp??r&az?gew??t&rabul,sugua??z&coks?sezr????xes?y&buzsak?d&azczseib?ikseb??hcyt?n&jes?lod-zreimizak??pal?r&ogt?uzam??walup?zutrak??z&am-awar?c&aprak?iwol?zsogdyb??dalezc?ib?s&i&lak?p??uklo????l??r&as?f?s??s!.&gro?moc?ten?ude?vog???t!.vog??ubnatsi?x3b689qq6--nx?yc5rb54--nx??m&00tsb3--nx?1qtxm--nx?981rvj--nx?a!.&aayn,enummoc?gro?moc?o&c?idar,ken,?t&en?opsgolb,??c!bew??dretsma?e&rts?t!.&citsalej,esruocsid,???fma?xq--nx??b!.&gro?moc?ten?ude?vog??i??c!.&moc?oc?ten?vog???d!.&gro?moc?ten?ude?vog???f!.&gro?moc?oidar,ten?ude??i??g!vu96d8syzf--nx??h?i!.&ca?gro?moc?o&c!.&clp?dtl???r,?t&en?t??vt??k?rbg4--nx??k!.&drp?e&rianiretev?sserp??gro?lim?m&o&c?n??t??nicedem?ossa?pooc?s&eriaton?neicamrahp?sa??ude?v&og?uog????l&if?ohkcots??o!.&dem?gro?m&oc?uesum??o&c?rp??ten?ude?vog??b?c!.&2aq,3pmevres,5sndd,a&c&-morf,ir&bafno,fa,??g&-morf,oy-sehcaet,?i-morf,m&-morf,all&-a-si,amai,??p&-morf,c-a-si,?r&emacytirucesym,odih,?s,tadtsudgniht,v-morf,w-morf,z,?b&dnevarym,ew&-sndnyd,draiw.segap,ottad,?ildts.ipa,?c&amytirucesemoh,d-morf,esyrcs,itsalej.omed,n&-morf,vym,?p&kroweht,ytirucesemoh,?q,rievres,s-morf,?d&aerotffuts,e&calpb,ifitrec-&si,ton-si,?llortnocduolc,rewopenignepw:.sj,,tsohecapsppa,?i&-morf,rgevissam.saap,?m-morf,n&-morf,abeht-htiw-si,?s-morf,uolc&-noitatsyalp,hr,iafaw.&d&ej,yr,?nol,?meaeboda,panqym:-&ahpla,ved,?,smetsystuo,tekcilc,ved&j,pw,??vreser,wetomer,?e&butuoyhtiw,ciffo-sndnyd,d:-morf,o&celgoog,n&il.srebmem,neve.&1-&su,ue,?2-&su,ue,?3-&su,ue,?4-&su,ue,????,erf&-sndnyd,sndd,?filflahevres,gnahcxeevres,i&hcet-a-si,p-sekil,?k&auqevres,irtsretnuocevres,?l&bitpa-no,googhtiw,?m&agevres,ina-otni-si,oh-&sndnyd,ta-sndnyd,??n&-morf,ilno&-evreser,ysrab,?og-si,?r&alfduolcyrt,ehwynanohtyp:.ue,,ihcec,?srun-a-si,t&i&nuarepo,s&-ybboh,aloy,tipohs,xiw,??omer-sndnyd,upmocsma,ysgolb,?v&als-elcibuc-a-si,i&lsndd,tavresnoc-a-si,??z&amkcar,eelg,iig,??fehc-a-si,g&ni&gats-&raeghtua,swennwot,?ksndd,robsikrow,tsoh-bt.etis,?o&fgp,lb&-sndnyd,pawodni,sihtsetirw,???h&n-morf,o-morf,?i&fiwehtno,h-morf,kiw-sndnyd,m-morf,pdetsoh,r-morf,w-morf,z&ihcppa,nilppa,??jn-morf,k&a&-morf,erfocsic,?cils-si,eeg&-a&-si,si,?sndd,?h,latsnaebcitsale:.&1-&htuos-pa,lartnec-&ac,ue,?ts&ae&-&as,su,?ht&ron-pa,uos-pa,??ew-&su,ue,vog-su,???2-ts&ae&-su,ht&ron-pa,uos-pa,??ew-&su,ue,??3-ts&aehtron-pa,ew-ue,??,o-morf,r&adhtiwtliub,ow&-&sndnyd,ta-sndnyd,?ten-orehkcats,??u,?l&a&-morf,colottad,rebil-a-si,?f-morf,i&-morf,am&-sndnyd,detsohpw,??l&ecelffaw,uf-ytnuob:.a&hpla,teb,?,?ppmswa,ru-&elpmis,taen,?ssukoreh,xegap,?m&n-morf,pml.ppa,rofe&pyt.orp,rerac-htlaeh,?sacrasevres,uirarret-yltsaf,?n&a&cilbuper-a-si,f&-sllub-a-si,racsan-a-si,?i&cisum-a-si,ratrebil-a-si,??c,dc&hsums,umpw,xirtrepmi,?eerg-a-si,i-morf,m-morf,o&ehtnaptog,isam-al-a-tse,r&italik,tap-el-tse,?s&iam-al-a-tse,replausunu,??pj,t-morf,?o&bordym,c,hce-namtsop,jodsnd,m&-morf,ed-baltlow,?n:iloxip,,ttadym,?p&2pevres,aelutym,i&-sndnyd,fles,ogol,ruoy&esol,hctid,?ym&eerf,teg,??ohsdaerpsym,pa&-rettalp,anis:piv,,esaberif,k1,lortnocduolc,oifilauq,r&aegyks,oetem:.ue,,?tnorfegap,ukoreh,?t&fevres,thevres,??r&a:-morf,tskcor-a-si,,b,e&d&iv&erp-yb-detsoh.saap,orpnwo,?ner&.ppa,no,??e&bevres,nigne-na-si,?ggolb&-a-si,ndi,?h&caet-a-si,pargotohp-a-si,?krow-drah-a-si,n&gised-a-si,ia&rtlanosrep-a-si,tretne-na-si,??p&acsdnal-a-si,eekkoob-a-si,?retac-a-si,subq,tn&ecysrab,iap-a-si,uh-a-si,?vres&-&ki.&cpj-rev-duolcj,duolcj,?s&ndnyd,pvtsaf,??inim,nmad,sak,?y&alp-a-si,wal-a-si,?zilibomdeepsegap,?g,ituob,k,mgrp.nex,o&-morf,sivdalaicnanif-a-si,t&areleccalabolgswa,c&a-na-si,od-a-si,?susaym,??p-morf,u&as-o-nyd,e&tsoh.&duolc-gar,hc-duolc-gar,?ugolb-nom-tse,?omuhevres,??s&a&apod,ila&nyd,snd,?nymsd,vnacremarf,?bbevres,ci&p&-sndnyd,evres,?tcatytiruces,?dylimaf,e&cived-anelab,itilitu3,lahw-eht-sevas,mag-otni-si,t&i&iis,sro,?yskciuq,??i&ht2tniop,pa&elgoog,tneltneg,??jfac,k&-morf,aerf-ten,colb&egrof,pohsym,??m&-morf,cxolb,?n&d&-pmet,dyard,golb,htiwssem,mood,tog,?kselp,nyd,ootrac-otni-si,?o&-xobeerf,xobeerf,?ppa&raeghtua,tneg,?r&ac-otni-si,e&ntrap-paelut,tsohmaerd,??s&e&l-rof-slles,rtca-na-si,?ibodym,?tsaeb-cihtym.&a&llicno,zno,?ilay,lacarac,re&gitnef,motsuc,?sv,toleco,x:n&ihps,yl,?,?u,wanozama.&1-&htuos-pa&-3s,.&3s,etisbew-3s,kcatslaud.3s,??la&nretxe-3s,rtnec-&ac&-3s,.&3s,etisbew-3s,kcatslaud.3s,??ue&-3s,.&3s,etisbew-3s,kcatslaud.3s,????ts&ae&-&as&-&3s,etisbew-3s,?.kcatslaud.3s,?su:-etisbew-3s,.kcatslaud.3s,,?ht&ron-pa&-&3s,etisbew-3s,?.kcatslaud.3s,?uos-pa&-&3s,etisbew-3s,?.kcatslaud.3s,???ew-&su-&3s,etisbew-3s,?ue&-&3s,etisbew-3s,?.kcatslaud.3s,?vog-su-&3s,spif-3s,????2-ts&ae&-su&-3s,.&3s,etisbew-3s,kcatslaud.3s,??ht&ron-pa&-3s,.&3s,etisbew-3s,kcatslaud.3s,??uos-pa&-&3s,etisbew-3s,?.kcatslaud.3s,???ew-&su-&3s,etisbew-3s,?ue&-3s,.&3s,etisbew-3s,kcatslaud.3s,????3&-tsew-ue&-3s,.&3s,etisbew-3s,kcatslaud.3s,??s,??yasdrocsid,?t&arcomed-a-si,c&-morf,etedatad.&ecnatsni,omed,??eel&-si,rebu-si,?hgilfhtiwletoh,m-morf,n&atnuocca-na-si,e&duts-a-si,r-ot-ecaps,tnocresu&buhtig,e&capsppa,donil.pi,lbavresbo.citats,?pl,???ops&edoc,golb,ppa,?s&i&hcrana-&a-si,na-si,?laicos-a-si,pareht-a-si,tra-na-si,xetn&od,seod,??oh&piym,sfn,??u&-morf,nyekcoh-asi,?v-morf,?u&-rof-slles,4,e,h,oynahtretramssi,r:ug-a-si,,?v&n-morf,rdlf,w-morf,?w&o&lpwons-yrt,zok,?ww100,?x&bsbf.sppa,em,i&nuemoh,rtrepmi,?obaniateb,t-morf,unilemoh,?y&a&bnx:.&2u,lacol-2u,?,l&erottad,pezam,?wetag-llawerif,?dnacsekil,fipohsym,k&-morf,niksisnd,?rotceridevitcaym,u:goo,,w-morf,x&alagkeeg,orp&hsilbup,mapson.duolc,???zesdrocsid,?inu??m!.&dna,rof,??or?tsla??p!.nwo,?raf!.jrots,etats??s?t!.&gro?lim?mo&c?n??oc?ten?ude?vog???u&esum!.&a&92chg-seacinumocelet-e-soierroc--nx?atnav?c&i&aduj?rfatsae??rollam??d&anac?enomaledasac?irolf??e&raaihpledalihp?srednu??g&hannavas?oonattahc??hamo?i&auhsu?bmuloc!hsitirb??dem?groeg?hpledalihp?l&artsua?etalif??n&igriv?rofilac??ssur?tsonod??ksa&la?rben??l&lojal?q-snl--nx?uossim!trof???m&a&bala?nap??enic?o&m?r???n&a&cirema?idni??edasap?ilorachtuos?olecrab??r&abrabatnas?ezzivs??su?t&nalta?osennim??zalp??c&dnotgnihsaw?ebeuq?i&depolcycne?ficap?hpargonaeco?lbup?sum?t&carporihc?lec?naltadim??vu??yn??d&a&dhgab?etsmraf?m?orliar??i&rdam?ulegnedleeb??leif?n&a!l&gne?nif?ragyduj?t&ocs?rop??yram???u&brofsdgybmeh?osdnaegami???r&augria?ofxo???e&c&a&l&ap?phtrib??ps??n&a&lubma?tsiser??e&fedlatsaoc?gilletni?ics!foyrotsih????pein?rof??d&nukneklov?revasem??e&rt?tsurt??f&atnas?ildliw??g&a&lliv?tireh!lanoitan???dirbmac?rog??i&cnum?nollaw??koorbrehs?l&ab?bib?cycrotom?i&ssim?txet??oks?tsac??m&affollah?it!iram??utsoc??n&golos?ilno?recul??r&a&uqs?waled!foetats???i&hs&acnal?kroy?pmahwen??otsih??omitlab?ut&an?cetihcra?inruf?luc!irga?su???vuol??s&abatad?iacnarf?sius?uoh!lum???t&a&locohc?rak?ts!e!yrtnuoc!su?????imesoy?tevroc??u&qihpargonaeco?velleb??vit&caretni?omotua???f&iuj?ohgrub??g&n&i&dliub?ginerevmuesum?kiv?lahw?nim?peekemit?vil??ulmmastsnuk??orf?r&ebnrats?u&b&ierf?le?m&ah?uan??ram?s&mailliw!lainoloc??naitsirhc?retepts??zlas??ob&irf?mexul?????h&atu?c&raeser?sirotsih?uot??g&ea1h--nx?rubsttip??si&tirb?wej??t&laeh?ro&n?wtrof??uo&mnom?y????i&d6glbhbd9--nx?iawah?k&nisleh?s??lad!rodavlas??sissa?tannicnic??k&c&nivleeg?olc!-dna-hctaw?dnahctaw???fj?inebis?l&is?ofron??na&rfenna?t??oorbnarc?r&am&ned?reiets??oy!wen????l&a&ci&dem?golo&eahcra?meg?oz??natob?rotsih??ertnom?iromem?noita&cude?n??oc?rutluc?trop?utriv?van??e&nurb?s&ab?surb??utriv??i&artnogero?sarb??l&a&besab?hsnoegrus??e&hs?rdnevle??i&b?m!dniw????o&bup?ohcs?tsirb???m&a&dretsma?ets?h&netlehc?rud???ct?elas!urej??l&if?ohkcots?u??raf?silanruoj?u&esumyrotsihlarutan?ira&tenalp?uqa??terobra???n&a&c!irema!evitan???gihcim?i&dni?tpyge??mfoelsi?wehctaksas??e&d&alokohcs?ews?rag!cinatob?lacinatob?s&nerdlihc?u????gahnepoc?hcneum?laftsew?ppahcsnetewruutan?r&dlihc?ednaalv?hu!dnutamieh???sseig??gised!dn&atra?utsnuk???h&ab!nesie??ojts??i&lreb?tsua??l&eok?ocnil??n&ob?urbneohcs??o&dnol?gero?i&s&iv&dnadnuos?elet??nam??t&a&c&inummoc?ude!tra???dnuof?erc?i&cossa?va??kinummokelet?nissassa?r&belectsevrah?oproc?tsulli??silivic?t&nalp?s??vres&erp?noclatnemnorivne??zilivic??c&elloc?if-ecneics??ibihxe???ri?s&dnah?imaj?reffej?sral??t&erbepac?nilc?sob???r&e&b?dom?tsew?uab?zul??obredap??vahnebeok?wot??o&2a6v-seacinumoc--nx?ablib?c&edtra?ixemwen?sicnarfnas??elap?g&a&cihc?to??eidnas??i&cadnuf?diserp?ratno??llecitnom?mitiram?nirot?r&htna?ienajedoir???pohskrow?qari?r&aw!dloc?livic??dd?e&b&ma?yc??irrac?llimsiwel?naksiznarf?papswen?t&aeht?exe?nec!ecneics?larutluc?muesum?tra??s&ehc&nam?or??neum??upmoc???ia!nepo??obal?u&asonid?obal?takirak???s&a&l&g?l&ad?eh???xet??di&k?pardnarg??e&cneics!larutan??dnal?hcsi&deuj?rotsih!nizidem?rutan??selhcs??itinamuh?l&aw?egnasol?l&e&rutansecneics?xurb??iasrev???r&e&em?ugif??tsac??suohcirotsih?u&en?q&adac?itna!nacirema?su????õçacinumoc!elet-e-soierroc???gnirpsmlap?htab?i&lopanaidni?rap?uoltnias?xa??l&essurb?lod??mraeriflanoitan?n&a&blats?l??erdlihc?oi&snam?tacinummoc!elet-dna-stsop???äl??re&dnalf?lttes?mraf?nim?tnececneics??s&alg?erp??t&farc!dnastra??nalp?olip?ra!e&nif?vitaroced!su???su?xuaeb???u&b!muloc??cric???t&agilltrop?cejorp?dats?e&esum?kramnaidni??iorted?ne&m&elttes?norivne?piuqemraf??vnoc??oped?r&a!drib?enif?gttuts?hsiwej?kcor?n&acirema?ootrac??tamsa?yraropmetnoc??op&aes?snart?wen??ufknarf??s&a&cdaorb?octsae??ewhtuos?ilayol?nuk?r&ohnemled?uhlyram??urt???u&a&bgreb?etalpodaroloc??rmyc??w&ocsom?rn??x&esse?ineohp?nam?tas??y&a&bekaepasehc?w&etag?liar???camrahp?doc?e&hsub?l&ekreb?l&av!eniwydnarb??ort???n&dys?om??rrus?s&nreug?rejwen???golo&e&ahcra?g??motne?nh&cet?te??oz?po&rhtna?t??roh??hpargotohp?l&etalihp?imaf??m&edaca?onortsa??n&atob?yn??ps?r&a&ropmetnoc?tilim??e&diorbme?llag!tra??vocsid??lewej?nosameerf?otsih!dnaecneics?ecneics?gnivil!su??la&col?rutan??retupmoc?su??tsudnidnaecneics??spelipe?t&eicos!lacirotsih??i&nummoc?srevinu??nuoc???z&arg?iewhcs?nil?ojadab?urcatnas??моки?םילשורי???rof??z!.&ca?gro?hcs?lim?moc?o&c?fni??ten?ude?vog?zib????n&315rmi--nx?a&brud?cilbuper?f?grompj?hkaga?idraug?m?ol?ssin?u&hix?qna??varac?yalo??b!.&gro?moc?oc,ten?ude?vog??c??c!.&ah?bh?c&a?s??d&5xq55--nx?g?s?uolctnatsni,?eh?g&la0do--nx?ro??h&a?q?s??i&7a0oi--nx?h??j&b?f?t?x?z??kh?l&h?im?j??m&n?oc!.swanozama.&1-htron-nc.3s,be.1-&htron-nc,tsewhtron-nc,????n&h?l?s?y??om?qc?s&g?j??ten?ude?vog?wt?x&g?j?n?s??z&g?x??司公?絡網?络网??b??d&g!.ypnc,?ka??e&drag?erg?fuak?gawsklov?hctik?i&libommi?w??m!.r&iaper,of,??po?r!ednaalv??sier?ves??g!.&ca?gro?moc?ten?ude?vog??is&ed!.ssb,?irev???h!.&bog?cc,gro?lim?moc?ten?ude???i!.&bew,c&a?in??dni?esabapus,gro?lim?mrif?neg?oc?s&er?nduolc,?t&en?opsgolb,?ude?vog?ysrab,?elknivlac?griv?ks?lreb?p?v?w!.taht,?x??k!.&gro?ten?ude?vog???l&eok?ocnil??m!.&cyn,gro?ude?vog???o&dnol!.&fo,ni,??i&hsaf!.fo,?n&o?utiderc??siv!orue??t&a&cude!.oc,?dnuof?tsyalp??c&etorp?u&a?rtsnoc?????kin?las?mrom?nac?p&q?uoc??s&iam?pe?scire??t&ron?sob??zama??p!.&gro?oc?ten?ude?vog??k??r&e&c?yab??op!.eidni,??s!.&gro?moc?osrep?t&opsgolb,ra??ude?v&inu?uog????t!.&d&ni?uolcegnaro,?gro?ltni?m&oc!nim??siruot??nif?o&fni?srep??sne?t&an?en??vog??m??u&f?r!.&bdnevar,lper,retropno,s&h,revres,?tnempoleved,??stad?xamay?y??v!.&ca?eman?gro?htlaeh?moc?o&fni?rp??t&en?ni?opsgolb,?ude?vog?zib???wo&rc?t!epac????o&76i4orfy--nx?a!.&bp?de?go?oc?ti?vg??boat??b!.&a&ci&sum?tilop??i&c&arcomed?neic??golo&ce?ncet??m&edaca?onoce??rt&ap?sudni??vilob??n&egidni?icidem??serpme?tsiver?vitarepooc??b&ew?og??dulas?e&rbmon?tr&a?op&ed?snart????g&olb?ro??ikiw?l&a&noi&canirulp?seforp??rutan??im??moc?o&fni?lbeup?rga?tneimivom??saiciton?t&askt?en?ni??ude?vt??h?iew?olg??c!.&bew?cer?dr&c,rac,?esabapus,gro?ipym,l&im?per:.di,,?m&o&c!.topsgolb,?n??rif??ofni?s&egap&dael,l,?tra??t&4n,en?ni??ude?vog??a?e?in?mara?s&edarb?ic???d!.&b&ew?og??dls?gro?lim?moc?t&en?ra??ude?vog??agoba?if?zd7acbgm--nx??e&c?d&iv?or??morafla??f!ni!.&e&g&delwonk-fo-l&errab,lerrab,?ellocevoli,?ht-skorg,rom-rof-ereh,tadpusn:d,,?llatiswonk,macrvd,ofni-v,p&i&-on,fles,?ohbew,?ruo-rof,s&iht-skorg,nd&-cimanyd,nyd,uolc,??tsrifyam,ysrab,zmurof,???g&el?n!am?ib???hwsohw?i!.&35nyd,8302,a&minifed,tad-b,?b&altig,uhtig,?czh,d&in,u&olc&iaznab.ppa,ropav,?rd,??e&c&apsinu.1rf-duolc,ivedniser,?donppad.sndnyd,egipa,lej,nilnigol,sufxob,t&i&beulb,snoehtnap,?newtu,ybeeb.saap,??gni&gatsniser.secived,tsohytsoh,?ilpu,k&coregrof.di,orgn,ramytefasresworb,?moc?n&mtsp:.kcom,,yded,?ot&oq,pyrctfihs,?p&opilol,pa&-arusah,e&nalpkcab,tybeeb.1dkes,???r&e&tsneum-hf,vres&cisab,lautriv,??ial.sppa,?s&codehtdaer,gnihtbew,nemeis-om,pparevelc,t&acdnas,ekcit,??t&e&kcubtib,notorp,?i&belet,detfihs,gude,kecaps,?raedon.egats,s&ohg,udgniht.&cersid.&dvreser,tsuc,?dorp.tsuc,gnitset.&dvreser,tsuc,?ved.&dvreser,tsuc,????vgib.0ku,whs,x&bslprbv.g,cq,rotide,?y&olpedew,srab,??b?d&ar?u&a?ts???j?r?syhp??j!.&eman?gro?hcs?lim?moc?ten?ude?vog???ll&ag?o??m!.&gro?moc?ten?ude?vog??g?il?mi?orp??n!.&a&0&b-ekhgnark--nx?c-iehsrgev--nx?g-lksedlig--nx?k-negnanvk--nx??1&p-nedragy--nx?q-&asierrs--nx?grebsnt--nx?lado-rs--nx?n&egnidl--nx?orf-rs--nx??regnayh--nx?ssofenh--nx??r-datsgrt--nx?s-ladrjts--nx?v-y&senner--nx?vrejks--nx???3g-datsobegh--nx?4&5-&dnaleprj--nx?goksnerl--nx?tednalyh--nx??6-neladnjm--nx?s-&antouvachb--nx?impouvtalm--nx??y-&agrjnevvad--nx?ikhvlaraeb--nx???7k-antouvacchb--nx?8&k-rekie-erv--nx?l-ladrua-rs--nx?m-darehsdrk--nx??a!.sg??bct-eimeuvejsemn--nx?d&do?iisevvad?lov?narts?uas??f&1-&l--nx?s--nx??2-h--nx??g&10aq0-ineve--nx?av?ev?lot?r&ajn&evvad?u??ájn&evvad?u????h?iz-lf--nx?j&ddadab?sel??k&el?hoj&sarak?šárák??iiv&ag&na&el?g??ŋ&ael?ág???ran???l&f?lahrevo?o&ms?s??sennev?t-&ilm--nx?tom--nx??u&-edr--nx?s??øms??muar?n&0-tsr--nx?2-dob--nx?5-&asir--nx?tals--nx??a&r!-i-om?f?t??t??douvsatvid?kiv?m&os?øs??n&od?ød??ra?sen?t&aouvatheig?ouv&a&c&ch&ab?áb??h&ab?áb???n??i&ag?ág??sa&mo?ttvid??án???z-rey--nx?ær&f?t???o&p-&ladr--nx?sens--nx??q-nagv--nx?r-asns--nx?s-kjks--nx?v-murb--nx?w-&anr&f--nx?t--nx??ublk--nx???ppol?q&0-t&baol--nx?soum--nx?veib--nx??x-&ipphl--nx?r&embh--nx?imph--nx???y-tinks--nx??r&f-atsr--nx?g-&an&ms--nx?nd--nx??e&drf--nx?ngs--nx??murs--nx?netl--nx?olmb--nx?sorr--nx??h-&a&lms--nx?yrf--nx??emjt--nx??i&-&lboh--nx?rsir--nx?y&d&ar--nx?na--nx??ksa--nx?lem--nx?r&ul--nx?yd--nx????stu??j-&drav--nx?rolf--nx?sdav--nx??kua?l-&drojf--nx?lares--nx??m-tlohr--nx?n-esans--nx?olf?p-sdnil--nx?s-ladrl--nx?tih?v-rvsyt--nx??s&a&ns?ons??i&ar?er&dron?r&os?øs???ár??la&g?h??mor!t??sir?uf?åns??t&koulo&nka?ŋká??la?p-raddjb--nx?r-agrjnu--nx?s&aefr&ammah?ámmáh??orf?r&o?ø???u-vreiks--nx??u&h-dnusel--nx?i-&drojfk--nx?vleslm--nx??j-ekerom--nx?k-rekrem--nx?u-&dnalr--nx?goksr--nx?sensk--nx??v-nekyr--nx?w-&k&abrd--nx?ivjg--nx??oryso--nx??y-y&dnas--nx?mrak--nx?n&art--nx?nif--nx??reva--nx??z-smort--nx??v!.sg?ledatskork?reiks??wh-antouvn--nx?x&9-dlofts--nx.aoq-relv--nx?d-nmaherk--nx?f-dnalnks--nx?h-neltloh--nx?i-drgeppo--nx?j-gve&gnal--nx?lreb--nx??m-negnilr--nx?n-drojfvk--nx??y&7-ujdaehal--nx?8-antouvig--nx?b-&dlofrs--nx?goksmr--nx?kivryr--nx?retslj--nx??e-nejsom--nx?f-y&krajb--nx?re&dni--nx?tso--nx??stivk--nx??g-regark--nx?orf?ørf??z9-drojfstb--nx??b&25-akiivagael--nx?53ay7-olousech--nx?a&iy-gv--nx?le-tl&b--nx?s--nx??n0-ydr--nx??c&0-dnal-erdns--nx?z-netot-erts--nx??g&g-regnarav-rs--nx?o-nejssendnas--nx??ju-erdils-ertsy--nx?nj-dnalh-goksrua--nx?q&q-ladsmor-go-erm--nx.&ari-yreh--nx?ednas??s-neslahsladrjts--nx???ca&4s-atsaefrmmh--nx?8m-dnusynnrb--nx?il-tl--nx?le-slg--nx?n5-rdib--nx?op-drgl--nx?uw-ynnrb--nx??d&a&qx-tggrv--nx?reh!nnivk?sd&ork?ørk??uas??ts&e&bi?kkar?llyh?nnan??g&ort?ørt??k&alf?irderf??levev?mirg?obeg&ah?æh??r&ah?ejg????barm-jdddb--nx?ie!rah?s&etivk?ladman???lof&r&os?øs??ts&ev.ednas?o.relav?ø.relåv???n&a&l&-erd&n&os?øs??ron??adroh.so?dron.&a&g5-b--nx?ri-yreh--nx??ob?y&oreh?øreh??øb??e&m!lejh??pr&oj?øj??vi??gyb?n&aks?åks??o&h-goksrua?rf??r&o?ua?ø??tros?øh-goksrua??rts!e&devt?lab?mloh???s&ellil?naitsirk?rof???u&l!os??s!d&im?lejt??e&guah?l&a?å???kkoh?lavk?naitsirk?r&af?eg&e?ie???tef?y&onnorb?ønnørb?????r&a&blavs!.sg??g&eppo?la???o&j&f&a!dniv?k?vk??die?e&dnas?kkelf??llins?r&iel?ots??s&lab?t&ab?åb??yt??å!k??ævk??les??ts??åg&eppo?lå???ureksub.sen??e&ayb-yrettn--nx?d&ar?lom?r&of?øf??år??g&gyr?nats??i&meuv&ejsem&aan?åån??sekaal??rjea??j&d&ef?oks??les??k&er&aom?åom??hgna&ark?årk??iregnir?kot!s??s&ig?uaf???l&bmab?kyb?l&av?ehtats??oh??m&it?ojt?øjt??n&arg?g&os?øs??meh?reil?te?ummok?yrb??r&dils-erts&ev?y&o?ø???ua?vod??sa&ans?åns??t&robraa?spaav??urg??f&62ats-ugsrop--nx?a&10-ujvrekkhr--nx?7k-tajjrv-attm--nx??o!.sg?h??s!.sg??v!.sg???g&5aly-yr&n--nx?v--nx??a&llor?ve&gnal?lreb???n&av!snellu??org??oks&die?m&or?ør??ner&ol?øl??r&o?ø???r&eb!adnar?edyps?s&die?elf?gnok?n&ot?øt????obspras??uahatsla?åve&gnal?lreb???h&0alu-ysm--nx?7&4ay8-akiivagg--nx?5ay7-atkoulok--nx??a!.sg???i&e&hsr&agev?ågev??rf??k&h&avlaraeb?ávlaraeb??s??lm&a?å??mpouvtal&am?ám??pph&al?ál??rrounaddleid?ssaneve?ššáneve??j&0aoq-ysgv--nx?94bawh-akhojrk--nx??k&a&b&ord?ørd??jks?lleis??iv!aklejps?l&am?evs?u??mag?nel?ojg?r&a&l?n??epok?iel?y&or?ør???s&ah?kel?om??øjg??kabene?ojsarak?ram&deh.&aoq-relv--nx?rel&av?åv??so??e&let.&ag5-b--nx?ob?øb??ra???åjks??l&a!d&anrus?d&numurb?ron??e&gnard?nte?s&meh?sin??ttin??g&is?nyl??kro?l&em?l&ejfttah?of??u&ag-ertdim?s???n&am?era?gos?i&b?nroh?r??kos?nus?oj??o-&dron?r&os?øs???ppo?r&a!l?nram??e&gne?l?v??is?o&jts?ts??u&a-&dron?r&os?øs???h??å?æl?øjts??s&e&jg?nivk?ryf??kav?mor-go-er&om.&ednas?yoreh??øm.&ednas?yøreh???uag??t&las?rajh?suan??v&l&a?e-rots??u-go-eron??yt??ksedlig?res&a?å???bib&eklof?seklyf??es!dah??h!.sg??i&m?syrt??l&ejf?ov&etsua?gnit?ksa?sdie???n!.sg??o!.sg?boh?g?h??r!.sg??å!ksedlig??øboh??m&a&rah?vk??f!.sg??h!.sg??i&e&h&dnort?rtsua?ssej??rkrejb??ksa??ol?t!.sg??u&dom?esum?r&ab?drejg?evle?os?uh?æb?øs??ttals???n&a&g&av?okssman?åv??jlis?or?r&g?rev???e&d&do&sen?ton??lah?r&agy&o?ø??ojfsam???g&iets?n&a&l&as?lab??n&avk?ævk??t&arg?ddosen??v&al?essov???i&d&ol?øl??l&ar?ær???yl??reb??iks?k&srot?y&or?ør???l&a&d&gnos?n&er?ojm?øjm??om??tloh??ug?åtloh??mmard?ojs&om?sendnas??ppolg?s&lahsladr&ojts?øjts??o??t&o&l?t-erts&ev?o?ø???roh?øl??vly&kkys?nav??yam-naj!.sg??øjs&om?sendnas???g&orf?ujb??i&dnaort?vnarg??kob?ladendua?maherk&a?å??n&it?urgsrop??orf-&dron?r&os?øs???r&aieb?evats??sfev?uaks?yrts??o&6axi-ygvtsev--nx?c,d&ob?rav??ievs?kssouf?l&m&ob?øb??ous&adna?ech&ac?áč???so!.sg???msdeks?niekotuak?r&egark?olf?y&oso?øso???s&dav?mort???p&ed?ohsdaerpsym,p&akdron?elk???r&a&d&dj&ab?áb??iab??jtif?luag?mah?vsyt??e&gn&a&k&iel?ro??merb?n&at?mas??rav-r&os?øs??srop?talf?v&ats?el??y&oh?øh???ivsgnok??il?jkniets?k&a&nvej?rem?s&gnir?nellu???ie-er&den?v&o?ø???ram?sa?årem??la&jf?vh??m&b&ah?áh??mahellil??nnul?ts&l&oj?øj??ul??y&o?ø???imp&ah?áh??m!.sg??osir?t!.sg??ádiáb?ævsyt?øsir??s&adnil?en&dnas?e&dga?k&ri&b?k??som??ve??me&h?jg??nroh-go-ejve?s&a?ednil?k&o?ø??of?yt?å??tsev??gv?hf?igaval?o&r&or?ør??sman??so&fen&oh?øh??m?v??uh&lem?sreka.sen??å!dnil???t&a&baol?g&aov?grav??jjr&av-attam?áv-attám??l&a&b?s??ás??soum?ts?v&eib?our???e&dnaly&oh?øh??f?s&nyt?rokomsdeks?sen??vtpiks??in&aks?áks??loh&ar?år??n!.sg??o&m&a?å??psgolb,?s!.sg?efremmah?or?ør??terdi?á&baol?ggráv?lá&b?s??soum?veib???u&b!.sg?alk?e&dna?gnir?nner??les?ælk??dra&b?eb??g&nasrop?vi?ŋásrop??j&daehal&a?á??jedub?v&arekkhar?árekkhár???ksiouf?n&diaegadvoug?taed???v&irp?lesl&am?åm???y&b&essen?nart?sebel?tsev??o&d&ar?na!s??or??gavtsev?k&rajb?sa??lem?mrak?n&art?n&if?orb???r&a&mah?n?v??e&dni?t&so?ton??va??ul?yd??s&am?enner?gav?lrak?tivk??vrejks??ø&d&ar?na!s??ør??gåvtsev?k&rajb?sa??lem?mrak?n&art?n&if?ørb???r&e&dni?t&so?tøn??va??ul?yd?æ&n?v???s&enner?gåv?tivk?åm??vrejks???á&slág?tlá?vreiks??å&gåv?h?jddådåb?lf??ø&d&ob?rav??r&egark?olf??s&dav?mort????aki?i&sac?tal??u??o&b?f?g?hay?o?ttat??r!.&cer?erots?gro?m&o&c?n??rif?t??o&c,fni??pohs,stra?t&n?opsgolb,?www?ysrab,?e&a!.&a&ac?cgd?idem??bulc!orea??ci&ffartria?taborea??e&cn&a&l&lievrus-ria?ubma??netniam?rusni??erefnoc??gnahcxe?mordorea?ni&gne?lria?zagam??rawtfos??gni&d&art?ilg!arap?gnah???l&dnahdnuorg?ledom??noollab?retac?sael?t&lusnoc?uhcarap??vidyks??hcraeser?l&anruoj?euf?icnuoc?ortnoc!-ciffart-ria???n&gised?oi&nu?t&a&cifitrec?ercer?gi&tsevni-tnedicca?van??i&cossa!-regnessap??valivic??redef??cudorp?neverp-tnedicca????ograc?p&ihsnoipmahc?uorg!gnikrow???r&e&dart?enigne?korb?niart?trahc??o&htua?tacude???s&citsigol?e&civres?r??krow?serp!xe??tnega??t&farcr&ia?otor??hgil&f?orcim??liubemoh?n&atlusnoc?e&duts?m&esuma?n&iatretne?revog??piuqe????olip?ropria?si&lanruoj?tneics???w&erc?ohs??y&cnegreme?dobper?tefas????rref?z??p!.&a&aa?ca?pc??dem?ecartsnd.icb,gne?r&ab?uj??snduolc,t&acova?cca?hcer??wal?ysrab,???s!.&em?gro?hcs,moc?ten?ude?vog???t!.&116,ayo,gro?lim?moc?nayn,sulpnpv,t&cennockciuq.tcerid,en??ude?v&dr,og???o&hp?m?v?yk??tol?ua??v&iv?lov??xas?ykot??p&a&ehc?g?m?s??eej?g!.&gro?ibom?moc?ossa?ppa,ten?ude???i&r!.nalc,?v?z??j!.&a&3&5xq6f--nx?xqi0ostn--nx??5wtb6--nx?85uwuu--nx?9xtlk--nx?bihc!.&a&bihciakoy?don?ma&him?ye&ragan?tat???r&a&bom?gan?hihci??u&agedos?kas?ustak???s&os?ufomihs??t&amihcay?iran??w&a&g&im&anah?o??omak??kihci?zustum??ihsak??y&agamak?imonihci???e&akas?nagot??i&azni?esohc?h&asa?s&abanuf?ohc???ka&to?zok??musi?orihs?r&akihabihsokoy?o&dim?tak??ukujuk??usihs??nano&hc?yk??o&d&iakustoy?ustam??hsonhot?k&a&rihs?t??iba??nihsaran?sobimanim?tas&arihsimao?imot??uhc?yihcay??u&kujno?s&ayaru?t&imik?tuf???zarasik????g&as!.&a&gas?m&a&tamah?yik??ihsak??rat?t&a&gatik?hatik??ira!ihsin????e&kaira?nimimak??i&akneg?g&aruyk?o??h&c&amo?uo??siorihs??kaznak?modukuf?ra&gonihsoy?mi???nezih?u&k&at?ohuok??s&ot?tarak?????ihs!.&a&kok?m&a&hagan?yirom??ihsakat??rabiam?wagoton??e&miharot?nokih??houyr?i&azaihsin?esok?kustakat?moihsagih??na&mihcahimo?nok??o&hsia?mag?t&asoyot?ok?tir???us&ay?t&asuk?o??????k&aso!.&a&d&awihsik?eki??k&a&noyot?s&akaayahihc?oihsagih???oadat?uziak??m&ayas!akaso??odak??r&a&bustam?wihsak??ediijuf??t&akarih?i&k?us???wag&ayen?odoyihsagih???e&son?tawanojihs??honim?i&akas?h&cugirom?s&ayabadnot?i&a&kat?t??n??oyimusihsagih???k&a&rabi?sim??ustakat??muzi?r&ijat?otamuk???nan&ak?n&ah?es???o&ay?n&a&ganihcawak?simuzi?tak??eba?ikibah?oyot??t&anim?iad?omamihs??uhc??ust&oimuzi?tes????ou&kuf!.&a&d&amay?eos??g&no?ok?usak??hiku?k&awayim?uzii??ma&kan?y&asih?im???rawak?t&a&gon?ka&h?num?t???umo??wa&g&a&kan?nay?t??ias??ko!rih???y&ihsa?usak???e&m&ay?uruk??taruk?us??i&a&nohs?raihcat??goruk?h&cukuf?s&a&gih?hukuy??in???k&a&gako?muzim??iust?o?ustani??m&anim?otihsoynihs?u??r&ogo?ugasas??usu??ne&siek?zu&b?kihc???o&gukihc?h&ak?ot?ukihc??j&ono?ukihc??kayim?nihsukihc?to?uhc??u&fiazad?gnihs?stoyot????zihs!.&a&bmetog?d&amihs?eijuf?ihsoy?omihs??kouzihs?mihsim?ra&biah?honikam??tawi?wa&g&ekak?ukik??kijuf??yimonijuf??i&a&ra?sok??hcamirom?juf?kaz&eamo?ustam??ma&nnak?ta??nukonuzi?orukuf??nohenawak?o&nosus?ti??u&stamamah?z&a&mun?wak??i!ay?i&hs&agih?in??manim??mihs????????m&a&tias!.&a&d&ihsoy?ot?usah??k&a&dih?sa??o&arihs?s???m&a&tias?y&as?o&rom?tah??ustamihsagih???i&hsagurust?jawak??uri??ni?wa&g&e&ko?man??ikot?o??k&ara?i&hsoy?mak???ru?zorokot??y&a&g&amuk?ihsok?otah??kuf??imo??ziin??e&bakusak?ogawak?sogo?ttas?zokoy??i&baraw?h&cugawak?s&oyim?ubustam???iroy?k&ato?ihs?u&k?stawi???m&akoyr?i&hsoy?juf??uziimak???naznar?o&dakas?ihsay?jnoh?n&a&go?nim??imijuf?nah?oy??r&ihsayim?otagan??t&asim!ak??igus?omatik??zak??u&bihcihc!ihsagih??sonuok?ynah????y&ak&aw!.&a&d&ira?notimak??kadih?ma&h&arihs?im??y&a&kaw?tik??oduk???ru&ustakihcan?y??sauy?wa&g&a&dira?zok??orih??konik??yok?zok??e&banat?dawi??i&garustak?jiat?mani??naniak?o&bog?nimik?t&asim?omihs&ah?uk????ugnihs???o!.&a&jos?koasak?m&ay&ako?ust??ihsayah??r&abi?ukawaihsin??wi&aka?nam???e&gakay?kaw??i&gan?h&cu&kasa?otes??sahakat??k&asim?ihsaruk??miin??n&anemuk?ezib??o&hsotas?jnihs?n&amat?imagak??ohs?uhcibik?????ot!.&a&damay?got?koakat?may&etat?ot??nahoj?riat?waki&inakan?reman???eb&ayo?oruk??i&h&asa?ciimak?sahanuf??kuzanu?m&an&i?ot??ih???nezuyn?otnan?u&hcuf?stimukuf?z&imi?ou???????ihs&o&gak!.&a&m&ayuok?ihsogak??si?yonak??e&banawak?n&at&akan?imanim??uka??tomoonihsin??i&adnesamustas?k&azarukam?oih??m&ama?uzi??usuy??nesi?o&knik?os?tomustam??uzimurat???rih!.&a&ka&n?s??m&ayukuf?i&hsorihihsagih?j&ate?imakikaso????r&a&bohs?h&ekat?im???es??tiak?wiad??e&kato?ruk??i&h&ci&akustah?mono?nihs??s&inares?oyim???manimasa?uk??negokikesnij?o&gnoh?namuk??uhcuf????uk&ot!.&a&bihci?mi&hsu&kot?stamok??m??wagakan??egihsustam?i&gum?h&coganas?soyim??kijaw?m&anim?uzia??ukihsihs??nan&a?iak??o&nati?turan????uf!.&a&batuf?m&a&to?y&enak?irok???ihs&im?ukuf??os?uko??r&aboihsatik?uganat??ta&katik?mawak?rih??w&a&g&akus?emas?uy??k&a&mat?rihs?sa??ihsi??nah??ohs???e&gnabuzia?iman?ta&d?tii???i&adnab?enet?hs&agih?iimagak??k&a&wi?zimuzi??ubay??minuk?r&ook?ustamay???nihsiat?o&g&etomo?ihsin?nan?omihs??no!duruf?rih??rihsawani?ta&may?simuzia???u&rahim?stamakawuzia?zia&ihsin?nay???????nug!.&a&bawak?doyihc?k&anna?oi&hsoy?juf?mot???m&ayakat?ustagaihsagih??n&ihsatak?nak??r&ahonagan?nak?o?u&kati?mamat???t&amun?inomihs?o??w&akubihs?iem?ohs???i&hsa&beam?yabetat??kas&akat?esi??m&akanim?uzio??ogamust?rodim??o&jonakan?n&eu?oyikust??tnihs??u&komnan?stasuk?yrik?????ran!.&a&bihsak?d&akatotamay?u!o???guraki?m&ay&atik&imak?omihs??irokotamay??oki??ra&hihsak?n??wa&geson?knet???e&kayim?ozamay?sog?ustim??i&a&rukas?wak??garustak?h&ciomihs?sinawak??jo?ka&mnak?toruk??makawak?nos?r&net?otakat?ugeh???o&d&na?oyo??gnas?jnihs?nihsoy!ihsagih??tomarawat?yrok????t&ag&amay!.&a&dihsio?k&atarihs?ourust??may&a&kan?rum??enak?onimak??rukho?ta&ga&may?nuf??hakat?kas??wa&g&ekas?orumam??ki&hsin?m??z&anabo?enoy?ot???zuy??e&agas?bonamay?dii?nihsagih?o??i&a&gan?nohs??h&asa?sinawak??nugo??o&dnet?jnihs?ynan??ukohak???iin!.&a&ga?k&ium?oagan??munou!imanim??t&a&bihs?giin??ioy??w&a&gioti?kikes?zuy??irak??yijo??e&kustim?mabust??i&aniat?hcamakot?kaz&awihsak?omuzi??m&a&gat?karum??o???n&anust?esog??o&das?ihcot?jnas?k&ihay?oym??mak?naga?ries??u&ories?steoj?????i&ka!.&a&go?k&asok?oimak??t&ago!rihcah??ika!atik???w&aki?oyk???e&mojog?natim?suranihsagih?t&ado?okoy???i&hsoyirom?magatak?naokimak??nesiad?o&hakin?jnoh!iruy??nuzak?rihson?tasi&juf?m??yjnoh??u&kobmes?oppah????o!.&a&dakatognub?m&asah?ihsemih??su?t&ekat?i&h?o????e&onokok?ustimak??i&jih?k&asinuk?ias?usu??mukust??onoognub?u&fuy?juk?ppeb?suk??????wa&ga&k!.&a&mihsoan?rihotok?waga&kihsagih?ya???emaguram?i&j&nonak?ustnez??kunas?monihcu??o&hsonot?nnam?yotim??u&st&amakat?odat??zatu????nak!.&a&dustam?kus&okoy?tarih??maz?nibe?r&a&gihsaimanim?h&esi?imagas??wa&do?guy???u&im?kamak???tikamay?wa&k&ia?oyik?umas??sijuf??yimonin??e&nokah?saya??i&akan?esiak?gusta?hsuz?kasagihc?o?ukust??o&nadah?sio?tamay?????kihsi!.&a&danihcu?gak?kihs?mijaw?t&abust?ikawak??wazanak??i&gurust?hcionon?mon?ukah??nasukah?o&anan?ton!akan???u&kohak?stamok?z&imana?us?????niko!.&a&han?m&arat?ijemuk?uru??n&e&dak?zi??no??ra&hihsin?rih??wa&kihsi?niko??yehi?zonig??e&osaru?seay??i&hsagih?jomihs?k&a&gihsi?not??ihsakot??m&a&ginuk?kihsug?maz??igo?otekat??nuga!noy???n&a&moti?timoy?wonig??i&jikan?k???o&gan?jnan?tiad&atik?imanim???u&botom?kusug&akan!atik??imot??rab&anoy?eah???????c&204ugv--nx?462a0t7--nx?678z7vq5d--nx?94ptr5--nx?a??d&17sql1--nx?3thr--nx?5&20xbz--nx?40sj5--nx??7&87tlk--nx?ptlk--nx??861ti4--nx?a?e!tfarcdnah,??e&16thr--nx?5&1a4m2--nx?9ny7k--nx??im!.&a&bot?k&asustam?uzus??m&a&him?y&emak?im???ihs??nawuk?wi&em?k???e&bani?ogawak?si!imanim???i&arataw?gusim?h&asa?ciakkoy??k&a&mat?sosik?t??iat??raban??o&dat?hik?n&amuk?ihseru?o&du?mok????ust???lasrepus,mihe!.&a&m&a&h&ataway?iin??yustam??ij&awu?imak???taki!man???ebot?i&anoh?kasam?rabami??n&ania?egokamuk?oot??o&jias?kihcu?nustam?uhcukokihs?yi!es???u&kohik?zo????n!.&nriheg,teniesa.resu,?amihs!.&a&d&amah?ho?usam??kustay?m&a?ihsoni&hsin?ko???wakih??e&namihs?ustam??i&g&aka?usay??konikak?mikih??nannu?o&mu&kay?zi!ihsagih?uko???nawust?tasim??u&stog?yamat?????rotsnoihsaf,tawi!.&a&bahay?d&amay?on??koirom?t&a&honat?katnezukir??imus??w&as&ijuf?uzim??ihs???e&hon&i&hci?n??uk??tawi??i&a&duf?murak?wak??h&custo?si&amak?ukuzihs???j&oboj?uk??k&a&m&anah?uzuk??sagenak??esonihci??m&akatik?uzia&rih?wi????o&kayim?no&rih?t??tanufo??uhso????g&3zsiu--nx?71qstn--nx?l??h&03pv23--nx?13ynr--nx?22tsiu--nx?61qqle--nx??i&54urkm--nx?g&ayim!.&a&dukak?m&a&goihs?kihs??ihsustam!ihsagih??unawi??r&awago?iho??ta&bihs?rum??w&a&gano?kuruf??iat??y&imot?ukaw???e&mot?nimes??i&hsiorihs?ka&monihsi?s&awak?o???mak?r&ataw?o&muram?tan????o&az?jagat?t&asim?omamay???u&fir?k&irnasimanim?uhsakihcihs?????ihcot!.&a&g&a&h?kihsa??ust??kom?m&ay&o?usarak??unak??r&a&boihsusan?watho??iho?ukas??t&akihsin?iay??wa&konimak?zenakat??y&imonustu?oihs???e&iiju?kustomihs?nufawi??i&akihci?g&etom?ihcot?on???o&k&ihsam?kin??nas?sioruk?tab??u&bim?san?????h&c&ia!.&a&dnah?m&a!h&akat?im??yuni??ihs&ibot?ust???r&a&hat?tihs??ik?u&ihsagih?kawi???t&ihc?o&k?yot???wa&koyot?zani??yi&monihci?rak???e&inak?k&aoyot?usa??manokot?noyot??i&a&gusak?kot?sia??eot?h&asairawo?cugo?s&ahoyot?oyim???k&a&mok?zako??ihssi??motay?rogamag??n&an&ikeh?ok??ihssin??o&got?ihsin?jna?rihsnihs?suf?tes??u&bo?raho?s&oyik?takihs??yrihc?zah????ok!.&a&dusay?kadih?mayotom?r&ah&im?usuy??umakan??sot!ihsin??wa&g&atik?odoyin??k&as?o????i&esieg?hco!k??jamu?k&a!sus??usto??ma&gak?k??rahan??o&mukus?n&i?ust!ihsagih???torum?yot!o???u&koknan?zimihsasot????ugamay!.&a&m&ayukot?ihso??toyot??e&bu?subat??i&gah?kesonomihs?nukawi?rakih??nanuhs?otagan?u&ba?foh?otim?stamaduk?uy?????sanamay!.&a&dihsoyijuf?mayabat?r&ahoneu?ustakihsin??w&a&k&ayah?ijuf??suran??ohs???egusok?i&ak?h&cimakan?s&anamay?od???k&asarin?u&feuf?sto????o&k&akanamay?ihcugawakijuf??nihso?t&asimawakihci?ukoh??uhc??spla-imanim?u&b&nan?onim??fok?hsok?rust?????ka&rabi!.&a&bukust?gok?kan!ihcatih??m&a&sak?timo?wi??ihsak?ustomihs??ni?r&a&hihcu?way??u&agimusak?ihcust???t&ag&amay?eman??oihcatih??w&ag&arukas?o??os??yi&moihcatih?rom???e&bomot?dirot?not?tadomihs??i&a&k&as?ot??rao??esukihc?gahakat?h&asa?catih??k&a&rabi?saguyr??ihsani?uy??ma?rukustamat??o&dnab?giad?him?kati?rihsijuf?soj?t&asorihs?im??yihcay??u&fius?kihsu?simak????sagan!.&a&m&abo?ihsust??natawak?r&abamihs?u&mo?ustam???wijihc?yahasi??i&akias?hies?k&asagan?i??masah??neznu?o&besas?darih?t&eso?og!imaknihs????ust&igot?onihcuk?uf????zayim!.&a&biihs?guyh?k&oebon?ustorom??mihsuk?r&emihsin?uatik??ta&katik?mim??wag&atik?odak??ya??e&banakat?sakog??i&hsayabok?kaza&kat?yim??m&animawak?ot&inuk?nihs????nanihcin?o&j&ik?onokayim??n&ibe?ust??tias??urahakat????ro&moa!.&a&dawot?turust?wasim??e&hon&ihc&ah?ihs??nas?og?ukor??sario??i&anarih?ganayati?hsioruk?jehon?kasorih?makihsah?nawo?r&amodakan?omoa???o&gnihs?kkat??u&ragust?stum????ttot!.&a&r&ahawak?uotok??sa&kaw?sim???egok?irottot?nanihcin?o&ganoy?nih?tanimiakas??u&bnan?z&ay?ihc??????ukuf!.&a&deki?gurust?ma&bo?h&akat?im??yustak??sakaw??eabas?i&akas?ho?jiehie?ukuf??nezihce!imanim??ono????k&26rtl8--nx?4&3qtr5--nx?ytjd--nx??522tin--nx?797ti4--nx??l33ussp--nx?m&11tqqq--nx?41s3c--nx??n&30sql1--nx?65zqhe--nx?n7p7qrt0--nx??o&131rot--nx?7qrbk--nx?c?diakkoh!.&a&deki?gakihset?hcebihs?k&adih?u&fib?narihs???m&ayiruk?hot?ihs&orihatik?ukuf??oras?usta??r&ib&a!ka??o?uruf??ozo?u&gakihsagih?oyot???sakim?ta&gikust?mun??w&a&ga&k&an?uf??nus!imak???k&aru?i&h&asa?sagih??kat?mak??omihs?um??zimawi??ine?oyk??yot??e&a&mustam?nan??b&a&kihs?yak??o&noroh?to???ian?k&ihsam?ufoto??nakami?ppoko!ihsin??sotihc?tad!okah??uonikat??i&a&bib?mokamot?n&a&k&kaw?oroh??wi??eomak?ihsatu?okik?usta&moruk?sakan????eib?h&c&ioy?u&bmek?irihs???s&ase?ekka?oknar?uesom???jufirihsir?k&amamihs?i&at?n???m&atik?otoyot??oa&kihs?rihs??r&a&hs?kihsi?mot??ihs&aba?ir??otarib???n&a&hctuk?rorum?se?tokahs??uber??o&kayot?m&ire?ukay??naruf!ima&k?nim???orih?r&ih&ibo?suk??o&bah?h&i&b?hsimak??sa??pnan?yan??umen??t&asoyik?eko?ukoh???u&bassa?kotnihs?m&assaw?uo??pp&akiin?en&ioto?nuk??ip??rato?s&akat?t&eb&e?i&a?hs!a??robon??m&e?o&m?takan???no&h?tamah??o&mik?s?t??u&kir?ppihc?st???onihsnihs?ufuras??uaru??yru!koh??zimihs!ok?????g!oyh!.&a&bmat?dnas?gusak?k&at?o&oyot?y??uzarakat??m&ayasas?irah??wa&g&ani?okak??k&i&hci?mak??oy???yi&hsa?monihsin???i&asak?hs&aka?i&at?nawak???j&awa!imanim??emih??k&a&goa?s&agama?ukuf??wihsin??i&hsog?m???mati?oia?rogimak??n&annas?esnonihs??o&gasa!kat??ka?n&ikat?o?ustat??rihsay?sihs?tomus?yas??u&bay?gnihs?????nagan!.&a&bukah?d&a&w?yim??e&ki?u??ii??k&a&s&ay?uki??zus??ihsoo?ousay??m&ay&akat?ii??i&hsukufosik?jii??ukihc??n&i!hsetat??uzii??r&ah?ugot??saim?t&agamay?oyim??w&a&g&a&kan?n??o??kustam?ziurak??onim!imanim??u&koo?s!omihs????ya&ko?rih???e&akas?nagamok?subo??i&gakat?h&asa?c&a!mo!nanihs???uonamay??sukagot??k&a&kas?mimanim?to??ia&atik?imanim??oa?uzihcom??m&akawak?ijuf?o!t???r&ato?ijoihs?omakat???n&ana?esnoawazon??o&hukas?n&a&gan?kan??i&hc?muza??ustat??romok?si&gan?k??tomustam??u&k&as?ohukihc??stamega????to&mamuk!.&a&gamay?rahihsin?sukama!imak??tamanim??enufim?i&hcukik?k&ihsam?u??nugo!imanim??romakat??o&ara?rihsustay?sa?t&amay?om&amuk?us??u!koyg???yohc??u&sagan?zo????yk!.&a&bmatoyk?k&ies?oemak?uzaw??mayi&h&cukuf?sagih??muk??nihsamay?rawatiju?t&away?ik???e&ba&nat!oyk??ya??di?ni??i&ju?kazamayo?manim??natnan?o&gnatoyk?kum?mak?rihsamayimanim?y&gakan?ka&koagan?s??oj???u&ruziam?z&ayim?ik??????wtc1--nx?ykot!.&a&d&i&hcam?mus??oyihc??k&atim?ihsustak??m&a&t!uko??yarumihsa&gih?sum???i&hs&agoa?ika?o!t??uzuok??ren???r&a&honih?wasago??iadok?umah??ssuf?t&ik?o??wa&g&anihs?ode??k&ara?ihcat???y&agates?ubihs???e&amok?donih?m&o?urukihsagih??soyik??i&enagok?gani?h&ca&da?tinuk??sabati??j&nubukok?oihcah??manigus??o&huzim?jihcah?n&akan?ih!sasum??urika??rugem?t&a&mayihsagih?nim??iat?ok??uhc?yknub??u&fohc?hcuf?kujnihs?????pohs&eht,iiawak,yub,?r&2xro6--nx?g?o??s&9nvfe--nx?xvp4--nx??t&netnocresu,opsgolb,?u&4rvp8--nx?fig!.&a&d&eki?ih??kimot?m&ayakat?ihsah??ne?raha&gi&kes?makak??sak??taga&may?tik??wa&g&ibi?ustakan??karihs!ihsagih????e&katim?uawak??i&gohakas?hc&apna?uonaw??k&ago?es?ot??m&anuzim?ijat??nak?urat??nanig?o&dog?jug?makonim?nim?roy?sihcih??u&fig?s&otom?t&amasak?oay???????x5ytlk--nx?yu6d27srjd--nx?z72thr--nx?井福?京東?分大?取鳥?口山?城&宮?茨??媛愛?山&富?岡?歌和??岡&福?静??島&児鹿?広?徳?福??崎&宮?長??川&奈神?石?香??庫兵?形山?手岩?木栃?本熊?根島?梨山?森青?潟新?玉埼?田秋?知&愛?高??縄沖?良奈?葉千?賀&佐?滋??道海北?都京?重三?野長?阜岐?阪大?馬群???k!.&art?gro?moc?per?ude?vog???l&eh?l??m!.uj,ac?j??nd?o&g?h&pih?s!.&esab,xilpoh,ysrab,???lnud?oc?t!.&lldtn,snd-won,???pa!.&0mroftalp,arusah,bew:erif,,e&gatskrelc,niln&igol,okoob,?tupmocegde,virdhsalfno,?krelc,lecrev,n&aecolatigidno,ur:.a,,?poon,remarf,t&ibelet,xenw,?yfilten,??ra&a?hs??u&ekam?llag?org!.esruocsid,cts?kouk?nayalo???vsr?xece4ibgm--nx??q&a!3a9y--nx??g?i!.&gro?lim?moc?ten?ude?vog???m?se??r&a!.&a&cisum?sanes??bog?gro?l&autum?im??moc!.topsgolb,?pooc?rut?t&e&b?n??ni??ude?vog??4d5a4prebgm--nx?b?c?eydoog?los?t&at?s!uen???ugaj??b!.&21g?a&b&a&coros?iuc??itiruc??cnogoas?dicerapa?gniram?i&naiog?ramatnas??n&erom?irdnol??op?p&acam?irolf?ma&j?s???rief?tsivaob??b!aj?ib?mi?sb??c&ba?e&r?t??js?sp?t!e???d&em?mb?n&f?i??rt??e&dnarganipmac?ficer?ht?llivnioj?rdnaotnas??f&dj?ed?gg?n&e?i???g&e&l!.&a&b,m,p,?bp,c&a,s,?e&c,p,s,?fd,gm,ip,jr,la,ma,nr,o&g,r,t,?p&a,s,?r&p,r,?s&e,m,r,?tm,??s??l&s?z??n&c?e?o??ol!b?f?v??pp?ro??hvp?i&du?kiw?nana?oretin?r&c?eurab??sp?te?xat??l&at&an?rof??el?im?sq??m&a?da?e&gatnoc?leb??f?ic?oc!.&duolclautriv.elacs.sresu,topsgolb,???nce?o&ariebir?c&e?narboir?saso??d&o?ranreboas??e&g?t??i&b?dar?ecam?r??rp?t&a?erpoir???p&er?m!e?t??ooc?pa?se??qra?r&af?ga?o&davlas?j??tn?ut??s&a&ixac?mlap?nipmac??ed?u&anam?j?m???t&am?e&d?n?v??nc?o&f?n??ra?sf??u&caug9?de?ja?rg??v&da?ed?og!.&a&b?m?p??bp?c&a?s??e&c?p?s??fd?gm?ip?jr?la?ma?nr?o&g?r?t??p&a?s??r&p?r??s&e?m?r??tm???rs?t??xiv?z&hb?ls?o&c?f?????c!.&as?ca?de?if?o&c?g??ro???e&bew?ccos?dnik?e&b?n&igne?oip??rac??gni&arg?rheob??h&cor?sok?t&aew?orb???itnorf?k&col?o&p?rb???l&aed?ffeahcs??mal?nes?pinuj?t&a&eht?rebsnegömrev??law?nec?s&acnal?nom?ubkcolb??upmoc??v&o&csid?rdnal??resbo??wulksretlow?ywal?zifp??f!.&aterg?bew-no,drp?e&c&itsuj-reissiuh?narf-ne-setsitned-sneigrurihc,?lipuog,rianiretev??hny,i&cc?rgabmahc??m&o&c?n??t??n&eicamrahp?icedem??ossa?pohsdaerpsym,s&e&lbatpmoc-strepxe?riaton?tsitned-sneigrurihc?uova??o&-x&bf,obeerf,?x&bf,obeerf,???t&acova?o&or-ne,psgolb,?r&epxe-ertemoeg?op!orea????vuog??avc7ylqbgm--nx?s??g!.&gro?moc?t&en?opsgolb,?ude?vog???h!.&e&erf,man??mo&c?rf??topsgolb,zi??ur??i!.&a&61f4a3abgm--nx?rf4a3abgm--nx??ca?di?gro?hcs?oc?ten?vog?نار&يا?یا???a&h?per??ew?lf??k!.&c&a?s??e&n?p?r??gk?iggnoeyg?kub&gn&oeyg?uhc??noej??l&im?uoes??man&gn&oeyg?uhc??noej??n&as&lu?ub??o&e&hcni?jead??wgnag???o&c?g??ro?s&e?h?m??topsgolb,u&gead?j&ej?gnawg????cilf??l!.&gro?moc?ten?ude?vog???m!.&topsgolb,vog???n!.&gro?moc?ofni?ten?ude?vog?zib???o&htua?odtnorf?t&c&a?od??laer???p!.&alsi?ca?eman?forp?gro?moc?o&fni?rp??t&en?se??ude?vog?zib???s?t!.&21k?bew?cn!.vog??eman?gro?kst?l&e&b?t??im?op??moc!.topsgolb,?neg?ofni?pek?rd?sbb?ten?ude?v&a?og?t??zib??f?m??ubad?vd??s&8sqif--nx?9zqif--nx?a!.vog?birappnb?gev?lliv?mtsirhc?s??b!.&ew,gro?moc?ten?ude?vog??c?oj?s?u??c&i&hparg?p?t&sigolyrrek?ylana???od??d&a?d?ik?l?n&iwriaf?omaid??oogemoh?rac??e!.&bog?gro?mo&c!.topsgolb,?n??pohsdaerpsym,ude??civres!.enilnigol,?d&d2bgm--nx?oc??h&ctaw?guh??i&lppus?rtsudni?treporp!yrrek???jaiv?l&aw?cycrotom?etoh?gnis?pats??m&ag?oh?reh??nut?ohs?picer?r&it?ut&cip!.7331,?nev???s!i&rpretne?urc??ruoc??taicossa?vig??g!nidloh??h5c822qif--nx?i!.&ekacpuc,gro?moc?t&en?ni?opsgolb,?ude?vog??a09--nx?nnet?rap?targ??k&c&or!.&ecapsbew,snddym,ytic-amil,??us??hxda08--nx?row??l!.&c&a?s??ed,gro?o&c?fni??ten?ude?vog?zib??a&ed?tner??e&ssurb?toh!yrrek???lahsram?m?oot??m!.&bal,etisinim,gro?moc?ten?ude?vog??b?etsys!.tniopthgink,?ialc??n&a&f?gorf?ol??egassap?i&a&grab?mod??giro??o&it&acav?cudorp?ulos??puoc???o&dnoc?geuj?leuv?ppaz?t&ohp?ua???p!.&ces?gro?moc?olp?ten?ude?vog??i&hsralohcs?lihp?t??u??r!.&au,ca?gro?ni?oc?topsgolb,ude?vog?xo,yldnerb.pohs,?a&c?p?tiug??c?e&dliub!.etisduolc,?erac?gor?levart?mraf?n&niw?trap??wolf??ot&cartnoc?omatat??pj?uot??s!.&em?gro?hcs?moc?ten?ude?vog?zib??alg?e&n&isub!.oc,?tif??rp!xe!nacirema???xnal??iws??t&a&e&b?ytic??ob??ek&cit?ram??fig?h&cay?gilf??n&atnuocca?e&mt&rapa?sevni??ve!.&nibook,oc,????rap??u!.&a&c!.&21k?bil?cc???g!.&21k?bil?cc???i!.&21k?bil?cc???l!.&21k?bil?cc???m!.&21k!.&hcorap?rthc?tvp???bil?cc???p!.&21k?bil?cc???si?v!.&21k?bil?cc???w!.&21k?bil?cc????c&d!.&21k?bil?cc???n!.&21k?bil?cc???s!.&21k?bil?cc????d&e&f?lacsne.xhp,?i!.&21k?bil?cc???m!.&21k?bil?cc???n!.&bil?cc???s!.&bil?cc???u&olcrim,rd,??e&d!.&21k?bil,cc???las-4-&dnal,ffuts,?m!.&21k?bil?cc???n!.&21k?bil?cc????h&n!.&21k?bil?cc???o!.&21k?bil?cc????i&h!.&bil?cc???m!.&21k?bil?c&c?et??goc?n&eg?otae??robra-nna?sum?tsd?wanethsaw???nd?r!.&bil?cc???v!.&21k?bil?cc???w!.&21k?bil?cc????jn!.&21k?bil?cc???k&a!.&21k?bil?cc???o!.&21k?bil?cc????l&a!.&21k?bil?cc???f!.&21k?bil?cc???i!.&21k?bil?cc????mn!.&21k?bil?cc???n&afflog,i!.&21k?bil?cc???m!.&21k?bil?cc???sn?t!.&21k?bil?cc????o&c!.&21k?bil?cc???m!.&21k?bil?cc???ttniop,?p&ion,rettalp,?r&a!.&21k?bil?cc???o!.&21k?bil?cc???p!.&21k?bil?cc????s&a!.&21k?bil?cc???dik?k!.&21k?bil?cc???m!.&21k?bil?cc???nd&deerf,uolc,??t&c!.&21k?bil?cc???m!.&21k?bil?cc???u!.&21k?bil?cc???v!.&21k?bil?cc????ug!.&21k?bil?cc???v&n!.&21k?bil?cc???w!.cc???x&ohparg,t!.&21k?bil?cc????y&b-si,k!.&21k?bil?cc???n!.&21k?bil?cc???w!.&21k?bil?cc????za!.&21k?bil?cc????ah!uab??bria?col?e!.ytrap.resu,?ineserf?lp?xe&l?n???vt?w!.&66duolc,gro?moc?s&ndnyd,tepym,?ten?ude?vog??a?e&iver?n!.elbaeciton,??odniw??y&alcrab?cam?ot???t&0srzc--nx?a!.&amil4,ca!.hts??gni&liamerutuf,tsoherutuf,?o&c!.topsgolb,?fni,?p&h21,ohsdaerpsym,?r&euefknuf.neiw,o??v&g?irp,?xi2,ytic-amil,zib,?c?e!s??hc?if?l!asite??mami?rcomed??b!.&gro?moc?ten?ude?vog??b?gl??c&atnoc?e&les?rid!txen????dimhcs?e!.&eman?gro?moc?ofni?ten?ude?vog?zib??b?em?grat?id?k&circ?ram??n!.&0rab,1rab,2rab,5inu,6vnyd,7&7ndc.r,erauqs,?a&l&-morf,moob,?minifed,remacytirucesym,tadsyawla,z,?b&boi,g,lyltsaf:.pam,,?c&inagro-gnitae,paidemym,?d&ecalpb,irgevissam.saap.&1-&gs,nol,rf,yn,?2-&nol,yn,??nab-eht-ni,uolc&meaeboda,nievas.c&di-etsedron,itsalej,?xednay:.e&garots,tisbew,?,??e&c&narusnihtlaehezitavirp,rofelacs.j,?gdirbtib,ht-no-eciffo,l&acs&liat.ateb,noom,?ibom-eruza,?m&ecnuob,ohtanyd,tcerider,?n&ilno-evreser,ozdop,?rehurht,s:abapus,,tis-repparcs,zamkcar,?f&aeletis,crs.&cos,resu,?ehc-a-si,?g&ni&reesnes,sirkcilc,tsohnnylf,?olb&evres,tsaf,??k&catsvano,eeg-a&-si,si,?u,?l&acolottad,iamwt,s&d-ni,s-77ndc,??m&ac&asac,ih,?urofniem,?n&a&f&agp,lhn,?i&bed,llerk,??dcduabkcalb,i,pv-ni,?o&c-morf,duppa,jodsnd,rp-ytinummoc,ttadym,?p&i&-&etsef,on,?emoh,fles,nwo,?j,mac-dnab-ta,o&-oidar-mah,h&bew,sdaerpsym,??pa&duolc,egde,?tfe&moh,vres,?usnd,?r&e&tsulcyduolc,vres-xnk,?vdslennahc:.u,,?s&a&ila&nyd,snd,?nymsd,?bbevres,dylimaf,e&gde-ndc,suohsyub,t&isbeweruza,ys,??k&catstsaf,ekokohcs,?n&d&-won,d,golb,npv,?oitcnufduolc,?ppacitatseruza:.&2suts&ae,ew,?aisatsae,eporuetsew,sulartnec,?,s&a-skcik,ecca&-citats,duolc,??t,?t&adies,ce&ffeym,jorprot:.segap,,lespohs,?e&nretnifodne,smem,?farcenimevres,i-&ekorb,s&eod,lles,teg,??n&essidym,orfduolc,?r0p3l3t,s&ixetnod,oh&-spv:.citsalej.&cir,lta,sjn,?,gnik,???u&h,nyd,r:eakust.citsalej,,?ved-naissalta.dorp.ndc,x&inuemoh,spym,tsale.&1ots-slj,2ots-slj,3ots-slj,?unilemoh,?y&awetag-llawerif,ffijduolc:.&ed-1arf,su-1tsew,?,ltsaf.&dorp.&a,labolg,?lss.&a,b,labolg,?pam,slteerf,?n&-morf,ofipi,?srab,?z&a-morf,tirfym,???p?tcip?v??f&ig?o&l?sorcim???g!.&bog?dni?ed,g&olb,ro??lim?moc?ot,ten?ude???h!.&dem?gro?l&er?op??m&oc?rif??o&fni?rp?s&rep?sa???po&hs?oc??t&en?luda?ra??ude?vuog???i!.&a&2n-loritds--nx?7e-etsoaellav--nx?8&c-aneseclrof--nx?i-lrofanesec--nx??at?b?c!cul??dv?i&blo&-oipmet?oipmet??cserb?drabmol?g&gof?urep??l&gup?i&cis?me&-oigger?oigger???uig&-&aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf???aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf????n&a&brev?cul?pmac?tac??idras?obrac&-saiselgi?saiselgi??resi??otsip?r&b&alac!-oigger?oigger??mu??dna&-&attelrab-inart?inart-attelrab??attelrabinart?inartattelrab?ssela??epmi?ugil??tnelav&-obiv?obiv??vap?z&e&nev?ps&-al?al???irog???l&iuqa!l??leib??m&or?rap??n!acsot?e&dom?is?sec&-&ilrof?ìlrof??ilrof?ìlrof???g&amor&-ailime?ailime??edras?olob??i&ssem?tal??ne!var??o&cna?merc?rev?vas???oneg?p?r!a&csep?rr&ac&-assam?assam??ef??von??etam?tsailgo!-lled?lled???s!ip?sam&-ararrac?ararrac??u&caris?gar???t!a&cilisab?recam??resac?soa!-&d&-&ellav?lav??ellav?lav??ellav??d&-&ellav?lav??ellav?lav??ellav??te&lrab&-&airdna-inart?inart-airdna??airdnainart?inartairdna??ssinatlac???udap?v!o&dap?neg?tnam???zn&airb&-a&lled-e-aznom?znom??a&lledeaznom?znom??eaznom??e&c&aip?iv??soc?top??om???b&-&23,46,61,?3c-lorit-ds-onitnert--nx?be-etsoa&-ellav--nx?dellav--nx??c!f-anesec-lrof--nx?m-lrof-anesec--nx??he-etsoa-d-ellav--nx?m!u??o2-loritds-nezob--nx?sn-loritds&-nasl&ab--nx?ub--nx??nitnert--nx??v!6-lorit-dsnitnert--nx?7-loritds&-nitnert--nx?onitnert--nx???z&r-lorit-ds&-nitnert--nx?onitnert--nx??s-loritds-onitnert--nx???c&f?is?l?m?p?r?v??d&p?u!olcnys,??e&c!cel?inev?nerolf??f?g!ida&-&a&-onitnert?onitnert??otla!-onitnert?onitnert???a&-onitnert?onitnert??otla!-on&azlob?itnert??onitnert????hcram?l?m!or??n&idu?o&n&edrop?isorf??torc???p?r?s&erav?ilom??t!nomeip?s&eirt?oa!-&d-e&ellav?éllav??e&ellav?éllav???de&ellav?éllav??e&ellav?éllav?????v?znerif??g&a?b?f?il?o?p?r?up?vf??hc?i&b?c?dol?f?l!lecrev?opan?rof&-anesec?anesec???m?n&a&part?rt&-attelrab-airdna?attelrabairdna???imir?ret??p?r!a&b?ilgac?ssas???s!idnirb??t&ei&hc?r??sa??v??l&a!c??b?c?o&m?rit&-&d&eus&-&nitnert?onitnert??nitnert?onitnert??us&-&nitnert?onitnert??nitnert?onitnert??üs&-&nitnert?onitnert??nitnert?onitnert???s&-onitnert?onitnert???d&eus!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??us&-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??üs!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert???s&-onitnert?onitnert?????m&ac?f?i!t.nepo.citsalej.duolc,?ol?r??n&a!lim?sl&ab?ub???b?c?e!en.cj,v?zob??irut?m!p??p?r?t??o&a!v??b!retiv??c!cel??enuc?g!ivor??i&dem&-onadipmac?onadipmac??pmet&-aiblo?aiblo??rdnos?zal??l?m!a&greb?ret??oc?re&f?lap???n!a&dipmac&-oidem?oidem??lim?tsiro?zlob??ecip&-ilocsa?ilocsa??i&bru&-orasep?orasep??lleva?rot?tnert??r&elas?ovil??ulleb??p?r!a&sep&-onibru?onibru??znatac??oun??s!ivert?sabopmac??t!arp?e&nev?ssorg??n&arat?e&girga?rt?veneb????zz&era?urba???p&a?ohsdaerpsym,s?t??qa?r&a!m?s??b!a??c?f?g?k?me?o?p?s?t?v??s&a&b?iselgi&-ainobrac?ainobrac???b?c?elpan?i?m?ot?s?t?v??t&a?b?c?l?m?nomdeip?o!psgolb,?p?v??u&de?l?n?p??v&a?og?p?s?t?v??y&drabmol?ellav&-atsoa?atsoa??licis?nacsut??z&al?b?c?p??ìlrof&-anesec?anesec???derc?er?f?m?utni??je3a3abgm--nx?kh?l!.&topsgolb,vog??uda??m!.&gro?moc!.topsgolb,?ten?ude???n&a&morockivdnas?ruatser?tnuocca??e&g?m&eganam!.retuor,?piuqe??r??i!.ue?m?opdlog??opud?uocsid??o&b?cs!.&ude,vog:.ecivres,,??d?g?h?j?oferab?p&edemoh?s???p!.&emon?gro?lbup?moc?t&en?ni?opsgolb,?ude?vog???r&a!m&law?s???epxe?op&er?pus!.ysrab,?s???s!.&adaxiabme?e&motoas?picnirp?rots??gro?lim?moc?o&c?dalusnoc?hon,?ten?ude??a&cmoc?f??e&b?r?uq??i!rolf?tned??o&h!.&duolc&p,rim,?e&lej,tiseerf,?flah,lrupmet,s&pvtsaf,seccaduolc,?tsafym,vedumpw,??p!sua???urt??t!.&eman?gro?ibom?levart?m&oc?uesum??o&c?fni?r&ea?p???pooc?sboj?t&en?ni??ude?vog?zib??ayh?n?o!bba?irram???uognah?xen?y!.gro,?ztej??u&2&5te9--nx?yssp--nx??a!.&a&s?w??civ?d&i?lq??fnoc?gro?moc!.&pohsdaerpsym,stelduolc.lem,topsgolb,??nsa?ofni?sat?t&ca?en?n??ude!.&a&s?w??ci&lohtac?v??dlq?sat?t&ca?n??wsn!.sloohcs????vog!.&a&s?w??civ?dlq?sat???wsn?zo??ti??c!.&fni?gro?moc?ten?ude?vog??i??d&e!.tir.segap-tig,?iab??e!.&dcym,enozgniebllew,noitatsksid,odagod.citsalej,snd&ps,uolc,?ysrab,??g!.&bew?gro?m&aug?oc??ofni?ten?ude?vog???h!.&0002?a&citore?idem?kitore??edszot?gro?ilus?letoh?m&alker?lif?t?urof??naltagni?o&c?ediv?fni?levynok?nisac??pohs?rarga?s&a&kal?zatu??emag?wen??t&lob?opsgolb,rops??virp?xe&s?zs??ytic?zsagoj??os?sut??l!.topsgolb,?m!.&ca?gro?moc?oc?ro?ten?vog???n!.&duolcesirpretne,eni&esrem,m,?tenkcahs,?em!.ysrab,??o&ggnaw?y!c???r!.&3kl,a&i&kymlak,rikhsab,vodrom,?yegyda,?bps,ca,duolcrim,e&niram,rpcm,?g&bc,nitsohurger.citsalej,ro,?ianatsuk,k&ihclan,s&m,rogitayp,??li&amdlc.bh,m,?moc,natsegad,onijym,pp,ri&b,d&cm:.spv,,orue,?midalv,?s&ar,itym,?t&en,ni,opsgolb,set,?u&4an,de,?vo&g,n,?ynzorg,zakvakidalv,?myc?p?ug??s!.&a&d&golov,nagarak,?gulak,i&groeg,kymlak,lerak,nemra,rikhsab,ssakahk,vodrom,zahkba,?lut,rahkub,vut,yegyda,znep,?bps,da&baghsa,rgonilest,?gunel,i&anatsuk,hcos,ovan,ttailgot,?k&alhsygnam,ihclan,s&legnahkra,m,n&a&mrum,yrb,?i&buytka,nbo,??tiort,vorkop,??l&ocarak,ybmaj,?na&gruk,jiabreza,ts&egad,hkazak-&htron,tsae,???ovonavi,r&adonsark,imidalv,?t&enxe,nek&hsat,mihc,??vo&hsalab,n,?ynzorg,z&akvakidalv,emret,??t&amok?i&juf?masih????v!.&em,g&olb,ro??moc?nc,ten?ude?ved,??ykuyr??v&b?c!.&emon?gro?moc?t&ni?opsgolb,?ude???ed!.&enilnigol,gnigats-oned,hcetaidem,lecrev,o&ned,tpyrctfihs,?ppa-rettalp,s&egap,rekrow,?vr&esi,uc,?weiverpbuhtig,ylf,??ih?l!.&di?fnoc?gro?lim?moc?nsa?ten?ude?vog???m!.&eman?gro?lim?m&oc?uesum??o&fni?r&ea?p???pooc?t&en?ni??ude?vog?zib???o&g?m??rt?s!.&bog?der?gro?moc?ude???t!.&bew-eht-no,naht-&esrow,retteb,?sndnyd,?d?gh?i?won??uqhv--nx??w&a!.moc?hs?l??b!.&gro?oc???c!.&gro?moc?ten?ude??cp??e&iver!.oby,?n?s??g?k!.&bme?dni?gro?moc?ten?ude?vog???m!.&ca?gro?m&oc?uesum??oc?pooc?t&en?ni??ude?vog?zib??b??o&csom?h!s??n?w??p!.&344x,de?en?o&c?g??ro?snduolc,ualeb???r!.&ca?gro?lim?oc?pooc?ten?vog??n??t!.&a46oa0fz--nx?b&82wrzc--nx?ulc??emag?gro?l&im?ru,?moc!.reliamym,?t&en?opsgolb,?ude?v&di?og?ta0cu--nx??zibe?業商?織組?路網???z!.&ca?gro?lim?oc?vog????x&a!.&cm,eb,gg,s&e,u,?tac,ue,yx,?t??c!.&hta,ofni,vog???e&d&ef?nay??ma!nab??rof?s??ilften?jt?m!.&bog?gro?moc?t&en?opsgolb,?ude??g?ma2ibgy--nx??o&b!x??f?rex??rbgn--nx?s!.vog??x&am&jt?kt??x???y&4punu--nx?7rr03--nx?a&d!i&loh?rfkcalb??ot!.emyfilauqerp,??g?lp?p!ila??rot?ssin?wdaorb??b!.&duolcym,fo?hcetaidem,lim?moc!.topsgolb,?vog??ab?gur??c!.&ca?dtl?gro?lim?m&oc!.&ecrofelacs.j,topsgolb,??t??orp?s&egolke?serp??ten?vog?zib??amrahp?nega??d&dadog?uts??e&kcoh?ltneb?n&dys?om?rotta??snikcm??g!.&eb,gro?moc?oc?ten?ude?vog??olonhcet!.oc,?rene??hpargotohp?id?k!.&gro?moc?ten?ude??s??l!.&clp?d&em?i??gro?hcs?moc?ten?ude?vog??f?imaf!nacirema??l&a?il??ppus??m!.&eman?gro?lim?moc?t&en?opsgolb,?ude?vog?zib??edaca!.laiciffo,?ra??n&a&ffit?pmoc??os??o&j?s??p!.&gro?lim?moc?pooc?ten?ude?vog???r&e&corg?grus?llag?viled??lewej?otcerid?tnuoc?uxul??s!.&gro?lim?moc?ten?ude?vog??pil??t&efas?i&c?ledif?n&ifx?ummoc!.&bdnevar,gon,murofym,???r&ahc?uces??srevinu??laer?r&ap!.oby,?eporp??uaeb??u!.&bug?gro?lim?moc!.topsgolb,?ten?ude??b!tseb???van!dlo??xes??z&a!.&eman?gro?lim?moc?o&fni?rp??pp?t&en?ni??ude?vog?zib???b!.&az,gro?jsg,moc?ten?ude?vog???c!.&4e,inum.duolc.&rsu,tlf,?m&laer,urtnecatem.motsuc,?oc,topsgolb,??d!.&cos?gro?lop?m&oc?t??ossa?t&en?ra??ude?vog???ib!.&duolcsd,e&ht-rof,mos-rof,rom-rof,?izoj,nafamm,p&i&-on,fles,?ohbew,tfym,?retteb-rof,snd&nyd,uolc,?xro,?g??k!.&duolcj,gro?lim?moc?t&en?ropeletzak.saapu,?ude?vog???m!.&ca?gro?lim?oc?ten?ude?v&da?og????n!.&asq-irom--nx?ca?gro?htlaeh?i&r&c?o&am?ām???wi!k???keeg?l&im?oohcs??neg?oc!.topsgolb,?t&en?nemailrap?vog???a!niflla???rawhcs?s!.&ca?gro?oc???t!.&c&a?s??e&m?n??ibom?l&etoh?im??o&c?fni?g??ro?vt???u!.&gro?moc?oc?ten??rwon??yx!.&e&nozlacol,tisgolb,?gnitfarc,otpaz,??zub??λε?υε?авксом?брс!.&гро?до?ка?р&бо?п!у?????г&б?ро??дкм?зақ?итед?килотак?леб?мок?н&йално?ом??рку?сур!.&арамас,бпс,гро,зиб,ичос,ксм,м&ок,ырк,?рим,я,??тйас?фр?юе?յահ?לארשי?םוק?اي&روس?سيلم?ناتيروم??بر&ع?غملا??ة&كبش?ي&دوعسلا?روس??یدوعسلا??ت&ا&راما?لاصتا??را&ب?ڀ?ھب???ر&ئازجلا?ازاب?صم?طق??سنوت?عقوم?قارع?ك&تيب?يلوثاك??موك?ن&ا&تس&كاپ?کاپ??دوس?ر&يا?یا??مع?يلعلا??درالا?ميلا?ي&رحبلا?طسلف???ه&ارمه?يدوعسلا??وكمارا?يبظوبا?ۃیدوعسلا?टेन?त&राभ?ोराभ??नठगंस?मॉक?्मतराभ?ত&রাভ?ৰাভ??ালংাব?ਤਰਾਭ?તરાભ?ତରାଭ?ாயித்நஇ?ைக்ஙலஇ?்ரூப்பக்ஙிச?్తరాభ?ತರಾಭ?ംതരാഭ?ාකංල?มอค?ยทไ!.&จิกรุธ?ต็นเ?ร&ก์คงอ?าหท??ลาบฐัร?าษกึศ???ວາລ?ეგ?なんみ?アトス?トンイポ?ドウラク?ムコ?ル&グーグ?ーセ??ン&ゾマア?ョシッァフ??业企?东广?乐娱?亚基诺?你爱我?信中?务政?动移?博微?卦八?厅餐?司公?品食?善慈?团集?国中?國中?址网?坡加新?城商?尚时?山佛?店&商?网?酒大里嘉??府政?康健?息信?戏游?拉里格香?拿大?教主天?机手?构机!织组??标商?歌谷?浦利飞?港香!.&人個?司公?府政?絡網?織組?育教???湾台?灣&台?臺??物购?界世?益公?看点?科盈訊電?站网?籍書?线在?络网?网文中?聘招?販通?逊马亚?通联?里嘉?锡马淡?門澳?门澳?闻新?電家?국한?넷닷?성삼?컴닷??");
+ "a&0&0trk9--nx?27qjf--nx?e9ebgn--nx?nbb0c7abgm--nx??1&2oa08--nx?apg6qpcbgm--nx?hbbgm--nx?rdceqa08--nx??2&8ugbgm--nx?eyh3la2ckx--nx?qbd9--nx??3&2wqq1--nx?60a0y8--nx??4x1d77xrck--nx?6&1f4a3abgm--nx?2yqyn--nx?5b06t--nx?axq--nx?ec7q--nx?lbgw--nx??883xnn--nx?9d2c24--nx?a&a?it??b!.&gro?lim?moc?sr,t&en?opsgolb,?ude?vog??abila?c?ihsot?m?n??c!.&b&a?m?n??c&b?g?q??ep?fn?k&s?y??ln?no?oc,p&i-on,ohsdaerpsym,?sn?t&n?opsgolb,?un?ysrab,?i&ma?r&emarp?fa??sroc??naiva?s??d&ats?n&eit?oh??om?sa?tl??eg?f&c?ob??g!emo?naripi?oy??hskihs?i&dem!.remarf,?hs?k!on??sa!.snduolc,??jnin?k&aso?dov?ede?usto??l!.&c,gro?moc?ofni?r&ep?nb,?t&en?ni??ude?vog??irgnahs?le&nisiuc?rbmuder???m!.&ca?gro?oc?sserp?ten?vog??ahokoy?e00sf7vqn--nx?m??n!.&ac?cc?eman?gro?ibom?loohcs?moc?ni?o&c?fni?rp??r&d?o??s&u?w??vt?xm??av?is?olecrab?tea??p!.&bog?ca?d&em?ls??g&ni?ro??mo&c?n??oba?ten?ude??c?g7hyabgm--nx?ra!.&461e?6pi?iru?nru?rdda-ni?siri???s??q!.&eman?gro?hcs?lim?moc?t&en?opsgolb,?ude?vog???r&az?emac?f4a3abgm--nx?n!d5uhf8le58r4w--nx??u&kas?tan???s!.&bup?dem?gro?hcs?moc?ten?ude?vog??ac!.uban.iu,?iv??t&ad?elhta?led?oyot??u!.&a&cinniv?emirc?i&hzhziropaz?stynniv??s&edo?sedo??tlay?vatlop??bs?cc,d&argovorik?o!roghzu??tl,?e&hzhziropaz?i,nvir?t??f&i?ni,?g&l?ro??hk?i&stvinrehc?ykstyn&lemhk?vypork???k&c?m?s&nagul?t&enod?ul??v&iknarf-onavi?orteporp&end?ind?????l&iponret?opotsa&bes?ves??p??m&k?oc?s?yrk??n&c?d?i?osrehk?v?ylov??o&c,nvor??p&d?p,z??r&c?imotihz?k?ymotyhz??sk?t&en?l?z??ude?v:c?e&alokin?ik??i&alokym?hinrehc?krahk?vl?yk??k?l?o&g!inrehc??krahk??r?,xc,y&ikstinlemhk?mus?s&akrehc?sakrehc?tvonrehc???z&ib,u????v!aj?bb?et?iv??waniko?x&a?iacal??yogan?z&.&bew?c&a?i&n?rga???gro?l&im?oohcs??m&on?t??o&c!.topsgolb,?gn??radnorg?sin?t&en?la??ude?vog?wal??zip!.korgn,???b&00ave5a9iabgm--nx?1&25qhx--nx?68quv--nx?e2kc1--nx??2xtbgm--nx?3&b2kcc--nx?jca1d--nx??4&6&1rfz--nx?qif--nx??96rzc--nx??88uvor--nx?a&0dc4xbgm--nx?c?her?n?ra?t??b!.&erots?gro?moc?o&c?fni??ten?ude?v&og?t??zib??a??c&j?s??d&hesa08--nx?mi??g?l!.&gro?moc?ten?ude?vog??m??s!.&gro?moc?ten?ude?vog???tc-retarebsnegmrev--nx?u&lc!.&elej,snduolc,ysrab,?smas??p!.ysrab,??wp-gnutarebsnegmrev--nx??c&1&1q54--nx?hbgw--nx??2e9c2czf--nx?4&4ub1km--nx?a1e--nx?byj9q--nx?erd5a9b1kcb--nx??8&4xx2g--nx?c9jrb2h--nx??9jr&b&2h--nx?54--nx?9s--nx??c&eg--nx?h3--nx?s2--nx???a!.&gro?lim?moc?rrd,ten?ude?vog??3a09--nx!.&ca1o--nx?gva1c--nx?h&ca1o--nx?za09--nx??ta1d--nx?ua08--nx????b&a?b?ci?f76a0c7ylqbgm--nx?sh??c!.&eugaelysatnaf,gnipparcs,liamwt,nwaps.secnatsni,revres-emag,s&nduolc,otohpym,seccaptf,?xsc,?0atf7b45--nx?a1l--nx??e!.&21k?bog?dem?esab,gro?l&aiciffo,im??moc?nif?o&fni?rp??ten?ude?vog??beuq?n?smoc??fdh?i&l&buperananab?ohtac??n&agro?ilc?osanap??sum?tic??l!.&gro?moc?oc?ten?ude?vog?yo,?l??m!.&mt?ossa??p1akcq--nx??n!.&mon?ossa??i?p??relcel?s!.&gro?moc?ten?ude?vog???t!.&e&m,w,?hc,?s?w??v!.&e0,gro?lim?moc?ten?ude?v&g:.d,,og????wp?yn??d&2urzc--nx?3&1wrpk--nx?c&4b11--nx?9jrcpf--nx???5xq55--nx?697uto--nx?75yrpk--nx?9ctdvkce--nx?a!.mon?d?er?olnwod??b2babgm--nx?c!.vog?g9a2g2b0ae0chclc--nx??e&m!bulc??r!k??sopxe?timil?w??fc?g!.&ude?vog???h&d3tbgm--nx?p?t??i!.&ased?bew?ca?etrof,hcs?lim?o&c!.topsgolb,?g??palf,ro?sepnop?ten?ym?zib??b?ordna?p?rdam??l&iub?og?row??m!.&ed,ot,pj,t&a,opsgolb,???n&a&b?l!.citats:.&setis,ved,?,raas???ob?uf??o&of?rp??r&a&c&tiderc?yalcrab??ugnav??ef506w4b--nx?k!.&oc,ude,?jh3a1habgm--nx??of??s!.&dem?gro?moc?ofni?ten?ude?v&og?t???m!kcrem???t!.topsgolb,excwkcc--nx?l??uolc!.&a&bura-vnej.&1ti,abura.rue.1ti,?tcepsrep,xo:.&ku,nt,?,?b&dnevar,ewilek:.sc,,?citsalej.piv,drayknil,elej,gnitsohdnert.&ed,hc,?letemirp:.ku,,m&edaid,ialcer.&ac,ku,su,??n&evueluk,woru,?r&epolroov,o&pav,tnemele,??tenraxa.1-se,ululetoj,wcs.&gnilebaltrams,koobelacs,latemerab.&1-&rap-rf,sma-ln,?2-rap-rf,?rap-rf.&3s,cnf:.snoitcnuf,,etisbew-3s,mhw,s8k:.sedon,,?s&8k,ecnatsni.&bup,virp,?ma-ln.&3s,etisbew-3s,mhw,s8k:.sedon,,??waw-lp.&3s,etisbew-3s,s8k:.sedon,,??xelpciffart,yawocne.ue,??za5cbgn--nx??e&1&53wlf--nx?7a1hbbgm--nx?ta3kg--nx??2a6a1b6b1i--nx?3ma0e1cvr--nx?418txh--nx?707b0e3--nx?a!.&ca?gro?hcs?lim?oc?t&en?opsgolb,?vog??09--nx??b!.&ca?etisbew321,gnitsohbew,nevueluk.yxorpze,pohsdaerpsym,snoitulostsohretni.duolc,topsgolb,?ortal?ut!uoy???c&0krbd4--nx!.&a2qbd8--nx?b8adbeh--nx?c6ytdgbd4--nx?d8lhbd5--nx???a&lp!.oc,?ps!.&lla4sx,rebu,tsafym,?artxe??sla??i!ffo??n&a&d?iler?nif?rusni!efil?srelevart???eics!.oby,??rofria??d!.&1sndnyd,42pi-nyd,7erauqs,amil4,b&ow-nrefeilgitsng--nx,rb-ni,vz-nelletsebgitsng--nx,?decalpb,e&daregtmueart,luhcsvresi,mohsnd,nihcamyek,tiesbew321,?hcierebsnoissuksid,keegnietsi,lsd-ni,m&oc,rofttalpluhcs,?n&-i-g-o-l,aw-ym,e&lletsebgitsnüg,sgnutiel,?i&emtsi,lreb-n&i,yd,??norblieh-sh.ti.segap,oitatsksid-ygolonys,pv&-n&i,yd,?nyd,?refeilgitsnüg,?orp-ytinummoc,p&h21,iog:ol,,ohsdaerpsym,?r&e&ntrapdeeps.remotsuc,su&-lautriv,lautriv,?t&adpusnd,tub-ni,uor-ym,?vres&-e&bucl,mohym,?bew-emoh:.nyd,,luhcs,??ogiv-&niem,ym,??s&d-&onys,ygolonys,?nd&-&dd,nufiat,sehcsimanyd,tenretni,yard,?isoc.nyd,ps,yard,?oper-&nvs,tig,?sndd:.&nyd,sndnyd,?,?topsgolb,vresi-&niem,tset,?xi2,y&awetag-&llawerif,ym,?srab,tic-amil,?zten&mitbel,sadtretteuf,??art!.oby,?i&sdoow?ug??on--nx??e!.&bil?dem?eif?gro?irp?kiir?moc!.topsgolb,?pia?ude?vog??ei?ffoc?gg?r&f?ged???f&a&c?s??il??g!.&gro?lim?moc?t&en?vp??ude?vog??a&f?gtrom?p!.&3xlh,detalsnart,grebedoc,kselp,sndp,tengam,xlh,y&cvrp,kcor,???rots?yov??elloc?na&hcxe?ro!.hcet,??roeg?ug??i!.&pohsdaerpsym,topsgolb,vog??tilop?v&bba?om???j!.&fo,gro?oc?ten???k!.&c&a?s??e&m?n??ibom?o&c!.topsgolb,?fni?g??ro??i&b?l?n???l&a&dmrif?s!rof???b&a?i&b?dua???c&aro?ric??dnik?g!oog??i&bom?ms??l&asal?erauqa??ppa?uhcs?yts!efil???m!.&4&32i,p&ct,v,??66c,ailisarb,b&dnevar,g-raegelif,?ca?duolcsd,e&d-raegelif,i&-raegelif,lpad:.tsohlacol,,?pcm,?g&ro?s-raegelif,?hctilg,kcatsegde,noitatsksid,o&bmoy,c?t&nigol,poh,??p&i&on,snart.etis,?j-raegelif,ohbew,?r&aegelif,idcm,ofsnd,?s&dym,ndd,ti?umhol,?t&en?s&acdnuos,ohon,??u&a-raegelif,de??v&irp?og??y&golonys,olpedew,srab,??a&g?n!.&reh.togrof,sih.togrof,???em?i&rp?twohs??orhc?w??n!goloc?i&lno!.&egats-oree,oree,ysrab,??w??o!.&derno:.gnigats,,ecivres,knilemoh,?hp?latipac?ts&der?e&gdirb?rif???z!.&66duolc,amil,sh,???ruoblem??om?p!.&bog?gro?lim?mo&c?n??t&en?opsgolb,?ude??irg?yks??r!.&mo&c?n??ossa?topsgolb,?a&c!htlaeh??pmoc?wtfos??bc?eh?if?ots!.&e&rawpohs,saberots,?yflles,??taeht?u&ces?sni?t&inruf?necca??za???s!.&a!bap.us,disnim321,?b!ibnal?rofmok??c!a??d!b?n&arb?ubroflanummok???e?f!noc,?g!ro??h!f??i!trap??k!shf??l?m!oc,t??n!mygskurbrutan??o?p!ohsdaerpsym,p??r!owebdluocti,?s!serp?yspoi,?t!opsgolb,?u?vhf?w?x!uvmok??y?z??a&c?el?hc??i&er?urc??nesemoh?roh?uoh??t&a&d?ts&e!laer??lla???is!.&e&lej,nilnigol,r&etnim,ocevon,?winmo,?k&rowtenoilof,wnf,?laicosnepo,n&eyb,oyc,?spvtsaf,thrs,xulel,ysrab,?bew!.remarf,??ov?ra?t&ioled?ol??utitsni??u&lb?qi&nilc?tuob???v!.&21e?b&ew?ib?og??ce&r?t??erots?gro?lim?m&o&c?n??rif??o&c?fni??rar?stra?t&en?ni??ude?vog??as?e3gerb2h--nx?i&l!.xlh,?rd?ssergorp??ol??w&kct--nx?r??xul?y!.&gro?lim?moc?ten?ude?vog????f&0f3rkcg--nx?198xim--nx?280xim--nx?7vqn--nx?a!.&gro?moc?ten?ude?vog???b!.vog?wa9bgm--nx??c!.topsgolb,a1p--nx!.&a14--nx,b8lea1j--nx,c&avc0aaa08--nx,ma09--nx,?f&a1a09--nx,ea1j--nx,?gva1c--nx,nha1h--nx,pda1j--nx,zila1h--nx,??ns??ea1j--nx?g?iam?l&a1d--nx?og??n!.&bew?cer?erots?m&oc?rif??ofni?re&hto?p??stra?ten???orp?p!.&gro?moc?ude???rus?t!.hcs,w??vd7ckaabgm--nx?w!.&hcs,zib,???g&2&4wq55--nx?8zrf6--nx??3&44sd3--nx?91w6j--nx!.&a5wqmg--nx?d&22svcw--nx?5xq55--nx??gla0do--nx?m1qtxm--nx?vta0cu--nx????455ses--nx?5mzt5--nx?69vqhr--nx?7&8a4d5a4prebgm--nx?rb2c--nx??a!.&gro?mo&c?n??oc?ten??vd??b!.&0?1?2?3?4?5?6?7?8?9?a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t!opsgolb,?u?v?w?x?y!srab,?z???c!b?za9a0cbgm--nx??e!.&eman?gro?ics?lim?moc!.topsgolb,?nue?ten?ude?vog??a??g!.&ayc,gro?lenap:.nomead,,oc?saak,ten???i&a?v??k!.&g&olb,ro??ku,lim?moc?oi,pj,su,ten?ude?v&og?t,???m!.&drp?gro?lim?m&o&c?n??t??oc?ude?vog??pk??n!.&dtl,eman?gro?hcs?i!bom??l&im?oc,?m&oc!.topsgolb,?rif,?neg,ogn,ten?ude?vog??aw?i!b!mulp??car?d&art?dew??h&sif?tolc??k&iv?oo&b?c???ls?n&aelc?iart??p!pohs??re&enigne?tac??t&ad?ekram?hgil?lusnoc?neg?ov?soh!.tfarcnepo,??vi&g?l???o!s??u&rehcisrev?smas?tarebsnegömrev???o&d?lb?og!.&duolc,etalsnart,???r&2n084qlj--nx?ebmoolb?o!.&77ndc.c:sr,,a&remacytirucesym,t&neimip,sivretla,?z,?bew-llams,d&ab-yrev-si,e&sufnocsim,vas-si,?nuof-si,oog-yrev-si,uolc&arfniarodef,mw,??e&a,cin-yrev-si,grof&loot,peh,?l&as-4-ffuts,poeparodef,?m&-morf,agevres,ohruoyslles,?n&ozdop,uma.elet,?r&ehwongniogyldlob,iwym,uces-77ndc.nigiro.lss,?t&adidnac-a-si,is&-ybboh,golb,???fehc-a-si,golbymdaer,k&eeg-a&-si,si,?h,nut,?l&i&amwt,ve-yrev-si,?lawerif&-ym,ym,?sd-ni,?m&acssecca,edom-elbac,?n&af&blm,cfu,egelloc,lfn,s&citlec-a-si,niurb-a-si,tap-a-si,?xos-a-si,?ibptth,o&itatsksid,rviop,?p&j,v-ni,??o&jodsnd,tp&az,oh,??p&i&-on,fles,?o&hbew,tksedeerf,?tf&e&moh,vres,?ym,??r&e&gatop,ppepteews,su-xunil-a-si,?gmtrec,vdmac,?s&a&ila&nyd,snd,?nymsd,?b&alfmw,bevres,?d&ikcet.3s,ylimaf,?eirfotatophcuoc,j,koob-daer,ltbup,nd&-won,deerf,emoh,golb,kcud,mood,nyd:.&emoh,og,?,ps,rvd,tog,uolc,?s&a-skcik,ndd,?tnemhcattaomb,u,?t&ce&jorparodef.&duolc,gts.so.ppa,so.ppa,?riderbew,?e&ews-yrev-si,nretni&ehtfodne,fodne,??hgink-a-si,oi-allizom,s&ixetn&od,seod,?o&h-emag,l-si,?rifyam,??ue:.&a&-q,c,?cm,dc,e&b,d,e,i,m,s,?g&b,n,?hc,i&f,s,?k&d,m,s,u,?l&a,i,n,p,?n&c,i,?o&n,r,ssa,?pj,r&f,g,h,k,t,?s&e,i:rap,,u,?t&a,en,i,l,m,ni,p,?u&a,de,h,l,r,?vl,y&c,m,?z&c,n,??,vresnyd,x&inuemoh,unilemoh,?y&limafxut,srab,???ub&mah?oj???s!.&delacsne,gro?moc?rep?t&en?opsgolb,?ude?vog??gb639j43us5--nx??t?u!.&c&a?s??en?gro?moc?o&c?g??ro?topsgolb,??v!.ta,a1c--nx??wsa08--nx??h&0ee5a3ld2ckx--nx?4wc3o--nx!.&a&2xyc3o--nx?3j0hc3m--nx?ve4b3c0oc21--nx??id1kzuc3h--nx?l8bxi8ifc21--nx?rb0ef1c21--nx???8&8yvfe--nx?a7maabgm--nx??b!.&gro?moc?ten?ude?vog??mg??c!.&7erauqs,amil4,duolc-drayknil,etisbew321,gniksnd,p&h21,ohsdaerpsym,?sndtog,topsgolb,wolf.e&a.1pla,nigneppa,?xi2,ytic-amil,?aoc?et?ir!euz??r&aes?uhc??sob?taw!s???d0sbgp--nx?f&2lpbgm--nx?k??g!.&gro?lim?moc?ude?vog???m!a1j--nx??ocir?p!.&gro?i?lim?moc?ogn?ten?ude?vog???s!.&g&nabhsah,ro??l&im?xv,?m&oc?roftalp.&cb,su,tne,ue,??pib,ten",
+ "?vog?won,yolpedew,?a&c?nom??i&d?f?ri???t!.&ca?enilno,im?ni?o&c?g??pohs,ro?ten??iaf!.oby,?laeh!.arh,?orxer?rae??vo!.lopdren,?zb??i&3tupk--nx?7a0oi--nx?a!.&ffo?gro?moc?ten?uwu,?1p--nx?bud?dnuyh?tnihc??b!.&gro?moc?oc?ro?ude??ahduba?o!m!.&duolcsd,ysrab,???s??c!.&ayb-tropora--nx?ca?d&e?m??esserp?gro?ln,moc?nif,o&c?g?ssa??ro?t&en?ni?roporéa??ude?vuog??cug?t??d&dk?ua??e&bhf--nx?piat??f!.&aw5-nenikkh--nx,dnala?i&ki,spak,?mroftalpduolc.if,nenikkäh,pohsdaerpsym,retnecatad.&omed,saap,?topsgolb,uvisitok321,yd,?onas??g!.&d&om?tl??gro?moc?ude?vog???h&c&atih?ra??s&abodoy?ibustim???juohs?k!.&gro?moc?ofni?ten?ude?vog?zib??b4gc--nx?iw!.remarf,?nisleh?s?uzus??l!.&aac,topsgolb,?drahcir?iamsi??maim?n!.&b&ew?og??ca?gro?lim?mo&c?n??ni?o&c?fni??pp?t&en?ni??ude?zib??airpic?i&hgrobmal?m??re??om?rarref?s!.&egaptig,ppatig,topsgolb,?ed??t&i&c?nifni??rahb??ut?v!.&21k?gro?moc?oc?ten???wik?xa&rp?t??yf??j&6pqgza9iabgm--nx?8da1tabbgl--nx?b!.&acirfa?eto?gro?m&oc?siruot??o&c!e??fni?noce?rga?tser??russa?s&etcetihcra?risiol?tacova??t&en?naruatser?opsgolb,?ude?vinu?yenom???d?f!.&ca?eman?gro?lim?moc?o&fni?rp??ten?vog?zib???nj?s?t!.&bew?c&a?in??eman?gro?lim?moc?o&c?g??t&en?ni?set??ude?vog?zib???yqx94qit--nx??k&8uxp3--nx?924tcf--nx?arfel?c&a&bdeef?lb??ebdnul?ilc?reme??d!.&e&disemmejh321,rots,?ger,mrif,oc,pohsdaerpsym,topsgolb,zib,?t??e&es?samet??h!.&a&4ya0cu--nx?5wqmg--nx??b3qa0do--nx?cni,d&2&2svcw--nx?3rvcl--nx??5xq55--nx?tl,?g&a0nt--nx?la0do--nx?ro??i&050qmg--nx?7a0oi--nx?xa0km--nx??m&1qtxm--nx?oc??npqic--nx?saaces,t&en?opsgolb,?ude?v&di?og?ta0cu--nx??xva0fz--nx?人&个?個?箇??司公?府政?絡&網?网??織&組?组??织&組?组??络&網?网??育&敎?教???n??i&tsob?vdnas??l!.&bew?c&a?os??dtl?gro?hcs?letoh?moc?nssa?ogn?prg?t&en?ni??ude?vog??at?cd?is??m!.&eman?fni?gro?moc?t&en?opsgolb,?ude?vog???n&ab!cfdh?etats?mmoc?t&en?fos??u??i!l!.&noyc,pepym,??p???oob?p!.&b&ew?og??gro?kog?m&af?oc??nog?ofni?pog?sog?ten?ude?vog?zib???row!ten!.&htumiza,nolt,o&c,vra,????s!.topsgolb,?t?u!.&c&a?lp??dtl?e&cilop?m??gro!.&gul:g,,sgul,yr&ettoly&lkeew,tiniffa,?tneelffar,???lenap-tnednepedni,n&noc,oissimmoc-&layor,tnednepedni,??o&c!.&bunsorter.tsuc,en&ilnoysrab,ozgniebllew,?krametyb.&hd,mv,?omida,p&i-on,ohsdaerpsym,?t&fihsreyal.j,opsgolb,?vres-hn,ysrab,??rpoc,?psoh,shn?t&en?nmyp,seuqni-tnednepedni,?vog!.&eci&ffoemoh,vres,?ipa,ngiapmac,??weiver-tnednepedni,y&riuqni-&cilbup,tnednepedni,?srab,????l&04sr4w--nx?a!.&gro?lim?moc?t&en?opsgolb,?ude?vog??bolg?c?ed?g!el??i&c&nanif!.oc,lpl??os??romem?tnedurp??n&if?oitanretni??t&i&gid!.sppaduolc:.nodnol,,?p&ac?soh???ned?ot??utum!nretsewhtron???c!.&bog?lim?oc?topsgolb,vog???dil?e&datic?n&ahc?nahc!rehtaew???t!ria?tam??vart??f&8f&pbgo--nx?tbgm--nx??a?n??g!.&gro?moc?oc?ten?ude?xx,zib,??h&d?op??i!.&21k?ca?fdi?gro?inum?oc!.&egapvar,redrotibat,t&ibatym,opsgolb,???ten?vog??a&f?m&e?g?toh???m?r??l&a&b&esab?t&eksab!.&sua,zn,??oof???c?mt??e&d?hs??ihmailliw?j??m!.&esserp?gro?moc?ten?ude?v&og?uog????n!.&etisbew321,no&med,rtsic,?oc,pohsdaerpsym,retsulc-gnitsoh,topsgolb,vog,yalphk,?o??o&a?btuf?l!.gmo,?o&c!.&ed,rotnemele,??hcs??rit?u??p!.&a&cin&diws?gel??d&g,ortso?urawon??i&dem?mraw?nydg,?k&elo&guld?rtso??slopolam?tsu?ytsyrut??l&ip?o&kzs?w&-awolats?oksnok????n&erapohs,img?zcel,?rog&-ai&bab?nelej??j?z??syn?tsaim?w&a&l&eib?i?o??zsraw??o&namil?tainop,??z&eiwolaib?mol???c&e&iw&alselob?o&nsos?rtso???le&im?zrogz???orw,p??d&em,ia?ragrats?uolc&inu,sds,??e&c&i&lrog?w&ilg,o&hc&arats?orp??klop?tak????yzreibok??i&csjuoniws?ksromop?saldop??l&ahdop?opo??napokaz,t&atselaer?iselpmis,?z&romop?swozam???g&alble?ezrbo&lok?nrat??ro??hcyzrblaw?i&csomohcurein?grat?klawus??k&e&rut?walcolw??in&byr?diws,sark,?le?o&nas?tsylaib??rob&el?lam??s&als?jazel?nadg,puls?rowezrp???l&colw?e&r?vart??i&am?m???m&o&c?dar?n?tyb??s&g?iruot??t!a???n&a&gaz?nzop,?i&bul?cezczs?lbul,molow?nok?zd&eb?obeiws???uleiw?y&tzslo?z&rtek?seic????o&c,fni?k&celo?zdolk??lkan?n&leim?pek?t&uk?yzczs??z&copo?eing?rowaj???rga?tua?w&ejarg?ogarm???p&e&eb,lks!emoh,??klwwortso?ohs!-ecremmoce,daerpsym,??romophcaz?sos?t&aiwop?en?opos,ra,sezc??ude?v&irp?og!.&a&io?p?s!w???bni&p?w??ci?dtiw?e&ko?ss&p?w???fiw?g&imu?u??hiiw?m&igu?rio?u!o???nds!ipz??o&ks?p!pu??s?wtsorats??p&a?sp!mk?pk?wk??u&m?p??wk?z??r&hcso?ksw?p?s??s&i?oiw?u?zu??talusnok?w&gzr?i&p?rg?w??m?o&o?pu??u!imzw???z&kw?ouw?????w&a&l&corw?sizdow??w??o&golg?k&ark,ul?zsurp??r&az?gew??t&rabul,sugua??z&coks?sezr????xes?y&buzsak?d&azczseib?ikseb??hcyt?n&jes?lod-zreimizak??pal?r&ogt?uzam??walup?zutrak??z&am-awar?c&aprak?iwol?zsogdyb??dalezc?ib?s&i&lak?p??uklo????l??r&as?f?s??s!.&gro?moc?ten?ude?vog???t!.vog??ubnatsi?x3b689qq6--nx?yc5rb54--nx??m&00tsb3--nx?1qtxm--nx?981rvj--nx?a!.&aayn,enummoc?gro?moc?o&c?idar,ken,?t&en?opsgolb,??c!bew??dretsma?e&rts?t!.&citsalej,esruocsid,???fma?xq--nx??b!.&gro?moc?ten?ude?vog??i??c!.&moc?oc?ten?vog???d!.&gro?moc?ten?ude?vog???f!.&gro?moc?oidar,ten?ude??i??g!vu96d8syzf--nx??h?i!.&ca?gro?moc?o&c!.&clp?dtl???r,?t&en?t??vt??k?rbg4--nx??k!.&drp?e&rianiretev?sserp??gro?lim?m&o&c?n??t??nicedem?ossa?pooc?s&eriaton?neicamrahp?sa??ude?v&og?uog????l&if?ohkcots??o!.&dem?gro?m&oc?uesum??o&c?rp??ten?ude?vog??b?c!.&0x,2aq,3pmevres,5sndd,a&c&-morf,ir&bafno,fa,??g&-morf,oy-sehcaet,?i-morf,m&-morf,all&-a-si,amai,??p&-morf,c-a-si,?r&emacytirucesym,odih,?s,tadtsudgniht,v-morf,w-morf,z,?b&ew&-sndnyd,arukas,draiw.segap,ottad,?ildts.ipa,?c&amytirucesemoh,d-morf,esyrcs,itsalej.omed,n&-morf,vym,?p&kroweht,ytirucesemoh,?q,rievres,s-morf,?d&aerotffuts,e&calpb,ifitrec-&si,ton-si,?llortnocduolc,rewopenignepw:.sj,,tsohecapsppa,?i&-morf,rgevissam.saap,?m-morf,n&-morf,abeht-htiw-si,?s-morf,uolc&-noitatsyalp,hr,iafaw.&d&ej,yr,?nol,?meaeboda,nevia,panqym:-&ahpla,ved,?,smetsystuo,tekcilc,ved&j,pw,??vreser,wetomer,?e&butuoyhtiw,ciffo-sndnyd,d:-morf,o&celgoog,n&il.srebmem,neve.&1-&su,ue,?2-&su,ue,?3-&su,ue,?4-&su,ue,????,erf&-sndnyd,sndd,?filflahevres,g&de-yltsaf,nahcxeevres,?i&hcet-a-si,p-sekil,?k&auqevres,irtsretnuocevres,?l&bitpa-no,googhtiw,?m&agevres,ina-otni-si,oh-&sndnyd,ta-sndnyd,??n&-morf,ilno&-evreser,ysrab,?og-si,?r&alfduolcyrt,ehwynanohtyp:.ue,,ihcec,?srun-a-si,t&i&nuarepo,s&-ybboh,aloy,elpmis,tipohs,xiw,??omer-sndnyd,upmocsma,ysgolb,?v&als-elcibuc-a-si,i&lsndd,tavresnoc-a-si,??z&amkcar,eelg,iig,??fehc-a-si,g&ni&gats-&raeghtua,swennwot,?ksndd,robsikrow,tsoh-bt.etis,?o&fgp,lb&-sndnyd,sihtsetirw,???h&n-morf,o-morf,?i&fiwehtno,h-morf,kiw-sndnyd,m-morf,p&aerocne,detsoh,?r-morf,w-morf,z&ihcppa,nilppa,??jn-morf,k&a&-morf,erfocsic,?cils-si,eeg&-a&-si,si,?sndd,?h,latsnaebcitsale:.&1-&htuos-pa,lartnec-&ac,ue,?ts&ae&-&as,su,?ht&ron-pa,uos-pa,??ew-&su,ue,vog-su,???2-ts&ae&-su,ht&ron-pa,uos-pa,??ew-&su,ue,??3-ts&aehtron-pa,ew-ue,??,o-morf,r&adhtiwtliub,ow&-&sndnyd,ta-sndnyd,?ten-orehkcats,??sedal,u,?l&a&-morf,colottad,rebil-a-si,?f-morf,i&-morf,am&-sndnyd,detsohpw,??l&ecelffaw,uf-ytnuob:.a&hpla,teb,?,?ppmswa,ru-&elpmis,taen,?ssukoreh,xegap,?m&n-morf,pml.ppa,rofe&pyt.orp,rerac-htlaeh,?sacrasevres,uirarret-yltsaf,?n&a&cilbuper-a-si,f&-sllub-a-si,racsan-a-si,?i&cisum-a-si,ratrebil-a-si,?tarukas,?c,dc&hsums,umpw,xirtrepmi,?eerg-a-si,i&-morf,jod,?m-morf,o&ehtnaptog,isam-al-a-tse,r&italik,tap-el-tse,?s&iam-al-a-tse,replausunu,??pj,t-morf,?o&bordym,c,hce-namtsop,jodsnd,m&-morf,ed-baltlow,?n:iloxip,,ttadym,?p&2pevres,aelutym,i&-sndnyd,fles,ogol,ruoy&esol,hctid,?ym&eerf,teg,??ohsdaerpsym,pa&-rettalp,anis:piv,,esaberif,k1,lortnocduolc,oifilauq,r&aegyks,oetem:.ue,,?t&ilmaerts,norfegap,?ukoreh,?t&fevres,thevres,??r&081,a:-morf,tskcor-a-si,,b,e&d&iv&erp-yb-detsoh.saap,orpnwo,?ner&.ppa,no,??e&bevres,nigne-na-si,?ggolb-a-si,h&caet-a-si,pargotohp-a-si,?krow-drah-a-si,n&gised-a-si,ia&rtlanosrep-a-si,tretne-na-si,??p&acsdnal-a-si,eekkoob-a-si,?retac-a-si,subq,tn&ecysrab,iap-a-si,uh-a-si,?vres&-&ki.&cpj-rev-duolcj,duolcj,?s&ndnyd,pvtsaf,??inim,nmad,sak,?y&alp-a-si,wal-a-si,?zilibomdeepsegap,?g,ituob,k,mgrp.nex,o&-morf,sivdalaicnanif-a-si,t&areleccalabolgswa,c&a-na-si,od-a-si,?susaym,??p-morf,u&as-o-nyd,e&tsoh.&duolc-gar,hc-duolc-gar,?ugolb-nom-tse,?omuhevres,??s&a&apod,ila&nyd,snd,?nymsd,vnacremarf,?bbevres,ci&p&-sndnyd,evres,?tcatytiruces,?dylimaf,e&cived-anelab,itilitu3,lahw-eht-sevas,mag-otni-si,t&i&iis,sro,?yskciuq,??fpi-&eralfduolc,fc,?i&ht2tniop,pa&elgoog,tneltneg,??jfac,k&-morf,aerf-ten,colb&egrof,pohsym,??m&-morf,cxolb,?n&d&-pmet,dyard,golb,htiwssem,mood,tog,?kselp,nyd,ootrac-otni-si,?o&-xobeerf,xobeerf,?ppa&-avnac,raeghtua,t&ikria,neg,??r&ac-otni-si,e&ntrap-paelut,tsohmaerd,??s&e&l-rof-slles,rtca-na-si,?ibodym,?tsaeb-cihtym.&a&llicno,zno,?ilay,lacarac,re&gitnef,motsuc,?sv,toleco,x:n&ihps,yl,?,?u,wanozama.&1-&ht&ron-ue.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??uos-&em.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??fa.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??pa&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,??ue.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,????la&nretxe-3s,rtnec-&ac&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,??ue&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,????ts&ae&-&as&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,??pa.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??su:-etisbew-3s,.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,yawetag-scitylana,?,?ht&ron-pa&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,yawetag-scitylana,??uos-pa&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,????ew-&su&-&3s,etisbew-3s,?.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,???ue&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,yawetag-scitylana,??vog-su-&3s,spif-3s,????2-ts&ae&-su&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,yawetag-scitylana,??ht&ron-pa&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,??uos-pa&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,????ew-&su&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??yawetag-scitylana,??ue&-3",
+ "s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,????3&-ts&aehtron-pa.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??ew-ue&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,???s,??yasdrocsid,?t&arcomed-a-si,c&-morf,etedatad.&ecnatsni,omed,??eel&-si,rebu-si,?hgilfhtiwletoh,i:batym,,m-morf,n&atnuocca-na-si,e&duts-a-si,r-ot-ecaps,tnocresu&buhtig,e&capsppa,donil.pi,lbavresbo.citats,?pl,???ops&edoc,golb,ppa,?s&i&hcrana-&a-si,na-si,?laicos-a-si,pareht-a-si,tra-na-si,xetn&od,seod,??oh&piym,sfn,??u&-morf,nyekcoh-asi,?v-morf,?u&-rof-slles,4,a-sppatikria,e,h,oynahtretramssi,r:ug-a-si,,?v&n-morf,rdlf,w-morf,?w&o&lpwons-yrt,zok,?ww100,?x&bsbf.sppa,em,i&nuemoh,rtrepmi,?obaniateb,t-morf,unilemoh,?y&a&bnx:.&2u,lacol-2u,?,l&erottad,pezam,?wetag-llawerif,?dnacsekil,fipohsym,k&-morf,niksisnd,?rot&ceridevitcaym,sitk,?u:goo,,w-morf,x&alagkeeg,orp&hsilbup,mapson.duolc,???zesdrocsid,?inu??m?or?tsla??p!.&eman,nwo,??raf!.jrots,etats??s?t!.&gro?lim?mo&c?n??oc?ten?ude?vog???u&esum?rof??z!.&ca?gro?hcs?lim?moc?o&c?fni??ten?ude?vog?zib????n&315rmi--nx?a&brud?cilbuper?f?grompj?hkaga?idraug?m?ol?ssin?u&hix?qna??varac?yalo??b!.&gro?moc?oc,ten?ude?vog??c??c!.&ah?bh?c&a?s??d&5xq55--nx?g?s?uolctnatsni,?eh?g&la0do--nx?ro??h&a?q?s??i&7a0oi--nx?h??j&b?f?t?x?z??kh?l&h?im?j??m&n?oc!.swanozama.&1-htron-nc.3s,be.1-&htron-nc,tsewhtron-nc,????n&h?l?s?y??om?qc?s&g?j?ppa-avnac,?t&cennockciuq.tcerid,en??ude?vog?wt?x&g?j?n?s??z&g?x??司公?絡網?络网??b??d&g!.ypnc,?ka??e&drag?erg?fuak?gawsklov?hctik?i&libommi?w??m?po?r!ednaalv??sier?ves??g!.&ca?gro?moc?ten?ude?vog??is&ed!.ssb,?irev???h!.&bog?cc,gro?lim?moc?ten?ude???i!.&ac?bew,c&a?in??dni?e&m?sabapus,?g&5?6?p?ro??i&a?hled??ku?l&evart?im??m&a?oc?rif??n&c?eg??o&c?fni?i?rp??p&ooc?u??r&ahib?d?e??s&c?er?nduolc,senisub?u??t&arajug?en!retni??ni?opsgolb,sop??ude?v&og?t??ysrab,zib??elknivlac?griv?ks?lreb?p?v?w?x??k!.&gro?ten?ude?vog???l&eok?ocnil??m!.&cyn,gro?ude?vog???o&dnol?i&hsaf?n&o?utiderc??siv!orue??t&a&cude!.oc,?dnuof?tsyalp??c&etorp?u&a?rtsnoc?????kin?las?mrom?nac?p&q?uoc??s&iam?pe?scire??t&ron?sob??zama??p!.&gro?oc?ten?ude?vog??k??r&e&c?yab??op!.eidni,??s!.&gro?moc?osrep?t&opsgolb,ra??ude?v&inu?uog????t!.&d&ni?uolcegnaro,?gro?ltni?m&oc!nim??siruot??nif?o&fni?srep??sne?t&an?en??vog??m??u&f?r!.&bdnevar,lper,retropno,s&h,revres,?tnempoleved,??stad?xamay?y??v!.&a&lnos?ohhnah&k?t???c&a?ouhphnib?uhphniv??di?e&man?rtneb?uhneihtauht??g&n&a&boac?ig&ah?cab?n&a?ei&k?t???uah??nad?rtcos?uqneyut??o&dmal?hpiah?lhniv?nkad?ud&hnib?iah????ro??h&ni&b&aoh?gnauq?hnin?iaht??d&hnib?man??mihcohohphnaht?n&cab?gnauq?yat??tah?vart??tlaeh??i&a!bney?coal?gngnauq?laig?ngnod??onah?rtgnauq??kalkad?m&an&ah?gnauq??oc?utnok??n&a&ehgn?gnol?kcab?uhthni&b?n???e&ibneid?y&gnuh?u&gniaht?hp????osgnal??o&fni?ht&nac?uhp??i?rp??pahtgnod?t&en?ni?opsgolb,?u&a&hcial?mac?tgnuv-airab??de?eilcab??vog?zib???wo&rc?t!epac????o&76i4orfy--nx?a!.&bp?de?go?oc?ti?vg??boat??b!.&a&ci&sum?tilop??i&c&arcomed?neic??golo&ce?ncet??m&edaca?onoce??rt&ap?sudni??vilob??n&egidni?icidem??serpme?tsiver?vitarepooc??b&ew?og??dulas?e&rbmon?tr&a?op&ed?snart????g&olb?ro??ikiw?l&a&noi&canirulp?seforp??rutan??im??moc?o&fni?lbeup?rga?tneimivom??saiciton?t&askt?en?ni??ude?vt??h?iew?olg??c!.&bew?cer?dr&c,rac,?esabapus,gro?ipym,l&im?per:.di,,?m&o&c!.topsgolb,?n??rif??ofni?s&egap&dael,l,?tra??t&4n,en?ilperdellawerif:.di,,ni??ude?vog??a?e?in?mara?s&edarb?ic???d!.&b&ew?og??dls?gro?lim?moc?t&en?ra??ude?vog??agoba?if?zd7acbgm--nx??e&c?d&iv?or???f!ni!.&e&g&delwonk-fo-l&errab,lerrab,?ellocevoli,?ht-skorg,rom-rof-ereh,tadpusn:d,,?llatiswonk,macrvd,ofni-v,p&i&-on,fles,?ohbew,?ruo-rof,s&iht-skorg,nd&-cimanyd,nyd,uolc,??tsrifyam,ysrab,zmurof,???g&el?n!am?ib???hwsohw?i!.&35nyd,8302,a&minifed,tad-b,?b&altig,uhtig,?czh,d&in,raobelgaeb,u&olc&iaznab.ppa,ropav,?rd,??e&c&apsinu.1rf-duolc,ivedniser,?donppad.sndnyd,egipa,lej,nilnigol,sufxob,t&i&beulb,snoehtnap,?newtu,ybeeb.saap,??gni&gatsniser.secived,tsohytsoh,?ilpu,k&coregrof.di,orgn:.&as,ni,p&a,j,?su,u&a,e,??,ramytefasresworb,?moc?n&aicisum,mtsp:.kcom,,yded,?ot&oq,pyrctfihs,?p&opilol,pa&-arusah,e&nalpkcab,tybeeb.1dkes,???r&e&tsneum-hf,vres&cisab,lautriv,??ial.sppa,?s&codehtdaer,gnihtbew,nemeis-om,pparevelc,t&acdnas,ekcit,??t&e&kcubtib,notorp,?i&belet,detfihs,gude,kecaps,?raedon.egats,s&ohg,udgniht.&cersid.&dvreser,tsuc,?dorp.tsuc,gnitset.&dvreser,tsuc,?ved.&dvreser,tsuc,????vgib.0ku,whs,x&bslprbv.g,cq,rotide,?y&olpedew,srab,??b?d&ar?u&a?ts???j?r?syhp??j!.&eman?gro?hcs?lim?moc?ten?ude?vog???ll&ag?o??m!.&gro?moc?ten?ude?vog??g?il?mi?orp??n!.&a&0&b-ekhgnark--nx?c-iehsrgev--nx?g-lksedlig--nx?k-negnanvk--nx??1&p-nedragy--nx?q-&asierrs--nx?grebsnt--nx?lado-rs--nx?n&egnidl--nx?orf-rs--nx??regnayh--nx?ssofenh--nx??r-datsgrt--nx?s-ladrjts--nx?v-y&senner--nx?vrejks--nx???3g-datsobegh--nx?4&5-&dnaleprj--nx?goksnerl--nx?tednalyh--nx??6-neladnjm--nx?s-&antouvachb--nx?impouvtalm--nx??y-&agrjnevvad--nx?ikhvlaraeb--nx???7k-antouvacchb--nx?8&k-rekie-erv--nx?l-ladrua-rs--nx?m-darehsdrk--nx??a!.sg??bct-eimeuvejsemn--nx?d&do?iisevvad?lov?narts?uas??f&1-&l--nx?s--nx??2-h--nx??g&10aq0-ineve--nx?av?ev?lot?r&ajn&evvad?u??ájn&evvad?u????h?iz-lf--nx?j&ddadab?sel??k&el?hoj&sarak?šárák??iiv&ag&na&el?g??ŋ&ael?ág???ran???l&f?lahrevo?o&ms?s??sennev?t-&ilm--nx?tom--nx??u&-edr--nx?s??øms??muar?n&0-tsr--nx?2-dob--nx?5-&asir--nx?tals--nx??a&r!-i-om?f?t??t??douvsatvid?kiv?m&os?øs??n&od?ød??ra?sen?t&aouvatheig?ouv&a&c&ch&ab?áb??h&ab?áb???n??i&ag?ág??sa&mo?ttvid??án???z-rey--nx?ær&f?t???o&p-&ladr--nx?sens--nx??q-nagv--nx?r-asns--nx?s-kjks--nx?v-murb--nx?w-&anr&f--nx?t--nx??ublk--nx???ppol?q&0-t&baol--nx?soum--nx?veib--nx??x-&ipphl--nx?r&embh--nx?imph--nx???y-tinks--nx??r&f-atsr--nx?g-&an&ms--nx?nd--nx??e&drf--nx?ngs--nx??murs--nx?netl--nx?olmb--nx?sorr--nx??h-&a&lms--nx?yrf--nx??emjt--nx??i&-&lboh--nx?rsir--nx?y&d&ar--nx?na--nx??ksa--nx?lem--nx?r&ul--nx?yd--nx????stu??j-&drav--nx?rolf--nx?sdav--nx??kua?l-&drojf--nx?lares--nx??m-tlohr--nx?n-esans--nx?olf?p-sdnil--nx?s-ladrl--nx?tih?v-rvsyt--nx??s&a&ns?ons??i&ar?er&dron?r&os?øs???ár??la&g?h??mor!t??sir?uf?åns??t&koulo&nka?ŋká??la?p-raddjb--nx?r-agrjnu--nx?s&aefr&ammah?ámmáh??orf?r&o?ø???u-vreiks--nx??u&h-dnusel--nx?i-&drojfk--nx?vleslm--nx??j-ekerom--nx?k-rekrem--nx?u-&dnalr--nx?goksr--nx?sensk--nx??v-nekyr--nx?w-&k&abrd--nx?ivjg--nx??oryso--nx??y-y&dnas--nx?mrak--nx?n&art--nx?nif--nx??reva--nx??z-smort--nx??v!.sg?ledatskork?reiks??wh-antouvn--nx?x&9-dlofts--nx.aoq-relv--nx?d-nmaherk--nx?f-dnalnks--nx?h-neltloh--nx?i-drgeppo--nx?j-gve&gnal--nx?lreb--nx??m-negnilr--nx?n-drojfvk--nx??y&7-ujdaehal--nx?8-antouvig--nx?b-&dlofrs--nx?goksmr--nx?kivryr--nx?retslj--nx??e-nejsom--nx?f-y&krajb--nx?re&dni--nx?tso--nx??stivk--nx??g-regark--nx?orf?ørf??z9-drojfstb--nx??b&25-akiivagael--nx?53ay7-olousech--nx?a&iy-gv--nx?le-tl&b--nx?s--nx??n0-ydr--nx??c&0-dnal-erdns--nx?z-netot-erts--nx??g&g-regnarav-rs--nx?o-nejssendnas--nx??ju-erdils-ertsy--nx?nj-dnalh-goksrua--nx?q&q-ladsmor-go-erm--nx.&ari-yreh--nx?ednas??s-neslahsladrjts--nx???ca&4s-atsaefrmmh--nx?8m-dnusynnrb--nx?il-tl--nx?le-slg--nx?n5-rdib--nx?op-drgl--nx?uw-ynnrb--nx??d&a&qx-tggrv--nx?reh!nnivk?sd&ork?ørk??uas??ts&e&bi?kkar?llyh?nnan??g&ort?ørt??k&alf?irderf??levev?mirg?obeg&ah?æh??r&ah?ejg????barm-jdddb--nx?ie!rah?s&etivk?ladman???lof&r&os?øs??ts&ev.ednas?o.relav?ø.relåv???n&a&l&-erd&n&os?øs??ron??adroh.so?dron.&a&g5-b--nx?ri-yreh--nx??ob?y&oreh?øreh??øb??e&m!lejh??pr&oj?øj??vi??gyb?n&aks?åks??o&h-goksrua?rf??r&o?ua?ø??tros?øh-goksrua??rts!e&devt?lab?mloh???s&ellil?naitsirk?rof???u&l!os??s!d&im?lejt??e&guah?l&a?å???kkoh?lavk?naitsirk?r&af?eg&e?ie???tef?y&onnorb?ønnørb?????r&a&blavs!.sg??g&eppo?la???o&j&f&a!dniv?k?vk??die?e&dnas?kkelf??llins?r&iel?ots??s&lab?t&ab?åb??yt??å!k??ævk??les??ts??åg&eppo?lå???ureksub.sen??e&ayb-yrettn--nx?d&ar?isemmejh321,lom?r&of?øf??år??g&gyr?nats??i&meuv&ejsem&aan?åån??sekaal??rjea??j&d&ef?oks??les??k&er&aom?åom??hgna&ark?årk??iregnir?kot!s??s&ig?uaf???l&bmab?kyb?l&av?ehtats??oh??m&it?ojt?øjt??n&arg?g&os?øs??meh?reil?te?ummok?yrb??r&dils-erts&ev?y&o?ø???ua?vod??sa&ans?åns??t&robraa?spaav??urg??f&62ats-ugsrop--nx?a&10-ujvrekkhr--nx?7k-tajjrv-attm--nx??o!.sg?h??s!.sg??v!.sg???g&5aly-yr&n--nx?v--nx??a&llor?ve&gnal?lreb???n&av!snellu??org??oks&die?m&or?ør??ner&ol?øl??r&o?ø???r&eb!adnar?edyps?s&die?elf?gnok?n&ot?øt????obspras??uahatsla?åve&gnal?lreb???h&0alu-ysm--nx?7&4ay8-akiivagg--nx?5ay7-atkoulok--nx??a!.sg???i&e&hsr&agev?ågev??rf??k&h&avlaraeb?ávlaraeb??s??lm&a?å??mpouvtal&am?ám??pph&al?ál??rrounaddleid?ssaneve?ššáneve??j&0aoq-ysgv--nx?94bawh-akhojrk--nx??k&a&b&ord?ørd??jks?lleis??iv!aklejps?l&am?evs?u??mag?nel?ojg?r&a&l?n??epok?iel?y&or?ør???s&ah?kel?om??øjg??kabene?ojsarak?ram&deh.&aoq-relv--nx?rel&av?åv??so??e&let.&ag5-b--nx?ob?øb??ra???åjks??l&a!d&anrus?d&numurb?ron??e&gnard?nte?s&meh?sin??ttin??g&is?nyl??kro?l&em?l&ejfttah?of??u&ag-ertdim?s???n&am?era?gos?i&b?nroh?r??kos?nus?oj??o-&dron?r&os?øs???ppo?r&a!l?nram??e&gne?l?v??is?o&jts?ts??u&a-&dron?r&os?øs???h??å?æl?øjts??s&e&jg?nivk?ryf??kav?mor-go-er&om.&ednas?yoreh??øm.&ednas?yøreh???uag??t&las?rajh?suan??v&l&a?e-rots??u-go-eron??yt??ksedlig?res&a?å???bib&eklof?seklyf??es!dah??h!.sg??i&m?syrt??l&ejf?ov&etsua?gnit?ksa?sdie???n!.sg??o!.sg?boh?g?h??r!.sg??å!ksedlig??øboh??m&a&rah?vk??f!.sg??h!.sg??i&e&h&dnort?rtsua?ssej??rkrejb??ksa??ol?t!.sg??u&dom?esum?r&ab?drejg?evle?os?uh?æb?øs??ttals???n&a&g&av?okssman?åv??jlis?or?r&g?rev???e&d&do&sen?ton??lah?r&agy&o?ø??ojfsam???g&iets?n&a&l&as?lab??n&avk?ævk??t&arg?ddosen??v&al?essov???i&d&ol?øl??l&ar?ær???yl??reb??iks?k&srot?y&or?ør???l&a&d&gnos?n&er?ojm?øjm??om??tloh??ug?åtloh??mmard?ojs&om?sendnas??ppolg?s&lahsladr&ojts?øjts??o??t&o&l?t-erts&ev?o?ø???roh?øl??vly&kkys?nav??yam-naj!.sg??øjs&om?sendnas???g&orf?ujb??i&dnaort?vnarg??kob?ladendua?maherk&a?å??n&it?urgsrop??orf-&dron?r&os?øs???r&aieb?evats??sfev?uaks?yrts??o&6axi-ygvtsev--nx?c,d&ob?rav??ievs?kssouf?l&m&ob?øb??ous&adna?ech&ac?áč???so!.sg???msdeks?niekotuak?r&egark?olf?y&oso?øso???s&dav?mort???p&ed?ohsdaerpsym,p&akdron?elk???r&a&d&dj&ab?áb??iab??jtif?luag?mah?vsyt??",
+ "e&gn&a&k&iel?ro??merb?n&at?mas??rav-r&os?øs??srop?talf?v&ats?el??y&oh?øh???ivsgnok??il?jkniets?k&a&nvej?rem?s&gnir?nellu???ie-er&den?v&o?ø???ram?sa?årem??la&jf?vh??m&b&ah?áh??mahellil??nnul?ts&l&oj?øj??ul??y&o?ø???imp&ah?áh??m!.sg??osir?t!.sg??ádiáb?ævsyt?øsir??s&adnil?en&dnas?e&dga?k&ri&b?k??som??ve??me&h?jg??nroh-go-ejve?s&a?ednil?k&o?ø??of?yt?å??tsev??gv?hf?igaval?o&r&or?ør??sman??so&fen&oh?øh??m?v??uh&lem?sreka.sen??å!dnil???t&a&baol?g&aov?grav??jjr&av-attam?áv-attám??l&a&b?s??ás??soum?ts?v&eib?our???e&dnaly&oh?øh??f?s&nyt?rokomsdeks?sen??vtpiks??in&aks?áks??loh&ar?år??n!.sg??o&m&a?å??psgolb,?s!.sg?efremmah?or?ør??terdi?á&baol?ggráv?lá&b?s??soum?veib???u&b!.sg?alk?e&dna?gnir?nner??les?ælk??dra&b?eb??g&nasrop?vi?ŋásrop??j&daehal&a?á??jedub?v&arekkhar?árekkhár???ksiouf?n&diaegadvoug?taed???v&irp?lesl&am?åm???y&b&essen?nart?sebel?tsev??o&d&ar?na!s??or??gavtsev?k&rajb?sa??lem?mrak?n&art?n&if?orb???r&a&mah?n?v??e&dni?t&so?ton??va??ul?yd??s&am?enner?gav?lrak?tivk??vrejks??ø&d&ar?na!s??ør??gåvtsev?k&rajb?sa??lem?mrak?n&art?n&if?ørb???r&e&dni?t&so?tøn??va??ul?yd?æ&n?v???s&enner?gåv?tivk?åm??vrejks???á&slág?tlá?vreiks??å&gåv?h?jddådåb?lf??ø&d&ob?rav??r&egark?olf??s&dav?mort????aki?i&sac?tal??u??o&b?f?g?hay?o?ttat??r!.&cer?erots?gro?m&o&c?n??rif?t??o&c,fni??pohs,stra?t&n?opsgolb,?www?ysrab,?e&a!.&a&ac?cgd?idem??bulc!orea??ci&ffartria?taborea??e&cn&a&l&lievrus-ria?ubma??netniam?rusni??erefnoc??gnahcxe?mordorea?ni&gne?lria?zagam??rawtfos??gni&d&art?ilg!arap?gnah???l&dnahdnuorg?ledom??noollab?retac?sael?t&lusnoc?uhcarap??vidyks??hcraeser?l&anruoj?euf?icnuoc?ortnoc!-ciffart-ria???n&gised?oi&nu?t&a&cifitrec?ercer?gi&tsevni-tnedicca?van??i&cossa!-regnessap??valivic??redef??cudorp?neverp-tnedicca????ograc?p&ihsnoipmahc?uorg!gnikrow???r&e&dart?enigne?korb?niart?trahc??o&htua?tacude???s&citsigol?e&civres?r??krow?serp!xe??tnega??t&farcr&ia?otor??hgil&f?orcim??liubemoh?n&atlusnoc?e&duts?m&esuma?n&iatretne?revog??piuqe????olip?ropria?si&lanruoj?tneics???w&erc?ohs??y&cnegreme?dobper?tefas????rref?z??p!.&a&aa?ca?pc??dem?ecartsnd.icb,gne?r&ab?uj??snduolc,t&acova?cca?hcer??wal?ysrab,???s!.&em?gro?hcs,moc?ten?ude?vog???t!.&0x,116,ayo,gro?lim?moc?nayn,sulpnpv,t&cennockciuq.tcerid,en??ude?v&dr,og???o&hp?m?v?yk??tol?ua??v&iv?lov??xas?ykot??p&a&ehc?g?m?s??eej?g!.&gro?ibom?moc?ossa?ppa,ten?ude???i&r!.nalc,?v?z??j!.&0o0o,a&3&5xq6f--nx?xqi0ostn--nx??5wtb6--nx?85uwuu--nx?9xtlk--nx?ad,b&ats,ihc!.&a&bihciakoy?don?ma&him?ye&ragan?tat???r&a&bom?gan?hihci??u&agedos?kas?ustak???s&os?ufomihs??t&amihcay?iran??w&a&g&im&anah?o??omak??kihci?zustum??ihsak??y&agamak?imonihci???e&akas?nagot??i&azni?esohc?h&asa?s&abanuf?ohc???ka&to?zok??musi?orihs?r&akihabihsokoy?o&dim?tak??ukujuk??usihs??nano&hc?yk??o&d&iakustoy?ustam??hsonhot?k&a&rihs?t??iba??nihsaran?sobimanim?tas&arihsimao?imot??uhc?yihcay??u&kujno?s&ayaru?t&imik?tuf???zarasik?????c&cah,ed,?g&as!.&a&gas?m&a&tamah?yik??ihsak??rat?t&a&gatik?hatik??ira!ihsin????e&kaira?nimimak??i&akneg?g&aruyk?o??h&c&amo?uo??siorihs??kaznak?modukuf?ra&gonihsoy?mi???nezih?u&k&at?ohuok??s&ot?tarak?????ihs!.&a&kok?m&a&hagan?yirom??ihsakat??rabiam?wagoton??e&miharot?nokih??houyr?i&azaihsin?esok?kustakat?moihsagih??na&mihcahimo?nok??o&hsia?mag?t&asoyot?ok?tir???us&ay?t&asuk?o??????k&aso!.&a&d&awihsik?eki??k&a&noyot?s&akaayahihc?oihsagih???oadat?uziak??m&ayas!akaso??odak??r&a&bustam?wihsak??ediijuf??t&akarih?i&k?us???wag&ayen?odoyihsagih???e&son?tawanojihs??honim?i&akas?h&cugirom?s&ayabadnot?i&a&kat?t??n??oyimusihsagih???k&a&rabi?sim??ustakat??muzi?r&ijat?otamuk???nan&ak?n&ah?es???o&ay?n&a&ganihcawak?simuzi?tak??eba?ikibah?oyot??t&anim?iad?omamihs??uhc??ust&oimuzi?tes????ou&kuf!.&a&d&amay?eos??g&no?ok?usak??hiku?k&awayim?uzii??ma&kan?y&asih?im???rawak?t&a&gon?ka&h?num?t???umo??wa&g&a&kan?nay?t??ias??ko!rih???y&ihsa?usak???e&m&ay?uruk??taruk?us??i&a&nohs?raihcat??goruk?h&cukuf?s&a&gih?hukuy??in???k&a&gako?muzim??iust?o?ustani??m&anim?otihsoynihs?u??r&ogo?ugasas??usu??ne&siek?zu&b?kihc???o&gukihc?h&ak?ot?ukihc??j&ono?ukihc??kayim?nihsukihc?to?uhc??u&fiazad?gnihs?stoyot????zihs!.&a&bmetog?d&amihs?eijuf?ihsoy?omihs??kouzihs?mihsim?ra&biah?honikam??tawi?wa&g&ekak?ukik??kijuf??yimonijuf??i&a&ra?sok??hcamirom?juf?kaz&eamo?ustam??ma&nnak?ta??nukonuzi?orukuf??nohenawak?o&nosus?ti??u&stamamah?z&a&mun?wak??i!ay?i&hs&agih?in??manim??mihs????????m&a&tias!.&a&d&ihsoy?ot?usah??k&a&dih?sa??o&arihs?s???m&a&tias?y&as?o&rom?tah??ustamihsagih???i&hsagurust?jawak??uri??ni?wa&g&e&ko?man??ikot?o??k&ara?i&hsoy?mak???ru?zorokot??y&a&g&amuk?ihsok?otah??kuf??imo??ziin??e&bakusak?ogawak?sogo?ttas?zokoy??i&baraw?h&cugawak?s&oyim?ubustam???iroy?k&ato?ihs?u&k?stawi???m&akoyr?i&hsoy?juf??uziimak???naznar?o&dakas?ihsay?jnoh?n&a&go?nim??imijuf?nah?oy??r&ihsayim?otagan??t&asim!ak??igus?omatik??zak??u&bihcihc!ihsagih??sonuok?ynah????y&ak&aw!.&a&d&ira?notimak??kadih?ma&h&arihs?im??y&a&kaw?tik??oduk???ru&ustakihcan?y??sauy?wa&g&a&dira?zok??orih??konik??yok?zok??e&banat?dawi??i&garustak?jiat?mani??naniak?o&bog?nimik?t&asim?omihs&ah?uk????ugnihs???o!.&a&jos?koasak?m&ay&ako?ust??ihsayah??r&abi?ukawaihsin??wi&aka?nam???e&gakay?kaw??i&gan?h&cu&kasa?otes??sahakat??k&asim?ihsaruk??miin??n&anemuk?ezib??o&hsotas?jnihs?n&amat?imagak??ohs?uhcibik?????ot!.&a&damay?got?koakat?may&etat?ot??nahoj?riat?waki&inakan?reman???eb&ayo?oruk??i&h&asa?ciimak?sahanuf??kuzanu?m&an&i?ot??ih???nezuyn?otnan?u&hcuf?stimukuf?z&imi?ou???????ihs&o&gak!.&a&m&ayuok?ihsogak??si?yonak??e&banawak?n&at&akan?imanim??uka??tomoonihsin??i&adnesamustas?k&azarukam?oih??m&ama?uzi??usuy??nesi?o&knik?os?tomustam??uzimurat???rih!.&a&ka&n?s??m&ayukuf?i&hsorihihsagih?j&ate?imakikaso????r&a&bohs?h&ekat?im???es??tiak?wiad??e&kato?ruk??i&h&ci&akustah?mono?nihs??s&inares?oyim???manimasa?uk??negokikesnij?o&gnoh?namuk??uhcuf????uk&ot!.&a&bihci?mi&hsu&kot?stamok??m??wagakan??egihsustam?i&gum?h&coganas?soyim??kijaw?m&anim?uzia??ukihsihs??nan&a?iak??o&nati?turan????uf!.&a&batuf?m&a&to?y&enak?irok???ihs&im?ukuf??os?uko??r&aboihsatik?uganat??ta&katik?mawak?rih??w&a&g&akus?emas?uy??k&a&mat?rihs?sa??ihsi??nah??ohs???e&gnabuzia?iman?ta&d?tii???i&adnab?enet?hs&agih?iimagak??k&a&wi?zimuzi??ubay??minuk?r&ook?ustamay???nihsiat?o&g&etomo?ihsin?nan?omihs??no!duruf?rih??rihsawani?ta&may?simuzia???u&rahim?stamakawuzia?zia&ihsin?nay???????nug!.&a&bawak?doyihc?k&anna?oi&hsoy?juf?mot???m&ayakat?ustagaihsagih??n&ihsatak?nak??r&ahonagan?nak?o?u&kati?mamat???t&amun?inomihs?o??w&akubihs?iem?ohs???i&hsa&beam?yabetat??kas&akat?esi??m&akanim?uzio??ogamust?rodim??o&jonakan?n&eu?oyikust??tnihs??u&komnan?stasuk?yrik????rep,?n&ibmab,nog,ob,?ppacihc,ra&n!.&a&bihsak?d&akatotamay?u!o???guraki?m&ay&atik&imak?omihs??irokotamay??oki??ra&hihsak?n??wa&geson?knet???e&kayim?ozamay?sog?ustim??i&a&rukas?wak??garustak?h&ciomihs?sinawak??jo?ka&mnak?toruk??makawak?nos?r&net?otakat?ugeh???o&d&na?oyo??gnas?jnihs?nihsoy!ihsagih??tomarawat?yrok????rikik,?t&ag&amay!.&a&dihsio?k&atarihs?ourust??may&a&kan?rum??enak?onimak??rukho?ta&ga&may?nuf??hakat?kas??wa&g&ekas?orumam??ki&hsin?m??z&anabo?enoy?ot???zuy??e&agas?bonamay?dii?nihsagih?o??i&a&gan?nohs??h&asa?sinawak??nugo??o&dnet?jnihs?ynan??ukohak???iin!.&a&ga?k&ium?oagan??munou!imanim??t&a&bihs?giin??ioy??w&a&gioti?kikes?zuy??irak??yijo??e&kustim?mabust??i&aniat?hcamakot?kaz&awihsak?omuzi??m&a&gat?karum??o???n&anust?esog??o&das?ihcot?jnas?k&ihay?oym??mak?naga?ries??u&ories?steoj?????i&k&a!.&a&go?k&asok?oimak??t&ago!rihcah??ika!atik???w&aki?oyk???e&mojog?natim?suranihsagih?t&ado?okoy???i&hsoyirom?magatak?naokimak??nesiad?o&hakin?jnoh!iruy??nuzak?rihson?tasi&juf?m??yjnoh??u&kobmes?oppah????in,?o!.&a&dakatognub?m&asah?ihsemih??su?t&ekat?i&h?o????e&onokok?ustimak??i&jih?k&asinuk?ias?usu??mukust??onoognub?u&fuy?juk?ppeb?suk?????nayn,?wa&ga&k!.&a&mihsoan?rihotok?waga&kihsagih?ya???emaguram?i&j&nonak?ustnez??kunas?monihcu??o&hsonot?nnam?yotim??u&st&amakat?odat??zatu????nak!.&a&dustam?kus&okoy?tarih??maz?nibe?r&a&gihsaimanim?h&esi?imagas??wa&do?guy???u&im?kamak???tikamay?wa&k&ia?oyik?umas??sijuf??yimonin??e&nokah?saya??i&akan?esiak?gusta?hsuz?kasagihc?o?ukust??o&nadah?sio?tamay?????kihsi!.&a&danihcu?gak?kihs?mijaw?t&abust?ikawak??wazanak??i&gurust?hcionon?mon?ukah??nasukah?o&anan?ton!akan???u&kohak?stamok?z&imana?us?????niko!.&a&han?m&arat?ijemuk?uru??n&e&dak?zi??no??ra&hihsin?rih??wa&kihsi?niko??yehi?zonig??e&osaru?seay??i&hsagih?jomihs?k&a&gihsi?not??ihsakot??m&a&ginuk?kihsug?maz??igo?otekat??nuga!noy???n&a&moti?timoy?wonig??i&jikan?k???o&gan?jnan?tiad&atik?imanim???u&botom?kusug&akan!atik??imot??rab&anoy?eah??????yp,zomim,?bus,c&204ugv--nx?462a0t7--nx?678z7vq5d--nx?94ptr5--nx?a?mpopilol,?d&-2,17sql1--nx?3thr--nx?5&20xbz--nx?40sj5--nx??7&87tlk--nx?ptlk--nx??861ti4--nx?a?e!tfarcdnah,?n&eirf&lrig,yob,?om,?ooftac,?e&16thr--nx?5&1a4m2--nx?9ny7k--nx??damydaer,eweep,garotsarukas.&10ksi.3s,20ksi.3s,?i&bmoz,m!.&a&bot?k&asustam?uzus??m&a&him?y&emak?im???ihs??nawuk?wi&em?k???e&bani?ogawak?si!imanim???i&arataw?gusim?h&asa?ciakkoy??k&a&mat?sosik?t??iat??raban??o&dat?hik?n&amuk?ihseru?o&du?mok????ust????kilbew,lasrepus,mihe!.&a&m&a&h&ataway?iin??yustam??ij&awu?imak???taki!man???ebot?i&anoh?kasam?rabami??n&ania?egokamuk?oot??o&jias?kihcu?nustam?uhcukokihs?yi!es???u&kohik?zo????n!.&arukas,lapo,n&erukom,riheg,?omomus,stnim,teniesa.resu,xob-liam,yrovi,zapot,?amihs!.&a&d&amah?ho?usam??kustay?m&a?ihsoni&hsin?ko???wakih??e&namihs?ustam??i&g&aka?usay??konikak?mikih??nannu?o&mu&kay?zi!ihsagih?uko???nawust?tasim??u&stog?yamat????nep,?rotsnoihsaf,srev,t&awi!.&a&bahay?d&amay?on??koirom?t&a&honat?katnezukir??imus??w&as&ijuf?uzim??ihs???e&hon&i&hci?n??uk??tawi??i&a&duf?murak?wak??h&custo?si&amak?ukuzihs???j&oboj?uk??k&a&m&anah?uzuk??sagenak??esonihci??m&akatik?uzia&rih?wi????o&kayim?no&rih?t??tanufo??uhso???isarap,saman,tococ,?ulbybab,?g&3zsiu--nx?71qstn--nx?l?olblooc,?h&03pv23--nx?13ynr--nx?22tsiu--nx?61qqle--nx?o-hu,sulb,?i&54urkm--nx?azosbew,ced,g&ayim!.&a&dukak?m&a&goihs?kihs??ihsustam!ihsagih??unawi??r&awago?iho??ta&bihs?rum??w&a&gano?kuruf??iat??y&imot?ukaw???e&mot?nimes??i&hsiorihs?ka&monihsi?s&awak?o???mak?r&ataw?o&muram?tan????o&az?jagat?t&asim?",
+ "omamay???u&fir?k&irnasimanim?uhsakihcihs?????ihcot!.&a&g&a&h?kihsa??ust??kom?m&ay&o?usarak??unak??r&a&boihsusan?watho??iho?ukas??t&akihsin?iay??wa&konimak?zenakat??y&imonustu?oihs???e&iiju?kustomihs?nufawi??i&akihci?g&etom?ihcot?on???o&k&ihsam?kin??nas?sioruk?tab??u&bim?san?????h&c&ia!.&a&dnah?m&a!h&akat?im??yuni??ihs&ibot?ust???r&a&hat?tihs??ik?u&ihsagih?kawi???t&ihc?o&k?yot???wa&koyot?zani??yi&monihci?rak???e&inak?k&aoyot?usa??manokot?noyot??i&a&gusak?kot?sia??eot?h&asairawo?cugo?s&ahoyot?oyim???k&a&mok?zako??ihssi??motay?rogamag??n&an&ikeh?ok??ihssin??o&got?ihsin?jna?rihsnihs?suf?tes??u&bo?raho?s&oyik?takihs??yrihc?zah????ok!.&a&dusay?kadih?mayotom?r&ah&im?usuy??umakan??sot!ihsin??wa&g&atik?odoyin??k&as?o????i&esieg?hco!k??jamu?k&a!sus??usto??ma&gak?k??rahan??o&mukus?n&i?ust!ihsagih???torum?yot!o???u&koknan?zimihsasot????ugamay!.&a&m&ayukot?ihso??toyot??e&bu?subat??i&gah?kesonomihs?nukawi?rakih??nanuhs?otagan?u&ba?foh?otim?stamaduk?uy?????s&anamay!.&a&dihsoyijuf?mayabat?r&ahoneu?ustakihsin??w&a&k&ayah?ijuf??suran??ohs???egusok?i&ak?h&cimakan?s&anamay?od???k&asarin?u&feuf?sto????o&k&akanamay?ihcugawakijuf??nihso?t&asimawakihci?ukoh??uhc??spla-imanim?u&b&nan?onim??fok?hsok?rust????ubon,??ix,ka&rabi!.&a&bukust?gok?kan!ihcatih??m&a&sak?timo?wi??ihsak?ustomihs??ni?r&a&hihcu?way??u&agimusak?ihcust???t&ag&amay?eman??oihcatih??w&ag&arukas?o??os??yi&moihcatih?rom???e&bomot?dirot?not?tadomihs??i&a&k&as?ot??rao??esukihc?gahakat?h&asa?catih??k&a&rabi?saguyr??ihsani?uy??ma?rukustamat??o&dnab?giad?him?kati?rihsijuf?soj?t&asorihs?im??yihcay??u&fius?kihsu?simak????sagan!.&a&m&abo?ihsust??natawak?r&abamihs?u&mo?ustam???wijihc?yahasi??i&akias?hies?k&asagan?i??masah??neznu?o&besas?darih?t&eso?og!imaknihs????ust&igot?onihcuk?uf????zayim!.&a&biihs?guyh?k&oebon?ustorom??mihsuk?r&emihsin?uatik??ta&katik?mim??wag&atik?odak??ya??e&banakat?sakog??i&hsayabok?kaza&kat?yim??m&animawak?ot&inuk?nihs????nanihcin?o&j&ik?onokayim??n&ibe?ust??tias??urahakat????ro&cep,moa!.&a&dawot?turust?wasim??e&hon&ihc&ah?ihs??nas?og?ukor??sario??i&anarih?ganayati?hsioruk?jehon?kasorih?makihsah?nawo?r&amodakan?omoa???o&gnihs?kkat??u&ragust?stum????ttot!.&a&r&ahawak?uotok??sa&kaw?sim???egok?irottot?nanihcin?o&ganoy?nih?tanimiakas??u&bnan?z&ay?ihc??????ukuf!.&a&deki?gurust?ma&bo?h&akat?im??yustak??sakaw??eabas?i&akas?ho?jiehie?ukuf??nezihce!imanim??ono????k&26rtl8--nx?4&3qtr5--nx?ytjd--nx??522tin--nx?797ti4--nx?ci&gid,ht,sevol,?ee,limybab,n&at,upatilol,??l&33ussp--nx?e&ccabew.&resu,sr,?llarap,?lik,oof,rigetuc,?m&11tqqq--nx?41s3c--nx?ef,sioge,?n&30sql1--nx?65zqhe--nx?a&ebyllej,i&lognom,viv,??iam,n7p7qrt0--nx?o&o&las,mflah,?ruk,staw,??o&131rot--nx?7qrbk--nx?aic,c?d&iakkoh!.&a&deki?gakihset?hcebihs?k&adih?u&fib?narihs???m&ayiruk?hot?ihs&orihatik?ukuf??oras?usta??r&ib&a!ka??o?uruf??ozo?u&gakihsagih?oyot???sakim?ta&gikust?mun??w&a&ga&k&an?uf??nus!imak???k&aru?i&h&asa?sagih??kat?mak??omihs?um??zimawi??ine?oyk??yot??e&a&mustam?nan??b&a&kihs?yak??o&noroh?to???ian?k&ihsam?ufoto??nakami?ppoko!ihsin??sotihc?tad!okah??uonikat??i&a&bib?mokamot?n&a&k&kaw?oroh??wi??eomak?ihsatu?okik?usta&moruk?sakan????eib?h&c&ioy?u&bmek?irihs???s&ase?ekka?oknar?uesom???jufirihsir?k&amamihs?i&at?n???m&atik?otoyot??oa&kihs?rihs??r&a&hs?kihsi?mot??ihs&aba?ir??otarib???n&a&hctuk?rorum?se?tokahs??uber??o&kayot?m&ire?ukay??naruf!ima&k?nim???orih?r&ih&ibo?suk??o&bah?h&i&b?hsimak??sa??pnan?yan??umen??t&asoyik?eko?ukoh???u&bassa?kotnihs?m&assaw?uo??pp&akiin?en&ioto?nuk??ip??rato?s&akat?t&eb&e?i&a?hs!a??robon??m&e?o&m?takan???no&h?tamah??o&mik?s?t??u&kir?ppihc?st???onihsnihs?ufuras??uaru??yru!koh??zimihs!ok?????nu,?g!iti,oyh!.&a&bmat?dnas?gusak?k&at?o&oyot?y??uzarakat??m&ayasas?irah??wa&g&ani?okak??k&i&hci?mak??oy???yi&hsa?monihsin???i&asak?hs&aka?i&at?nawak???j&awa!imanim??emih??k&a&goa?s&agama?ukuf??wihsin??i&hsog?m???mati?oia?rogimak??n&annas?esnonihs??o&gasa!kat??ka?n&ikat?o?ustat??rihsay?sihs?tomus?yas??u&bay?gnihs?????hih,konip,l&bs,ik,?mol,nagan!.&a&bukah?d&a&w?yim??e&ki?u??ii??k&a&s&ay?uki??zus??ihsoo?ousay??m&ay&akat?ii??i&hsukufosik?jii??ukihc??n&i!hsetat??uzii??r&ah?ugot??saim?t&agamay?oyim??w&a&g&a&kan?n??o??kustam?ziurak??onim!imanim??u&koo?s!omihs????ya&ko?rih???e&akas?nagamok?subo??i&gakat?h&asa?c&a!mo!nanihs???uonamay??sukagot??k&a&kas?mimanim?to??ia&atik?imanim??oa?uzihcom??m&akawak?ijuf?o!t???r&ato?ijoihs?omakat???n&ana?esnoawazon??o&hukas?n&a&gan?kan??i&hc?muza??ustat??romok?si&gan?k??tomustam??u&k&as?ohukihc??stamega????o&b,m,pac,?to&mamuk!.&a&gamay?rahihsin?sukama!imak??tamanim??enufim?i&hcukik?k&ihsam?u??nugo!imanim??romakat??o&ara?rihsustay?sa?t&amay?om&amuk?us??u!koyg???yohc??u&sagan?zo????yk!.&a&bmatoyk?k&ies?oemak?uzaw??mayi&h&cukuf?sagih??muk??nihsamay?rawatiju?t&away?ik???e&ba&nat!oyk??ya??di?ni??i&ju?kazamayo?manim??natnan?o&gnatoyk?kum?mak?rihsamayimanim?y&gakan?ka&koagan?s??oj???u&ruziam?z&ayim?ik??????wtc1--nx?ykot!.&a&d&i&hcam?mus??oyihc??k&atim?ihsustak??m&a&t!uko??yarumihsa&gih?sum???i&hs&agoa?ika?o!t??uzuok??ren???r&a&honih?wasago??iadok?umah??ssuf?t&ik?o??wa&g&anihs?ode??k&ara?ihcat???y&agates?ubihs???e&amok?donih?m&o?urukihsagih??soyik??i&enagok?gani?h&ca&da?tinuk??sabati??j&nubukok?oihcah??manigus??o&huzim?jihcah?n&akan?ih!sasum??urika??rugem?t&a&mayihsagih?nim??iat?ok??uhc?yknub??u&fohc?hcuf?kujnihs?????p&a&ehc,rc,?o&hs&eht,iiawak,yub,?lf,p&evol,ydnac,?rd&kcab,niar,???r&2xro6--nx?atselttil,e&d&nu,wohc,?h,ilf,pp&ep,irts,u,?t&aerg,tib,??g!r,?ks,o!on,?ufekaf,?s&9nvfe--nx?dom,p&ihc,oo,?remagten,sikhcnerf,u&bloohcs,ruci,srev,?xvp4--nx??t&a&cyssup,obgip,?e&rces,vlev,?hginyad,netnocresu,opsgolb,sidas,u&b,ollihc,??u&4rvp8--nx?fig!.&a&d&eki?ih??kimot?m&ayakat?ihsah??ne?raha&gi&kes?makak??sak??taga&may?tik??wa&g&ibi?ustakan??karihs!ihsagih????e&katim?uawak??i&gohakas?hc&apna?uonaw??k&ago?es?ot??m&anuzim?ijat??nak?urat??nanig?o&dog?jug?makonim?nim?roy?sihcih??u&fig?s&otom?t&amasak?oay??????hc,pup,stoknot,ynup,?wonsetihw,x&5ytlk--nx?irtam,?y&adynnus,dr,knarc,l&oh,rig,?moolg,ob,pp&ih,olf,?rgn&a,uh,?u6d27srjd--nx?vaeh,?z&72thr--nx?e&ej,lur,??井福?京東?分大?取鳥?口山?城&宮?茨??媛愛?山&富?岡?歌和??岡&福?静??島&児鹿?広?徳?福??崎&宮?長??川&奈神?石?香??庫兵?形山?手岩?木栃?本熊?根島?梨山?森青?潟新?玉埼?田秋?知&愛?高??縄沖?良奈?葉千?賀&佐?滋??道海北?都京?重三?野長?阜岐?阪大?馬群???k!.&art?gro?moc?per?ude?vog???l&eh?l??m!.uj,ac?j??nd?o&g?h&pih?s!.&esab,xilpoh,ysrab,???lnud?oc?t!.&lldtn,snd-won,???pa!.&0mroftalp,a&rusah,ted,?bew:erif,,e&erf-korgn,gatskrelc,kalfwons:.kniletavirp,,niln&igol,okoob,?tupmocegde,virdhsalfno,?ilressem,k&orgn,relc,?le&crev,napysae,?maerdepyt,n&aecolatigidno,ur:.a,,?poon,r&cne,emarf,?t&i&belet,lmaerts,?xenw,?yfilten,??ra&a?hs??u&ekam?llag?org!.esruocsid,cts?kouk?nayalo???vsr?xece4ibgm--nx??q&a!3a9y--nx??g?i!.&gro?lim?moc?ten?ude?vog???m?se??r&a!.&a&cisum?sanes??bog?gro?l&autum?im??moc!.topsgolb,?pooc?rut?t&e&b?n??ni??ude?vog??4d5a4prebgm--nx?b?c?eydoog?los?t&at?s!uen???ugaj??b!.&21g?a&b&a&coros?iuc??itiruc??cnogoas?dicerapa?gniram?i&naiog?ramatnas??n&erom?irdnol??op?p&acam?irolf?ma&j?s???rief?tsivaob??b!aj?ib?mi?sb??c&ba?e&r?t??js?sp?t!e???d&em?mb?n&f?i??rt??e&dnarganipmac?ficer?ht?llivnioj?rdnaotnas??f&dj?ed?gg?n&e?i???g&e&l!.&a&b,m,p,?bp,c&a,s,?e&c,p,s,?fd,gm,ip,jr,la,ma,nr,o&g,r,t,?p&a,s,?r&p,r,?s&e,m,r,?tm,??s??l&s?z??n&c?e?o??ol!b?f?v??pp?ro??hvp?i&du?kiw?nana?oretin?r&c?eurab??sp?te?xat??l&at&an?rof??el?im?sq??m&a?da?e&gatnoc?leb??f?ic?oc!.&duolclautriv.elacs.sresu,etiselpmis,topsgolb,???nce?o&ariebir?c&e?narboir?saso??d&o?ranreboas??e&g?t??i&b?dar?ecam?r??rp?t&a?erpoir???p&er?m!e?t??ooc?pa?se??qra?r&af?ga?o&davlas?j??tn?ut??s&a&ixac?mlap?nipmac??ed?u&anam?j?m???t&am?e&d?n?v??nc?o&f?n??ra?sf??u&caug9?de?ja?rg??v&da?ed?og!.&a&b?m?p??bp?c&a?s??e&c?p?s??fd?gm?ip?jr?la?ma?nr?o&g?r?t??p&a?s??r&p?r??s&e?m?r??tm???rs?t??xiv?z&hb?ls?o&c?f?????c!.&as?ca?de?if?o&c?g??ro???e&bew?ccos?dnik?e&b?n&igne?oip??rac??gni&arg?rheob??h&cor?sok?t&aew?orb???itnorf?k&col?o&p?rb???l&aed?ffeahcs??mal?nes?pinuj?t&a&eht?rebsnegömrev??law?nec?s&acnal?nom?ubkcolb??upmoc??v&o&csid?rdnal??resbo??wulksretlow?ywal?zifp??f!.&aterg?bew&-no,etis321,?drp?e&c&itsuj-reissiuh?narf-ne-setsitned-sneigrurihc,?lipuog,rianiretev??hny,i&cc?rgabmahc??m&o&c?n??t??n&eicamrahp?icedem??ossa?pohsdaerpsym,s&e&lbatpmoc-strepxe?riaton?tsitned-sneigrurihc?uova??o&-x&bf,obeerf,?x&bf,obeerf,???t&acova?o&or-ne,psgolb,?r&epxe-ertemoeg?op!orea????vuog?xobided,?avc7ylqbgm--nx?s??g!.&etiselpmis,gro?moc?t&en?opsgolb,?ude?vog???h!.&e&erf,man??mo&c?rf??topsgolb,zi??ur??i!.&a&61f4a3abgm--nx?rf4a3abgm--nx??ca?di?gro?hcs?oc?ten?vog?نار&يا?یا???a&h?per??ew?lf??k!.&c&a?s??e&n?p?r??gk?iggnoeyg?kub&gn&oeyg?uhc??noej??l&im?uoes??man&gn&oeyg?uhc??noej??n&as&lu?ub??o&e&hcni?jead??wgnag???o&c?g??ro?s&e?h?m??topsgolb,u&gead?j&ej?gnawg????cilf??l!.&gro?moc?ten?ude?vog???m!.&topsgolb,vog???n!.&gro?moc?ofni?ten?ude?vog?zib???o&htua?odtnorf?t&c&a?od??laer???p!.&alsi?ca?eman?forp?gro?moc?o&fni?rp??t&en?se??ude?vog?zib???s?t!.&21k?bew?cn!.vog??eman?gro?kst?l&e&b?t??im?op??moc!.topsgolb,?neg?ofni?pek?rd?sbb?ten?ude?v&a?og?t??zib??f?m??ubad?vd??s&8sqif--nx?9zqif--nx?a!.vog?birappnb?gev?lliv?mtsirhc?s??b!.&ew,gro?moc?ten?ude?vog??c?oj?s?u??c&i&hparg?p?t&sigolyrrek?ylana???od??d&a?d?ik?l?n&iwriaf?omaid??oogemoh?rac??e!.&b&ewim321,og??gro?mo&c!.topsgolb,?n??pohsdaerpsym,ude??civres!.enilnigol,?d&d2bgm--nx?oc??h&ctaw?guh??i&lppus?rtsudni?treporp!yrrek???jaiv?l&aw?cycrotom?gnis?pats??m&ag?oh?reh??nut?ohs?picer?r&it?ut&cip!.7331,?nev???s&i&rpretne?urc??ruoc??taicossa?vig??g!nidloh??h5c822qif--nx?i!.&ekacpuc,gro?moc?t&en?ni?opsgolb,?ude?vog??a09--nx?nnet?rap?targ??k&c&or!.&ecapsbew,snddym,ytic-amil,??us??hxda08--nx?row??l!.&c&a?s??ed,gro?o&c?fni??ten?ude?vog?zib??a&ed?tner??e&ssurb?toh!yrrek???lahsram?m?oot??m!.&bal,etisinim,gro?moc?ten?ude?vog??b?etsys!.tniopthgink,?ialc??n&a&f?gorf?ol??i&a&grab?mod??giro??o&it&acav?cudorp?ulos??puoc???o&dnoc?geuj?ppaz?t&ohp!.remarf,?ua???p!.&ces?gro?moc?olp?ten?ude?vog??i&hsralohcs?lihp?t??u??r!.&au,ca?gro?ni?oc?topsgolb,ude?vog?xo,yldnerb.pohs,?a&c?p?tiug??c?e&dliub!.etisduolc,?erac?gor?levart?mraf?n&niw?trap??wolf??ot&cartnoc?omatat??pj?uot??s!.&em?gro?hcs?moc?ten?ude?vog?zib??alg?e&n&isub",
+ "!.oc,?tif??rp!xe!nacirema???xnal??iws??t&a&e&b?ytic??ob??ek&cit?ram??fig?h&cay?gilf??n&atnuocca?e&mt&rapa?sevni??ve!.&nibook,oc,????rap??u!.&a&c!.&21k?bil?cc???g!.&21k?bil?cc???i!.&21k?bil?cc???l!.&21k?bil?cc???m!.&21k!.&hcorap?rthc?tvp???bil?cc???p!.&21k?bil?cc???si?v!.&21k?bil?cc???w!.&21k?bil?cc????c&d!.&21k?bil?cc???n!.&21k?bil?cc???s!.&21k?bil?cc????d&e&f?lacsne.xhp,?i!.&21k?bil?cc???m!.&21k?bil?cc???n!.&bil?cc???s!.&bil?cc???u&olcrim,rd,??e&d!.&21k?bil,cc???las-4-&dnal,ffuts,?m!.&21k?bil?cc???n!.&21k?bil?cc????h&n!.&21k?bil?cc???o!.&21k?bil?cc????i&h!.&bil?cc???m!.&21k?bil?c&c?et??goc?n&eg?otae??robra-nna?sum?tsd?wanethsaw???nd?r!.&bil?cc???v!.&21k?bil?cc???w!.&21k?bil?cc????jn!.&21k?bil?cc???k&a!.&21k?bil?cc???o!.&21k?bil?cc????l&a!.&21k?bil?cc???f!.&21k?bil?cc???i!.&21k?bil?cc????mn!.&21k?bil?cc???n&afflog,i!.&21k?bil?cc???m!.&21k?bil?cc???sn?t!.&21k?bil?cc????o&c!.&21k?bil?cc???m!.&21k?bil?cc???ttniop,?p&ion,rettalp,?r&a!.&21k?bil?cc???o!.&21k?bil?cc???p!.&21k?bil?cc????s&a!.&21k?bil?cc???dik?k!.&21k?bil?cc???m!.&21k?bil?cc???nd&deerf,uolc,??t&c!.&21k?bil?cc???m!.&21k?bil?cc???u!.&21k?bil?cc???v!.&21k?bil?cc????ug!.&21k?bil?cc???v&n!.&21k?bil?cc???w!.cc???x&ohparg,t!.&21k?bil?cc????y&b-si,k!.&21k?bil?cc???n!.&21k?bil?cc???w!.&21k?bil?cc????za!.&21k?bil?cc????ah!uab??bria?col?e!.ytrap.resu,?ineserf?lp?xe&l?n???vt?w!.&66duolc,gro?moc?s&ndnyd,tepym,?ten?ude?vog??a?e&iver?n!.elbaeciton,??odniw??y&alcrab?ot???t&0srzc--nx?a!.&amil4,ca!.hts??etiesbew321,gni&liamerutuf,tsoherutuf,?o&c!.topsgolb,?fni,?p&h21,ohsdaerpsym,?r&euefknuf.neiw,o??v&g?irp,?xi2,ytic-amil,zib,?c?e!s??hc?l!asite??mami?rcomed??b!.&gro?moc?ten?ude?vog??b?gl??c&atnoc?e&les?rid!txen????dimhcs?e!.&eman?gro?moc?ofni?ten?ude?vog?zib??b?em?grat?id?k&circ?ram??n!.&0rab,1rab,2rab,5inu,6vnyd,7&7ndc.r,erauqs,?a&l&-morf,moob,?minifed,remacytirucesym,tadsyawla,z,?b&boi,g,lyltsaf:.pam,,?c&i&nagro-gnitae,tats-oieboda,?paidemym,?d&e&calpb,ziamaka,?hiamaka,irgevissam.saap.&1-&gs,nol,rf,yn,?2-&nol,yn,??nab-eht-ni,uolc&meaeboda,nievas.c&di-etsedron,itsalej,?xednay:.e&garots,tisbew,?,??e&c&narusnihtlaehezitavirp,rofelacs.j,?gd&eiamaka,irbtib,?ht-no-eciffo,l&acs&liat.ateb,noom,?ibom-eruza,?m&ecnuob,itnuroieboda,ohtanyd,tcerider,?n&ilno-evreser,ozdop,?rehurht,s:abapus,,ti&s-repparcs,usegde,?zam&aym,kcar,??f&aeletis,crs.&cos,resu,?ehc-a-si,?g&ni&gats-&d&eziamaka,hiamaka,?e&gdeiamaka,tiusegde,?iamaka,nigiroiamaka,yekegde,?reesnes,sirkcilc,tsohnnylf,?olbevres,?iamaka,k&catsvano,eeg-a&-si,si,?u,?l&acolottad,iamwt,meteh,s&d-ni,s-77ndc,??m&ac&asac,ih,?urofniem,?n&a&f&agp,lhn,?i&bed,llerk,??dcduabkcalb,i:giroiamaka,,pv-ni,?o&c-morf,duppa,jodsnd,rp-ytinummoc,ttadym,?p&i&-&etsef,on,?emoh,fles,nwo,?j,mac-dnab-ta,o&-oidar-mah,h&bew,sdaerpsym,??pa&duolc,egde,?tfe&moh,vres,?usnd,?r&e&tsulcyduolc,vres-xnk,?vdslennahc:.u,,?s&a&ila&nyd,snd,?nymsd,?bbevres,dylimaf,e&gde-ndc,rauqs,suohsyub,t&isbeweruza,ys,??k&catstsaf,ekokohcs,?n&d&-won,aka,d,golb,npv,?oitcnufduolc,?ppacitatseruza:.&1,2:suts&ae,ew,?,3,aisatsae,eporuetsew,sulartnec,?,s&a-skcik,ecca&-citats,duolc,??t,?t&adies,ce&ffeym,jorprot:.segap,,lespohs,?e&nretnifodne,smem,?farcenimevres,i-&ekorb,s&eod,lles,teg,??n&essidym,orfduolc,?r0p3l3t,s&ixetnod,oh&-spv:.citsalej.&cir,lta,sjn,?,gnik,???u&h,nyd,r:eakust.citsalej,,?ved-naissalta.dorp.ndc,x&inuemoh,spym,tsale.&1ots-slj,2ots-slj,3ots-slj,?unilemoh,?y&awetag-llawerif,ekegde,ffijduolc:.&ed-1arf,su-1tsew,?,ltsaf.&dorp.&a,labolg,?lss.&a,b,labolg,?pam,slteerf,?n&-morf,ofipi,?srab,?z&a-morf,tirfym,???p?tcip?v??f&ig?osorcim??g!.&bog?dni?ed,g&olb,ro??lim?moc?ot,ten?ude???h!.&dem?gro?l&er?op??m&oc?rif??o&fni?rp?s&rep?sa???po&hs?oc??t&en?luda?ra??ude?vuog???i!.&a&2n-loritds--nx?7e-etsoaellav--nx?8&c-aneseclrof--nx?i-lrofanesec--nx??at?b?c!cul??dv?i&blo&-oipmet?oipmet??cserb?drabmol?g&gof?urep??l&gup?i&cis?me&-oigger?oigger???uig&-&aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf???aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf????n&a&brev?cul?pmac?tac??idras?obrac&-saiselgi?saiselgi??resi??otsip?r&b&alac!-oigger?oigger??mu??dna&-&attelrab-inart?inart-attelrab??attelrabinart?inartattelrab?ssela??epmi?ugil??tnelav&-obiv?obiv??vap?z&e&nev?ps&-al?al???irog???l&iuqa!l??leib??m&or?rap??n!acsot?e&dom?is?sec&-&ilrof?ìlrof??ilrof?ìlrof???g&amor&-ailime?ailime??edras?olob??i&ssem?tal??ne!var??o&cna?merc?rev?vas???oneg?p?r!a&csep?rr&ac&-assam?assam??ef??von??etam?tsailgo!-lled?lled???s!ip?sam&-ararrac?ararrac??u&caris?gar???t!a&cilisab?recam??resac?soa!-&d&-&ellav?lav??ellav?lav??ellav??d&-&ellav?lav??ellav?lav??ellav??te&lrab&-&airdna-inart?inart-airdna??airdnainart?inartairdna??ssinatlac???udap?v!o&dap?neg?tnam???zn&airb&-a&lled-e-aznom?znom??a&lledeaznom?znom??eaznom??e&c&aip?iv??soc?top??om???b&-&23,46,61,?3c-lorit-ds-onitnert--nx?be-etsoa&-ellav--nx?dellav--nx??c!f-anesec-lrof--nx?m-lrof-anesec--nx??he-etsoa-d-ellav--nx?m!u??o2-loritds-nezob--nx?sn-loritds&-nasl&ab--nx?ub--nx??nitnert--nx??v!6-lorit-dsnitnert--nx?7-loritds&-nitnert--nx?onitnert--nx???z&r-lorit-ds&-nitnert--nx?onitnert--nx??s-loritds-onitnert--nx???c&f?is?l?m?p?r?v??d&p?u!olcnys,??e&c!cel?inev?nerolf??f?g!apemoh321,ida&-&a&-onitnert?onitnert??otla!-onitnert?onitnert???a&-onitnert?onitnert??otla!-on&azlob?itnert??onitnert????hcram?l?m!or??n&idu?o&n&edrop?isorf??torc???p?r?s&erav?ilom??t!nomeip?s&eirt?oa!-&d-e&ellav?éllav??e&ellav?éllav???de&ellav?éllav??e&ellav?éllav?????v?znerif??g&a?b?f?il?o?p?r?up?vf??hc?i&b?c?dol?f?l!lecrev?opan?rof&-anesec?anesec???m?n&a&part?rt&-attelrab-airdna?attelrabairdna???imir?ret??p?r!a&b?ilgac?ssas???s!idnirb??t&ei&hc?r??sa??v??l&a!c??b?c?o&m?rit&-&d&eus&-&nitnert?onitnert??nitnert?onitnert??us&-&nitnert?onitnert??nitnert?onitnert??üs&-&nitnert?onitnert??nitnert?onitnert???s&-onitnert?onitnert???d&eus!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??us&-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??üs!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert???s&-onitnert?onitnert?????m&ac?f?i!t.nepo.citsalej.duolc,?ol?r??n&a!lim?sl&ab?ub???b?c?e!en.cj,v?zob??irut?m!p??p?r?t??o&a!v??b!retiv??c!cel??enuc?g!ivor??i&dem&-onadipmac?onadipmac??pmet&-aiblo?aiblo??rdnos?zal??l?m!a&greb?ret??oc?re&f?lap???n!a&dipmac&-oidem?oidem??lim?tsiro?zlob??ecip&-ilocsa?ilocsa??i&bru&-orasep?orasep??lleva?rot?tnert??r&elas?ovil??ulleb??p?r!a&sep&-onibru?onibru??znatac??oun??s!ivert?sabopmac??t!arp?e&nev?ssorg??n&arat?e&girga?rt?veneb????zz&era?urba???p&a?ohsdaerpsym,s?t??qa?r&a!m?s??b!a??c?f?g?k?me?o?p?s?t?v??s&a&b?iselgi&-ainobrac?ainobrac???b?c?elpan?i?m?o&t?x&bi,obdaili,??s?t?v??t&a?b?c?l?m?nomdeip?o!psgolb,?p?v??u&de?l?n?p??v&a?og?p?s?t?v??y&drabmol?ellav&-atsoa?atsoa??licis?nacsut??z&al?b?c?p??ìlrof&-anesec?anesec???derc?er?f?m?utni??je3a3abgm--nx?kh?l!.&topsgolb,vog??uda??m!.&gro?moc!.topsgolb,?ten?ude???n&a&morockivdnas?ruatser?tnuocca??e&g?m&eganam!.retuor,?piuqe??r??i!.ue?m?opdlog??opud?uocsid??o&b?cs!.&ude,vog:.ecivres,,??d?g?h?j?oferab?p&edemoh?s???p!.&bewanigap321,emon?gro?lbup?moc?t&en?ni?opsgolb,?ude?vog???r&a!m&law?s???epxe?op&er?pus!.ysrab,?s???s!.&a&daxiabme?rarik,?e&motoas?picnirp?rots??gro?lim?moc?o&c?dalusnoc?hon,?ten?ude??a&cmoc?f??e&b?r?uq??i!rolf?tned??o&h!.&duolc&p,rim,?e&lej,tiseerf,?flah,l&enapysae,rupmet,?s&pvtsaf,seccaduolc,?tsafym,vedumpw,??p!sua???urt??t!.&eman?gro?ibom?levart?m&oc?uesum??o&c?fni?r&ea?p???pooc?sboj?t&en?ni??ude?vog?zib??ayh?n?o!bba?irram???uognah?xen?y!.gro,?ztej??u&2&5te9--nx?yssp--nx??a!.&a&s?w??civ?d&i?lq??fnoc?gro?moc!.&pohsdaerpsym,stelduolc.lem,topsgolb,??nsa?ofni?sat?t&ca?en?n??ude!.&a&s?w??ci&lohtac?v??dlq?sat?t&ca?n??wsn!.sloohcs????vog!.&a&s?w??civ?dlq?sat???wsn?zo??ti??c!.&fni?gro?moc?ten?ude?vog??i??d&e!.tir.segap-tig,?iab??e!.&dcym,enozgniebllew,noitatsksid,odagod.citsalej,s&nd&ps,uolc,?ppatikria,?ysrab,??g!.&bew?gro?m&aug?oc??ofni?ten?ude?vog???h!.&0002?a&citore?idem?kitore??edszot?gro?ilus?letoh?m&alker?lif?t?urof??naltagni?o&c?ediv?fni?levynok?nisac??pohs?rarga?s&a&kal?zatu??emag?wen??t&lob?opsgolb,rops??virp?xe&s?zs??ytic?zsagoj??os?sut??l!.&etisbew321,topsgolb,??m!.&ca?gro?moc?oc?ro?ten?vog???n!.&duolcesirpretne,eni&esrem,m,?tenkcahs,?em!.ysrab,??o&ggnaw?y!c???r!.&3kl,a&i&kymlak,rikhsab,vodrom,?yegyda,?bps,ca,duolcrim,e&niram,rpcm,?g&bc,nitsohurger.citsalej,ro,?ianatsuk,k&ihclan,s&m,rogitayp,??li&amdlc.bh,m,?moc,natsegad,onijym,pp,ri&b,d&cm:.spv,,orue,?midalv,?s&ar,itym,?t&en,ias321,ni,opsgolb,set,?u&4an,de,?vo&g,n,?ynzorg,zakvakidalv,?myc?p?ug??s!.&a&d&golov,nagarak,?gulak,i&groeg,kymlak,lerak,nemra,rikhsab,ssakahk,vodrom,zahkba,?lut,rahkub,vut,yegyda,znep,?bps,da&baghsa,rgonilest,?gunel,i&anatsuk,hcos,ovan,ttailgot,?k&alhsygnam,ihclan,s&legnahkra,m,n&a&mrum,yrb,?i&buytka,nbo,??tiort,vorkop,??l&ocarak,ybmaj,?na&gruk,jiabreza,ts&egad,hkazak-&htron,tsae,???ovonavi,r&adonsark,imidalv,?t&enxe,nek&hsat,mihc,??vo&hsalab,n,?ynzorg,z&akvakidalv,emret,??t&amok?i&juf?masih????v!.&em,g&olb,ro??moc?nc,ten?ude?ved,??ykuyr??v&b?c!.&emon?gro?moc?t&ni?opsgolb,?ude???ed!.&2r,ated,e&docotua,erf-korgn,nilnigol,?gnigats-oned,hcetaidem,korgn,lecrev,o&ned,tpyrctfihs,?ppa-rettalp,s&egap,rekrow,?vr&esi,uc,?weiverpbuhtig,ylf,??ih?l!.&di?fnoc?gro?lim?moc?nsa?ten?ude?vog???m!.&eman?gro?lim?m&oc?uesum??o&fni?r&ea?p???pooc?t&en?ni??ude?vog?zib???o&g?m??rt?s!.&bog?der?gro?moc?ude???t!.&arukas,bew-eht-no,morf,naht-&esrow,retteb,?sndnyd,?d?i?won??uqhv--nx??w&a!.moc?hs?l??b!.&gro?oc???c!.&gro?moc?ten?ude??cp??e&iver!.oby,?n?s??g?k!.&bme?dni?gro?moc?ten?ude?vog???m!.&ca?gro?m&oc?uesum??oc?pooc?t&en?ni??ude?vog?zib??b??o&csom?h!s??n?w??p!.&344x,de?en?o&c?g??ro?snduolc,ualeb???r!.&ca?gro?lim?oc?pooc?ten?vog??n??t!.&a46oa0fz--nx?b&82wrzc--nx?ulc??emag?gro?l&im?ru,?moc!.reliamym,?t&en?opsgolb,?ude?v&di?og?ta0cu--nx??zibe?業商?織組?路網???z!.&ca?gro?lim?oc?vog????x&a!.&cm,eb,gg,s&e,u,?tac,ue,yx,?t??c!.&hta,ofni,vog???e&d&ef?nay??ma!nab??rof?s??ilften?jt?m!.&bog?gro?moc?t&en?opsgolb,?ude??g?ma2ibgy--nx??o&b!x??f?rex??rbgn--nx?s!.vog??x&am&jt?kt??x???y&4punu--nx?7rr03--nx?a&d!i&loh?rfkcalb??ot!.emyfilauqerp,??g?lp?p!ila??rot?ssin?wdaorb??b!.&duolcym,fo?hcetai",
+ "dem,lim?moc!.topsgolb,?vog??ab?gur??c!.&ca?dtl?gro?lim?m&oc!.&ecrofelacs.j,topsgolb,??t??orp?s&egolke?serp??ten?vog?zib??amrahp?nega??d&dadog?uts??e&kcoh?ltneb?n&dys?om?rotta??snikcm??g!.&eb,gro?moc?oc?ten?ude?vog??olonhcet!.oc,?rene??hpargotohp?id?k!.&gro?moc?ten?ude??s??l!.&clp?d&em?i??gro?hcs?moc?ten?ude?vog??f?imaf!nacirema??l&a?il??ppus??m!.&eman?gro?lim?moc?t&en?opsgolb,?ude?vog?zib??edaca!.laiciffo,?ra??n&a&ffit?pmoc??os??o&j?s??p!.&gro?lim?moc?pooc?ten?ude?vog???r&e&corg?grus?llag?viled??lewej?otcerid?tnuoc?uxul??s!.&gro?lim?moc?ten?ude?vog??pil??t&efas?i&c?ledif?n&ifx?ummoc!.&bdnevar,gon,murofym,???r&ahc?uces??srevinu??laer?r&ap!.oby,?eporp??uaeb??u!.&bug?gro?lim?moc!.topsgolb,?ten?ude??b!tseb???van!dlo??xes??z&a!.&eman?gro?lim?moc?o&fni?rp??pp?t&en?ni??ude?vog?zib???b!.&az,gro?jsg,moc?ten?ude?vog???c!.&4e,inum.duolc.&rsu,tlf,?m&laer,urtnecatem.motsuc,?oc,topsgolb,??d!.&cos?gro?lop?m&oc?t??ossa?t&en?ra??ude?vog???ib!.&duolcsd,e&ht-rof,mos-rof,rom-rof,?izoj,liartevitca,nafamm,p&i&-on,fles,?ohbew,tfym,?retteb-rof,snd&nyd,uolc,?xro,?g??k!.&duolcj,gro?lim?moc?t&en?ropeletzak.saapu,?ude?vog???m!.&ca?gro?lim?oc?ten?ude?v&da?og????n!.&asq-irom--nx?ca?gro?htlaeh?i&r&c?o&am?ām???wi!k???keeg?l&im?oohcs??neg?oc!.topsgolb,?t&en?nemailrap?vog???a!niflla???rawhcs?s!.&ca?gro?oc???t!.&c&a?s??e&m?n??ibom?l&etoh?im??o&c?fni?g??ro?vt???u!.&gro?moc?oc?ten??rwon??yx!.&e&nozlacol,tisgolb,?gnitfarc,otpaz,??zub??λε?υε?авксом?брс!.&гро?до?ка?р&бо?п!у?????г&б?ро??дкм?зақ?итед?килотак?леб?мок?н&йално?ом??рку?сур!.&арамас,бпс,гро,зиб,ичос,ксм,м&ок,ырк,?рим,я,??тйас?фр?юе?յահ?לארשי!.&בושי?הימדקא?ל&הצ?שממ????םוק?اي&روس?سيلم?ناتيروم??بر&ع?غملا??ة&كبش?ي&دوعسلا?روس??یدوعسلا??ت&ا&راما?لاصتا??را&ب?ڀ?ھب???ر&ئازجلا?ازاب?صم?طق??سنوت?عقوم?قارع?ك&تيب?يلوثاك??موك?ن&ا&تس&كاپ?کاپ??دوس?ر&يا?یا??مع?يلعلا??درالا?ميلا?ي&رحبلا?طسلف???ه&ارمه?يدوعسلا??وكمارا?يبظوبا?ۃیدوعسلا?टेन?त&राभ?ोराभ??नठगंस?मॉक?्मतराभ?ত&রাভ?ৰাভ??ালংাব?ਤਰਾਭ?તરાભ?ତରାଭ?ாயித்நஇ?ைக்ஙலஇ?்ரூப்பக்ஙிச?్తరాభ?ತರಾಭ?ംതരാഭ?ාකංල?มอค?ยทไ!.&จิกรุธ?ต็นเ?ร&ก์คงอ?าหท??ลาบฐัร?าษกึศ???ວາລ?ეგ?なんみ?アトス?トンイポ?ドウラク?ムコ?ル&グーグ?ーセ??ン&ゾマア?ョシッァフ??业企?东广?乐娱?你爱我?信中?务政?动移?博微?卦八?厅餐?司公?品食?善慈?团集?国中?國中?址网?坡加新?城商?尚时?山佛?店&商?网?酒大里嘉??府政?康健?息信?戏游?拉里格香?拿大?教主天?机手?构机!织组??标商?歌谷?浦利飞?港香!.&人個?司公?府政?絡網?織組?育教???湾台?灣&台?臺??物购?界世?益公?看点?科盈訊電?站网?籍書?线在?络网?网文中?聘招?販通?逊马亚?通联?里嘉?锡马淡?門澳?门澳?闻新?電家?국한?넷닷?성삼?컴닷??");
/**
* If a hostname is not a key in the EXCLUDE map, and if removing its leftmost component results
@@ -50,7 +56,7 @@ public final class PublicSuffixPatterns {
*/
public static final ImmutableMap<String, PublicSuffixType> UNDER =
TrieParser.parseTrie(
- "ac.vedwa,d&b?i.ym.ssr,uolc.&etiso&isnes,tnegam,?iaznab,rehcnar-no,scitats,??e&b.lrusnart,d.&ecapsrebu,yksurf,?noz.notirt,t&atse.etupmoc,is.&areduolc,hsmroftalp,tst,???g&oog.tnetnocresu,p??h&c.tenerif:.cvs,,k?trae.sppad:.zzb,,?k&c?f?nil.bewd,rowten.secla,u.hcs??ln.lrusnart,m&j?m?oc.&duolcmeaeboda.ved,edonil.recnalabedon,ico-remotsuc:.&ico,pco,sco,?,lrihwyap,mme0,osseccandcved,s&ecapsnaecolatigid,t&cejbo&edonil,rtluv,?nemelepiuq,?wanozama.&1-etupmoc,ble,etupmoc,??t&neyoj.snc,opsppa.r,???n&c.moc.swanozama.&ble,etupmoc,?ur.edoc,?o&c.pato,i.&duolciaznab.sdraykcab,elacsnoom,oir-no,reniatnoceruza,s&3k-no,olots,?xcq.sys,y5s,??p&j.&a&mahokoy?yogan??ebok?i&adnes?kasawak??oroppas?uhsuykatik??n?pa.&knalfhtron,repoleved,tegeb,??r&b.mon?e??s&edoc.owo,noitulos.rehid,w.rosivda,?t&a.&ofnistro.&nednuk,xe,?smcerutuf:.&ni,xe,?,?en.&cimonotpyrc,hvo.&gnitsoh,saapbew,???u&e.lrusnart,r.onijym.&gni&dnal,tsoh,?murtceps,spv,??ved.&e&gats&gts,lcl,?rahbew,?gts,lcl,yawetag,?z&c.murtnecatem.duolc,yx.tibelet,??");
+ "ac.vedwa,d&b?i.ym.ssr,uolc.&etiso&isnes,tnegam,?iaznab,rehcnar-no,scitats,??e&b.lrusnart,d.&ecapsrebu,yksurf,?noz.notirt,t&atse.etupmoc,is.&areduolc,hsmroftalp,tst,???g&oog.tnetnocresu,p??h&c.tenerif:.cvs,,k?trae.sppad:.zzb,,?k&c?f?nil.bewd,rowten.secla,u.hcs??ln.lrusnart,m&f.resu,j?m?oc.&duolcmeaeboda.ved,edo&c.redliub:-&gts,ved,?,nil.recnalabedon,?ico-remotsuc:.&ico,pco,sco,?,lrihwyap,mme0,osseccandcved,s&ecapsnaecolatigid,t&cejbo&edonil,rtluv,?nemelepiuq,?wanozama.&1-etupmoc,ble,etupmoc,??t&neyoj.snc,opsppa.r,???n&c.moc.swanozama.&ble,etupmoc,?ur.&dliub,e&doc,sabatad,?noitargim,??o&c.pato,i.&duolciaznab.sdraykcab,elacsnoom,nroca-no,oir-no,reniatnoceruza,s&3k-no,olots,?xcq.sys,y5s,??p&j.&a&mahokoy?yogan??ebok?i&adnes?kasawak??oroppas?uhsuykatik??n?pa.&knalfhtron,repoleved,tegeb,??r&b.mon?e??s&edoc.owo,noitulos.rehid,w.rosivda,?t&a.&ofnistro.&nednuk,xe,?smcerutuf:.&ni,xe,?,?en.&cimonotpyrc,hvo.&gnitsoh,saapbew,???u&e.lrusnart,r.onijym.&gni&dnal,tsoh,?murtceps,spv,??ved.&e&gats&gts,lcl,?rahbew,?gts,lcl,treclacol.resu,yawetag,?z&c.murtnecatem.duolc,yx.tibelet,??");
/**
* The elements in this map would pass the UNDER test, but are known not to be public suffixes and
diff --git a/android/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java b/android/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
index 89cdadd3d..82bf8b3c1 100644
--- a/android/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
+++ b/android/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
@@ -14,28 +14,40 @@
package com.google.thirdparty.publicsuffix;
+import static com.google.common.collect.Queues.newArrayDeque;
+
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Queues;
import java.util.Deque;
/** Parser for a map of reversed domain names stored as a serialized radix tree. */
@GwtCompatible
final class TrieParser {
- private static final Joiner PREFIX_JOINER = Joiner.on("");
+
+ private static final Joiner DIRECT_JOINER = Joiner.on("");
/**
* Parses a serialized trie representation of a map of reversed public suffixes into an immutable
- * map of public suffixes.
+ * map of public suffixes. The encoded trie string may be broken into multiple chunks to avoid the
+ * 64k limit on string literal size. In-memory strings can be much larger (2G).
*/
- static ImmutableMap<String, PublicSuffixType> parseTrie(CharSequence encoded) {
+ static ImmutableMap<String, PublicSuffixType> parseTrie(CharSequence... encodedChunks) {
+ String encoded = DIRECT_JOINER.join(encodedChunks);
+ return parseFullString(encoded);
+ }
+
+ @VisibleForTesting
+ static ImmutableMap<String, PublicSuffixType> parseFullString(String encoded) {
ImmutableMap.Builder<String, PublicSuffixType> builder = ImmutableMap.builder();
int encodedLen = encoded.length();
int idx = 0;
+
while (idx < encodedLen) {
- idx += doParseTrieToBuilder(Queues.<CharSequence>newArrayDeque(), encoded, idx, builder);
+ idx += doParseTrieToBuilder(newArrayDeque(), encoded, idx, builder);
}
+
return builder.buildOrThrow();
}
@@ -59,9 +71,10 @@ final class TrieParser {
int idx = start;
char c = '\0';
- // Read all of the characters for this node.
+ // Read all the characters for this node.
for (; idx < encodedLen; idx++) {
c = encoded.charAt(idx);
+
if (c == '&' || c == '?' || c == '!' || c == ':' || c == ',') {
break;
}
@@ -74,17 +87,20 @@ final class TrieParser {
// '?' represents a leaf node, which represents a REGISTRY entry in map.
// ':' represents an interior node that represents a private entry in the map
// ',' represents a leaf node, which represents a private entry in the map.
- String domain = PREFIX_JOINER.join(stack);
+ String domain = DIRECT_JOINER.join(stack);
+
if (domain.length() > 0) {
builder.put(domain, PublicSuffixType.fromCode(c));
}
}
+
idx++;
if (c != '?' && c != ',') {
while (idx < encodedLen) {
// Read all the children
idx += doParseTrieToBuilder(stack, encoded, idx, builder);
+
if (encoded.charAt(idx) == '?' || encoded.charAt(idx) == ',') {
// An extra '?' or ',' after a child node indicates the end of all children of this node.
idx++;
@@ -92,6 +108,7 @@ final class TrieParser {
}
}
}
+
stack.pop();
return idx - start;
}
diff --git a/android/pom.xml b/android/pom.xml
index 3784c9f12..d99f05992 100644
--- a/android/pom.xml
+++ b/android/pom.xml
@@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-android</version>
+ <version>32.1.2-android</version>
<packaging>pom</packaging>
<name>Guava Maven Parent</name>
<description>Parent for guava artifacts</description>
@@ -14,14 +14,21 @@
<properties>
<!-- Override this with -Dtest.include="**/SomeTest.java" on the CLI -->
<test.include>%regex[.*.class]</test.include>
- <truth.version>1.1.2</truth.version>
- <checker-framework.version>3.12.0</checker-framework.version>
- <animal.sniffer.version>1.20</animal.sniffer.version>
- <maven-javadoc-plugin.version>3.1.0</maven-javadoc-plugin.version>
+ <truth.version>1.1.3</truth.version>
+ <maven-javadoc-plugin.version>3.4.1</maven-javadoc-plugin.version>
+ <javac.version>9+181-r4173-1</javac.version>
<!-- Empty for all JDKs but 9-12 -->
<maven-javadoc-plugin.additionalJOptions></maven-javadoc-plugin.additionalJOptions>
<maven-source-plugin.version>3.2.1</maven-source-plugin.version>
+ <project.build.outputTimestamp>2023-07-31T21:00:57Z</project.build.outputTimestamp>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <test.add.opens></test.add.opens>
+ <module.status>release</module.status>
+ <variant.jvmEnvironment>android</variant.jvmEnvironment>
+ <variant.jvmEnvironmentVariantName>android</variant.jvmEnvironmentVariantName>
+ <otherVariant.version>32.1.2-jre</otherVariant.version>
+ <otherVariant.jvmEnvironment>standard-jvm</otherVariant.jvmEnvironment>
+ <otherVariant.jvmEnvironmentVariantName>jre</otherVariant.jvmEnvironmentVariantName>
</properties>
<issueManagement>
<system>GitHub Issues</system>
@@ -70,11 +77,11 @@
<testSourceDirectory>test</testSourceDirectory>
<resources>
<resource>
- <directory>src</directory>
- <excludes>
- <exclude>**/*.java</exclude>
- <exclude>**/*.sw*</exclude>
- </excludes>
+ <directory>../..</directory>
+ <includes>
+ <include>LICENSE</include>
+ </includes>
+ <targetPath>META-INF</targetPath>
</resource>
</resources>
<testResources>
@@ -111,6 +118,9 @@
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
+ <configuration>
+ <source>${java.specification.version}</source>
+ </configuration>
</plugin>
</plugins>
<pluginManagement>
@@ -121,6 +131,8 @@
<configuration>
<source>1.8</source>
<target>1.8</target>
+ <encoding>UTF-8</encoding>
+ <parameters>true</parameters>
<compilerArgs>
<!--
Make includes/excludes fully work:
@@ -130,7 +142,24 @@
-->
<arg>-sourcepath</arg>
<arg>doesnotexist</arg>
+ <!-- https://errorprone.info/docs/installation#maven -->
+ <arg>-XDcompilePolicy=simple</arg>
+ <!-- -Xplugin:ErrorProne is set conditionally by a profile. -->
</compilerArgs>
+ <annotationProcessorPaths>
+ <path>
+ <groupId>com.google.errorprone</groupId>
+ <artifactId>error_prone_core</artifactId>
+ <version>2.16</version>
+ </path>
+ </annotationProcessorPaths>
+ <!-- Fork:
+
+ - for JDK8 because we use a javac9 bootclasspath
+
+ - for JDK9+ because we need args like add-exports
+ -->
+ <fork>true</fork>
</configuration>
</plugin>
<plugin>
@@ -151,8 +180,9 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
- <version>${animal.sniffer.version}</version>
+ <version>1.23</version>
<configuration>
+ <annotations>com.google.common.collect.IgnoreJRERequirement,com.google.common.hash.IgnoreJRERequirement,com.google.common.io.IgnoreJRERequirement,com.google.common.reflect.IgnoreJRERequirement,com.google.common.testing.IgnoreJRERequirement</annotations>
<checkTestClasses>true</checkTestClasses>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
@@ -230,7 +260,7 @@
<runOrder>alphabetical</runOrder>
<!-- Set max heap for tests. -->
<!-- Catch dependencies on the default locale by setting it to hi-IN. -->
- <argLine>-Xmx1536M -Duser.language=hi -Duser.country=IN</argLine>
+ <argLine>-Xmx1536M -Duser.language=hi -Duser.country=IN ${test.add.opens}</argLine>
</configuration>
</plugin>
<plugin>
@@ -238,6 +268,15 @@
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>3.3.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>3.4.0</version>
+ </plugin>
</plugins>
</pluginManagement>
</build>
@@ -268,74 +307,19 @@
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
- <version>${checker-framework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.checkerframework</groupId>
- <artifactId>checker-qual</artifactId>
- <version>${checker-framework.version}</version>
- <classifier>sources</classifier>
+ <version>3.33.0</version>
</dependency>
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
- <version>2.11.0</version>
+ <version>2.18.0</version>
</dependency>
<dependency>
<groupId>com.google.j2objc</groupId>
<artifactId>j2objc-annotations</artifactId>
- <version>1.3</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.13.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- <version>4.3</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <version>3.9.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.jimfs</groupId>
- <artifactId>jimfs</artifactId>
- <version>1.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.truth</groupId>
- <artifactId>truth</artifactId>
- <version>${truth.version}</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <!-- use the guava we're building. -->
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.google.caliper</groupId>
- <artifactId>caliper</artifactId>
- <version>1.0-beta-2</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <!-- use the guava we're building. -->
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- </exclusions>
+ <version>2.8</version>
</dependency>
+ <!-- We avoid using dependencyManagement for test-only deps because of https://github.com/google/guava/issues/6654 -->
</dependencies>
</dependencyManagement>
<profiles>
@@ -372,7 +356,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
- <version>1.6</version>
+ <version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
@@ -388,21 +372,128 @@
</profile>
<profile>
<!--
- Passes JDK 9-12-specific `no-module-directories` flag to Javadoc tool,
+ Passes JDK 11-12-specific `no-module-directories` flag to Javadoc tool,
which is required to make symbol search work correctly in the generated
pages.
- This flag does not exist on 8 and 13+ (https://bugs.openjdk.java.net/browse/JDK-8215582).
+ This flag does not exist on 9-10 and 13+ (https://bugs.openjdk.java.net/browse/JDK-8215582).
Consider removing it once our release and test scripts are migrated to a recent JDK (17+).
-->
- <id>javadocs-jdk9-12</id>
+ <id>javadocs-jdk11-12</id>
<activation>
- <jdk>[9,13)</jdk>
+ <jdk>[11,13)</jdk>
</activation>
<properties>
<maven-javadoc-plugin.additionalJOptions>--no-module-directories</maven-javadoc-plugin.additionalJOptions>
</properties>
</profile>
+ <profile>
+ <id>open-jre-modules</id>
+ <activation>
+ <jdk>[9,]</jdk>
+ </activation>
+ <properties>
+ <!--
+ Some tests need reflective access to the internals of these packages. It is only the
+ tests themselves and not the code being tested that needs that access, though there's no
+ obvious way to ensure that.
+
+ We could consider arranging things so that only the tests we know need this would get
+ the add-opens. Right now that doesn't seem worth the effort, though.
+ -->
+ <test.add.opens>
+ --add-opens java.base/java.lang=ALL-UNNAMED
+ --add-opens java.base/java.util=ALL-UNNAMED
+ --add-opens java.base/sun.security.jca=ALL-UNNAMED
+ </test.add.opens>
+ </properties>
+ </profile>
+ <profile>
+ <id>javac9-for-jdk8</id>
+ <activation>
+ <jdk>1.8</jdk>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <!-- Under JDK8, we continue to use errorprone's javac9 (even
+ though we don't run Error Prone itself, which no longer
+ supports JDK8!).
+
+ Why? At some point, presumably after
+ https://github.com/google/guava/commit/e06a8cec65815599e510d7f9c1ea9d2a8eaa438a,
+ builds with JDK8 began failing animal-sniffer with the error:
+
+ Failed to check signatures: Bad class file .../CollectionFuture$ListFuture.class
+
+ One way of dealing with that would be to disable
+ animal-sniffer. And that would be fine for our -jre builds:
+ If we're building with JDK8, then clearly we're sticking to
+ JDK8 APIs. However, I assume (but did not confirm) that we'd
+ have the same issue with our -android builds, which need
+ animal-sniffer so that they can check that we're sticking to
+ JDK6-like APIs.
+
+ So instead, we use javac9, which doesn't lead to this error.
+ -->
+ <compilerArgs combine.children="append">
+ <arg>-J-Xbootclasspath/p:${settings.localRepository}/com/google/errorprone/javac/${javac.version}/javac-${javac.version}.jar</arg>
+ </compilerArgs>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ <profile>
+ <id>run-error-prone</id>
+ <activation>
+ <!--
+ Error Prone requires 11+: https://errorprone.info/docs/installation
+ We skip 12-15 because of https://github.com/google/error-prone/issues/3540.
+ -->
+ <jdk>[11,12),[16,)</jdk>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <compilerArgs combine.children="append">
+ <!-- https://errorprone.info/docs/installation#maven -->
+ <!-- TODO(cpovirk): Enable NullArgumentForNonNullParameter for
+ prod code. It's disabled automatically for "test code"
+ (which is good: our tests have intentional violations), but
+ Error Prone doesn't know it's building test code unless we
+ pass -XepCompilingTestOnlyCode, and that argument needs to
+ be passed as part of the same <arg> as -Xplugin:ErrorProne,
+ and I gave up trying to figure out how to do that for test
+ compilation only. -->
+ <arg>-Xplugin:ErrorProne -Xep:NullArgumentForNonNullParameter:OFF -Xep:Java8ApiChecker:ERROR</arg>
+ <!-- https://github.com/google/error-prone/blob/f8e33bc460be82ab22256a7ef8b979d7a2cacaba/docs/installation.md#jdk-16 -->
+ <!-- TODO(cpovirk): Use .mvn/jvm.config instead (per
+ https://errorprone.info/docs/installation#maven) if it can
+ be made not to interfere with JDK8 or if we stop building
+ with JDK8. -->
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>
+ <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>
+ <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg>
+ </compilerArgs>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
</profiles>
</project>
diff --git a/futures/failureaccess/pom.xml b/futures/failureaccess/pom.xml
index 1e10465b6..47fe296de 100644
--- a/futures/failureaccess/pom.xml
+++ b/futures/failureaccess/pom.xml
@@ -33,7 +33,7 @@
<extensions>true</extensions>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <version>2.5.0</version>
+ <version>5.1.8</version>
<executions>
<execution>
<id>bundle-manifest</id>
diff --git a/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutureFailureAccess.java b/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutureFailureAccess.java
index 7cc84898b..96ed5184b 100644
--- a/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutureFailureAccess.java
+++ b/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutureFailureAccess.java
@@ -14,6 +14,7 @@
package com.google.common.util.concurrent.internal;
+
/**
* A future that, if it fails, may <i>optionally</i> provide access to the cause of the failure.
*
@@ -48,5 +49,6 @@ public abstract class InternalFutureFailureAccess {
* instance method. In the unlikely event that you need to call this method, call {@link
* InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}.
*/
- protected abstract Throwable tryInternalFastPathGetFailure();
+ protected abstract
+ Throwable tryInternalFastPathGetFailure();
}
diff --git a/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutures.java b/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutures.java
index 42df5ec14..bfc3ac689 100644
--- a/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutures.java
+++ b/futures/failureaccess/src/com/google/common/util/concurrent/internal/InternalFutures.java
@@ -14,6 +14,7 @@
package com.google.common.util.concurrent.internal;
+
/**
* Static utilities for {@link InternalFutureFailureAccess}. Most users will never need to use this
* class.
@@ -37,7 +38,8 @@ public final class InternalFutures {
* return value of this method as its cause
* </ul>
*/
- public static Throwable tryInternalFastPathGetFailure(InternalFutureFailureAccess future) {
+ public static
+ Throwable tryInternalFastPathGetFailure(InternalFutureFailureAccess future) {
return future.tryInternalFastPathGetFailure();
}
diff --git a/futures/listenablefuture1/src/com/google/common/util/concurrent/ListenableFuture.java b/futures/listenablefuture1/src/com/google/common/util/concurrent/ListenableFuture.java
index a8d9dd4de..cdc2ee110 100644
--- a/futures/listenablefuture1/src/com/google/common/util/concurrent/ListenableFuture.java
+++ b/futures/listenablefuture1/src/com/google/common/util/concurrent/ListenableFuture.java
@@ -36,10 +36,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
* asynchronous operations. You can chain them together manually with calls to methods like {@link
- * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)
- * Futures.transform}, but you will often find it easier to use a framework. Frameworks automate the
- * process, often adding features like monitoring, debugging, and cancellation. Examples of
- * frameworks include:
+ * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor) Futures.transform}
+ * (or {@link FluentFuture#transform(com.google.common.base.Function, Executor)
+ * FluentFuture.transform}), but you will often find it easier to use a framework. Frameworks
+ * automate the process, often adding features like monitoring, debugging, and cancellation.
+ * Examples of frameworks include:
*
* <ul>
* <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
diff --git a/guava-bom/pom.xml b/guava-bom/pom.xml
index 1a3d98ec4..0a625cda5 100644
--- a/guava-bom/pom.xml
+++ b/guava-bom/pom.xml
@@ -8,7 +8,7 @@
<groupId>com.google.guava</groupId>
<artifactId>guava-bom</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
<packaging>pom</packaging>
<parent>
diff --git a/guava-gwt/pom.xml b/guava-gwt/pom.xml
index 5c93f83d8..8eddd48e7 100644
--- a/guava-gwt/pom.xml
+++ b/guava-gwt/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
</parent>
<artifactId>guava-gwt</artifactId>
<name>Guava GWT compatible libs</name>
@@ -17,8 +17,8 @@
This project includes GWT-friendly sources.
</description>
<properties>
- <gwt.version>2.9.0</gwt.version>
- <gwt.plugin.version>2.8.2</gwt.plugin.version>
+ <gwt.version>2.10.0</gwt.version>
+ <gwt.plugin.version>2.10.0</gwt.plugin.version>
<gwt.logLevel>WARN</gwt.logLevel>
</properties>
<repositories>
@@ -53,11 +53,6 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>com.google.elemental2</groupId>
- <artifactId>elemental2-promise</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>${project.version}</version>
@@ -78,13 +73,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.google.gwt</groupId>
+ <groupId>org.gwtproject</groupId>
<artifactId>gwt-dev</artifactId>
<version>${gwt.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.google.gwt</groupId>
+ <groupId>org.gwtproject</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwt.version}</version>
<scope>test</scope>
@@ -95,6 +90,13 @@
<version>${truth.version}</version>
<classifier>gwt</classifier>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <!-- use the guava we're building. -->
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.google.truth.extensions</groupId>
@@ -102,6 +104,13 @@
<version>${truth.version}</version>
<classifier>gwt</classifier>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <!-- use the guava we're building. -->
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
@@ -299,17 +308,28 @@
<include name="**/InternalFutureFailureAccess.java" />
</fileset>
</copy>
+ <!-- Any manually written supersource should take priority over the original guava source, so we set overwrite=true. -->
+ <copy toDir="${project.build.directory}/guava-gwt-sources" overwrite="true">
+ <fileset dir="src-super" />
+ </copy>
<copy toDir="${project.build.directory}/guava-test-gwt-sources">
<fileset dir="${project.build.directory}/guava-test-sources">
<contains text="@GwtCompatible"/>
</fileset>
</copy>
+ <!-- TODO(cpovirk): If we continue stripping these once we use @ElementTypesAreNonnullByDefault, then we should strip @ElementTypesAreNonnullByDefault, too, to reflect that the classes are *not* fully annotated. But hopefully we can stop stripping them, as https://github.com/jspecify/jspecify/issues/184 should make possible. -->
<replace token="@Nullable" value="">
<fileset dir="${project.build.directory}">
<include name="guava-gwt-sources/**/*.java"/>
<include name="guava-test-gwt-sources/**/*.java"/>
</fileset>
</replace>
+ <replace token="@NonNull" value="">
+ <fileset dir="${project.build.directory}">
+ <include name="guava-gwt-sources/**/*.java"/>
+ <include name="guava-test-gwt-sources/**/*.java"/>
+ </fileset>
+ </replace>
</target>
</configuration>
</execution>
@@ -329,6 +349,7 @@
<module>com.google.common.ForceGuavaCompilation</module>
<failOnError>true</failOnError>
<logLevel>${gwt.logLevel}</logLevel>
+ <generateJsInteropExports>true</generateJsInteropExports>
<validateOnly>true</validateOnly>
<sourceLevel>1.8</sourceLevel>
<!--
@@ -401,9 +422,8 @@
<resource>
<directory>src</directory>
</resource>
- <resource>
- <directory>src-super</directory>
- </resource>
+ <!-- src-super is copied to guava-gwt-sources (so that we can strip its @Nullable annotations), so we don't need to list it here. We may want to arrange something similar for test-super someday. -->
+ <!-- TODO(cpovirk): Why do we have separate src and src-super directories, anyway? -->
<resource>
<directory>${project.build.directory}/guava-gwt-sources</directory>
</resource>
diff --git a/guava-gwt/src-super/com/google/common/base/super/com/google/common/base/Platform.java b/guava-gwt/src-super/com/google/common/base/super/com/google/common/base/Platform.java
index 2e17c9a28..81d84cc64 100644
--- a/guava-gwt/src-super/com/google/common/base/super/com/google/common/base/Platform.java
+++ b/guava-gwt/src-super/com/google/common/base/super/com/google/common/base/Platform.java
@@ -18,7 +18,6 @@ package com.google.common.base;
import static jsinterop.annotations.JsPackage.GLOBAL;
-import java.util.concurrent.TimeUnit;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -33,21 +32,6 @@ final class Platform {
return matcher;
}
- @SuppressWarnings("GoodTime") // reading system time without TimeSource
- static long systemNanoTime() {
- // System.nanoTime() is not available in GWT, so we get milliseconds
- // and convert to nanos.
- return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis());
- }
-
- static <T extends Enum<T>> Optional<T> getEnumIfPresent(Class<T> enumClass, String value) {
- try {
- return Optional.of(Enum.valueOf(enumClass, value));
- } catch (IllegalArgumentException iae) {
- return Optional.absent();
- }
- }
-
static String formatCompact4Digits(double value) {
return "" + ((Number) (Object) value).toPrecision(4);
}
@@ -80,16 +64,5 @@ final class Platform {
throw new UnsupportedOperationException();
}
- /*
- * We will eventually disable GWT-RPC on the server side, but we'll leave it nominally enabled on
- * the client side. There's little practical difference: If it's disabled on the server, it won't
- * work. It's just a matter of how quickly it fails. I'm not sure if failing on the client would
- * be better or not, but it's harder: GWT's System.getProperty reads from a different property
- * list than Java's, so anyone who needs to reenable GWT-RPC in an emergency would have to figure
- * out how to set both properties. It's easier to have to set only one, and it might as well be
- * the Java property, since Guava already reads another Java property.
- */
- static void checkGwtRpcEnabled() {}
-
private Platform() {}
}
diff --git a/guava-gwt/src-super/com/google/common/cache/super/com/google/common/cache/LocalCache.java b/guava-gwt/src-super/com/google/common/cache/super/com/google/common/cache/LocalCache.java
index 8530defd2..fb3a03e41 100644
--- a/guava-gwt/src-super/com/google/common/cache/super/com/google/common/cache/LocalCache.java
+++ b/guava-gwt/src-super/com/google/common/cache/super/com/google/common/cache/LocalCache.java
@@ -26,6 +26,7 @@ import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
@@ -112,6 +113,7 @@ public class LocalCache<K, V> implements ConcurrentMap<K, V> {
}
}
+ @CanIgnoreReturnValue
@Override
public V put(K key, V value) {
checkNotNull(key);
@@ -124,6 +126,7 @@ public class LocalCache<K, V> implements ConcurrentMap<K, V> {
return oldValue.getValue();
}
+ @CanIgnoreReturnValue
@Override
public V remove(Object key) {
Timestamped<V> stamped = cachingHashMap.remove(key);
@@ -166,6 +169,7 @@ public class LocalCache<K, V> implements ConcurrentMap<K, V> {
return put(key, value);
}
+ @CanIgnoreReturnValue
@Override
public boolean remove(Object key, Object value) {
if (value.equals(get(key))) {
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/AbstractSortedMultiset.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/AbstractSortedMultiset.java
index 88cc53631..412ef964c 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/AbstractSortedMultiset.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/AbstractSortedMultiset.java
@@ -20,7 +20,6 @@ import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
-import org.checkerframework.checker.nullness.qual.Nullable;
/**
* This class provides a skeletal implementation of the {@link SortedMultiset} interface.
@@ -98,10 +97,7 @@ abstract class AbstractSortedMultiset<E> extends AbstractMultiset<E> implements
@Override
public SortedMultiset<E> subMultiset(
- @Nullable E fromElement,
- BoundType fromBoundType,
- @Nullable E toElement,
- BoundType toBoundType) {
+ E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) {
// These are checked elsewhere, but NullPointerTester wants them checked eagerly.
checkNotNull(fromBoundType);
checkNotNull(toBoundType);
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EnumMultiset.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EnumMultiset.java
new file mode 100644
index 000000000..f4676a0f6
--- /dev/null
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/EnumMultiset.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.collect.Platform.getDeclaringClassOrObjectForJ2cl;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.Serializable;
+import java.util.EnumMap;
+import java.util.Iterator;
+
+@GwtCompatible(emulated = true)
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
+public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E>
+ implements Serializable {
+ public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) {
+ return new EnumMultiset<>(new EnumMap<E, Count>(type));
+ }
+
+ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) {
+ Iterator<E> iterator = elements.iterator();
+ checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable");
+ EnumMap<E, Count> map = new EnumMap<>(getDeclaringClassOrObjectForJ2cl(iterator.next()));
+ EnumMultiset<E> multiset = new EnumMultiset<>(map);
+ Iterables.addAll(multiset, elements);
+ return multiset;
+ }
+
+ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements, Class<E> type) {
+ EnumMultiset<E> result = create(type);
+ Iterables.addAll(result, elements);
+ return result;
+ }
+
+ /** Creates an empty {@code EnumMultiset}. */
+ private EnumMultiset(EnumMap<E, Count> map) {
+ super(map);
+ }
+}
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMap.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMap.java
index ff989657f..0b9b3cd32 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMap.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMap.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
@@ -164,35 +165,41 @@ public abstract class ImmutableBiMap<K, V> extends ForwardingImmutableMap<K, V>
super(initCapacity);
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
super.putAll(map);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
return this;
}
+ @CanIgnoreReturnValue
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
super.orderEntriesByValue(valueComparator);
return this;
}
+ @CanIgnoreReturnValue
Builder<K, V> combine(Builder<K, V> other) {
super.combine(other);
return this;
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java
index ccab6d882..ee93d9b1f 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
@@ -139,8 +140,10 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
return newCapacity;
}
+ @CanIgnoreReturnValue
public abstract Builder<E> add(E element);
+ @CanIgnoreReturnValue
public Builder<E> add(E... elements) {
checkNotNull(elements); // for GWT
for (E element : elements) {
@@ -149,6 +152,7 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
return this;
}
+ @CanIgnoreReturnValue
public Builder<E> addAll(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
for (E element : elements) {
@@ -157,6 +161,7 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
return this;
}
+ @CanIgnoreReturnValue
public Builder<E> addAll(Iterator<? extends E> elements) {
checkNotNull(elements); // for GWT
while (elements.hasNext()) {
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableList.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableList.java
index 7f7b72be3..6fddbedc9 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableList.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableList.java
@@ -29,6 +29,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import java.util.stream.Collector;
+import jsinterop.annotations.JsMethod;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -118,6 +119,12 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
System.arraycopy(source, 0, dest, pos, source.length);
}
+ /** ImmutableList.of API that is friendly to use from JavaScript. */
+ @JsMethod(name = "of")
+ static <E> ImmutableList<E> jsOf(E... elements) {
+ return copyOf(elements);
+ }
+
public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
return (elements instanceof Collection)
@@ -142,6 +149,7 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
return copyFromCollection(elements);
}
+ @JsMethod
public static <E> ImmutableList<E> copyOf(E[] elements) {
checkNotNull(elements); // eager for GWT
return copyOf(Arrays.asList(elements));
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMap.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMap.java
index f0b15f6b5..24063ac87 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMap.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableMap.java
@@ -21,6 +21,7 @@ import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
@@ -265,11 +266,13 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
this.entries = Lists.newArrayListWithCapacity(initCapacity);
}
+ @CanIgnoreReturnValue
public Builder<K, V> put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
+ @CanIgnoreReturnValue
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
if (entry instanceof ImmutableEntry) {
checkNotNull(entry.getKey());
@@ -283,10 +286,12 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
return this;
}
+ @CanIgnoreReturnValue
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
return putAll(map.entrySet());
}
+ @CanIgnoreReturnValue
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
for (Entry<? extends K, ? extends V> entry : entries) {
put(entry);
@@ -294,12 +299,14 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
return this;
}
+ @CanIgnoreReturnValue
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
checkState(this.valueComparator == null, "valueComparator was already set");
this.valueComparator = checkNotNull(valueComparator, "valueComparator");
return this;
}
+ @CanIgnoreReturnValue
Builder<K, V> combine(Builder<K, V> other) {
checkNotNull(other);
entries.addAll(other.entries);
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSet.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSet.java
index d5a8dad54..a5ba12333 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSet.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSet.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.util.ArrayList;
import java.util.Collection;
@@ -26,6 +27,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collector;
+import jsinterop.annotations.JsMethod;
/**
* GWT emulated version of {@link com.google.common.collect.ImmutableSet}. For the unsorted sets,
@@ -84,6 +86,13 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
return copyOf(all.iterator());
}
+ /** ImmutableSet.of API that is friendly to use from JavaScript. */
+ @JsMethod(name = "of")
+ static <E> ImmutableSet<E> jsOf(E... elements) {
+ return copyOf(elements);
+ }
+
+ @JsMethod
public static <E> ImmutableSet<E> copyOf(E[] elements) {
checkNotNull(elements);
switch (elements.length) {
@@ -237,12 +246,14 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
this.contents = Lists.newArrayListWithCapacity(initialCapacity);
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> add(E element) {
contents.add(checkNotNull(element));
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> add(E... elements) {
checkNotNull(elements); // for GWT
@@ -251,6 +262,7 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
@@ -261,12 +273,14 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
+ @CanIgnoreReturnValue
Builder<E> combine(Builder<E> builder) {
contents.addAll(builder.contents);
return this;
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedMap.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedMap.java
index fb626be42..7006cc880 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedMap.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedMap.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.Maps.newTreeMap;
import static java.util.Collections.singletonMap;
import static java.util.Collections.unmodifiableSortedMap;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
@@ -342,23 +343,27 @@ public final class ImmutableSortedMap<K, V> extends ForwardingImmutableMap<K, V>
this.comparator = checkNotNull(comparator);
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
return putAll(map.entrySet());
}
+ @CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
for (Entry<? extends K, ? extends V> entry : entries) {
@@ -367,6 +372,7 @@ public final class ImmutableSortedMap<K, V> extends ForwardingImmutableMap<K, V>
return this;
}
+ @CanIgnoreReturnValue
Builder<K, V> combine(Builder<K, V> other) {
super.combine(other);
return this;
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedSet.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedSet.java
index ce09f6129..6a3250adf 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedSet.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableSortedSet.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -401,30 +402,35 @@ public abstract class ImmutableSortedSet<E> extends ForwardingImmutableSet<E>
this.comparator = checkNotNull(comparator);
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> add(E element) {
super.add(element);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
+ @CanIgnoreReturnValue
Builder<E> combine(Builder<E> builder) {
super.combine(builder);
return this;
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/MapMaker.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/MapMaker.java
index b2fd7ae78..a0d535ca8 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/MapMaker.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/MapMaker.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -31,6 +32,7 @@ public final class MapMaker {
public MapMaker() {}
+ @CanIgnoreReturnValue
public MapMaker initialCapacity(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException();
@@ -39,6 +41,7 @@ public final class MapMaker {
return this;
}
+ @CanIgnoreReturnValue
public MapMaker concurrencyLevel(int concurrencyLevel) {
checkArgument(
concurrencyLevel >= 1, "concurrency level (%s) must be at least 1", concurrencyLevel);
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java
index 4b85849ac..840b4622b 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java
@@ -21,15 +21,15 @@ import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Minimal GWT emulation of {@code com.google.common.collect.Platform}.
*
- * <p><strong>This .java file should never be consumed by javac.</strong>
- *
* @author Hayward Chan
*/
final class Platform {
@@ -74,13 +74,8 @@ final class Platform {
}
static <T> T[] newArray(T[] reference, int length) {
- T[] clone = Arrays.copyOf(reference, 0);
- resizeArray(clone, length);
- return clone;
- }
-
- private static void resizeArray(Object array, int newSize) {
- ((NativeArray) array).setLength(newSize);
+ T[] empty = reference.length == 0 ? reference : Arrays.copyOf(reference, 0);
+ return Arrays.copyOf(empty, length);
}
/** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */
@@ -101,6 +96,33 @@ final class Platform {
return mapMaker;
}
+ static <E extends Enum<E>> Class<E> getDeclaringClassOrObjectForJ2cl(E e) {
+ Class<E> classOrNull = getDeclaringClassOrNullForJ2cl(e);
+ @SuppressWarnings("unchecked")
+ Class<E> result = classOrNull == null ? (Class<E>) (Class<?>) Object.class : classOrNull;
+ return result;
+ }
+
+ /*
+ * If I understand correctly:
+ *
+ * This needs to be a @JsMethod so that J2CL knows to look for a JavaScript implemention of
+ * it in Platform.native.js. (The JavaScript implementation inline below is visible to *GWT*, but
+ * *J2CL* doesn't look at it.)
+ *
+ * However, once it's a @JsMethod, GWT produces a warning. That's because (a) the *other* purpose
+ * of @JsMethod is to make a method *callable* from JavaScript and (b) this method would not be
+ * useful to call from vanilla JavaScript because it returns an instance of Class, which can't be
+ * converted to a standard JavaScript type. (Contrast to something like String or boolean.) Since
+ * we're not calling it from JavaScript, we suppress the warning.
+ */
+ @JsMethod
+ @SuppressWarnings("unusable-by-js")
+ private static native <E extends Enum<E>> @Nullable Class<E> getDeclaringClassOrNullForJ2cl(
+ E e) /*-{
+ return e.@java.lang.Enum::getDeclaringClass()();
+ }-*/;
+
static int reduceIterationsIfGwt(int iterations) {
return iterations / 10;
}
@@ -109,16 +131,5 @@ final class Platform {
return exponent / 2;
}
- /*
- * We will eventually disable GWT-RPC on the server side, but we'll leave it nominally enabled on
- * the client side. There's little practical difference: If it's disabled on the server, it won't
- * work. It's just a matter of how quickly it fails. I'm not sure if failing on the client would
- * be better or not, but it's harder: GWT's System.getProperty reads from a different property
- * list than Java's, so anyone who needs to reenable GWT-RPC in an emergency would have to figure
- * out how to set both properties. It's easier to have to set only one, and it might as well be
- * the Java property, since Guava already reads another Java property.
- */
- static void checkGwtRpcEnabled() {}
-
private Platform() {}
}
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.native.js b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.native.js
new file mode 100644
index 000000000..0853e2d8f
--- /dev/null
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.native.js
@@ -0,0 +1,3 @@
+Platform.getDeclaringClassOrNullForJ2cl = function(e) {
+ return null;
+}
diff --git a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultiset.java b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultiset.java
index 5adb9db43..e4c0a6334 100644
--- a/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultiset.java
+++ b/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultiset.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import java.util.Comparator;
import java.util.SortedSet;
@@ -27,7 +26,6 @@ import java.util.SortedSet;
* @author Louis Wasserman
* @since 11.0
*/
-@Beta
public interface SortedMultiset<E> extends Multiset<E>, SortedIterable<E> {
Comparator<? super E> comparator();
diff --git a/guava-gwt/src-super/com/google/common/primitives/super/com/google/common/primitives/Platform.java b/guava-gwt/src-super/com/google/common/primitives/super/com/google/common/primitives/Platform.java
deleted file mode 100644
index 7596ea284..000000000
--- a/guava-gwt/src-super/com/google/common/primitives/super/com/google/common/primitives/Platform.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2019 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.primitives;
-
-final class Platform {
- /*
- * We will eventually disable GWT-RPC on the server side, but we'll leave it nominally enabled on
- * the client side. There's little practical difference: If it's disabled on the server, it won't
- * work. It's just a matter of how quickly it fails. I'm not sure if failing on the client would
- * be better or not, but it's harder: GWT's System.getProperty reads from a different property
- * list than Java's, so anyone who needs to reenable GWT-RPC in an emergency would have to figure
- * out how to set both properties. It's easier to have to set only one, and it might as well be
- * the Java property, since Guava already reads another Java property.
- */
- static void checkGwtRpcEnabled() {}
-
- private Platform() {}
-}
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AbstractFuture.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AbstractFuture.java
index 1ecce78ec..e17376e7a 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AbstractFuture.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AbstractFuture.java
@@ -23,6 +23,7 @@ import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
@@ -37,7 +38,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/** Emulation for AbstractFuture in GWT. */
@SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |.
-public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
+@ElementTypesAreNonnullByDefault
+public abstract class AbstractFuture<V extends @Nullable Object> extends InternalFutureFailureAccess
implements ListenableFuture<V> {
static final boolean GENERATE_CANCELLATION_CAUSES = false;
@@ -47,14 +49,17 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
* of this interface must also be an AbstractFuture and must not override or expose for overriding
* any of the public methods of ListenableFuture.
*/
- interface Trusted<V> extends ListenableFuture<V> {}
+ interface Trusted<V extends @Nullable Object> extends ListenableFuture<V> {}
- abstract static class TrustedFuture<V> extends AbstractFuture<V> implements Trusted<V> {
+ abstract static class TrustedFuture<V extends @Nullable Object> extends AbstractFuture<V>
+ implements Trusted<V> {
+ @CanIgnoreReturnValue
@Override
public final V get() throws InterruptedException, ExecutionException {
return super.get();
}
+ @CanIgnoreReturnValue
@Override
public final V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
@@ -76,6 +81,7 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
super.addListener(listener, executor);
}
+ @CanIgnoreReturnValue
@Override
public final boolean cancel(boolean mayInterruptIfRunning) {
return super.cancel(mayInterruptIfRunning);
@@ -86,8 +92,8 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
private State state;
private V value;
- private Future<? extends V> delegate;
- private Throwable throwable;
+ private @Nullable Future<? extends V> delegate;
+ private @Nullable Throwable throwable;
private boolean mayInterruptIfRunning;
private List<Listener> listeners;
@@ -96,6 +102,7 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
listeners = new ArrayList<Listener>();
}
+ @CanIgnoreReturnValue
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (!state.permitsPublicUserToTransitionTo(State.CANCELLED)) {
@@ -129,12 +136,14 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
/*
* ForwardingFluentFuture needs to override those methods, so they are not final.
*/
+ @CanIgnoreReturnValue
@Override
public V get() throws InterruptedException, ExecutionException {
state.maybeThrowOnGet(throwable);
return value;
}
+ @CanIgnoreReturnValue
@Override
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
@@ -152,6 +161,7 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
}
}
+ @CanIgnoreReturnValue
protected boolean setException(Throwable throwable) {
checkNotNull(throwable);
if (!state.permitsPublicUserToTransitionTo(State.FAILURE)) {
@@ -168,6 +178,7 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
notifyAndClearListeners();
}
+ @CanIgnoreReturnValue
protected boolean set(V value) {
if (!state.permitsPublicUserToTransitionTo(State.VALUE)) {
return false;
@@ -183,6 +194,7 @@ public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
notifyAndClearListeners();
}
+ @CanIgnoreReturnValue
protected boolean setFuture(ListenableFuture<? extends V> future) {
checkNotNull(future);
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AggregateFutureState.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AggregateFutureState.java
index 0058c34c0..f7d9dd21f 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AggregateFutureState.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AggregateFutureState.java
@@ -19,12 +19,15 @@ package com.google.common.util.concurrent;
import static com.google.common.collect.Sets.newHashSet;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Emulation of AggregateFutureState. */
-abstract class AggregateFutureState<OutputT> extends AbstractFuture.TrustedFuture<OutputT> {
+@ElementTypesAreNonnullByDefault
+abstract class AggregateFutureState<OutputT extends @Nullable Object>
+ extends AbstractFuture.TrustedFuture<OutputT> {
// Lazily initialized the first time we see an exception; not released until all the input futures
// & this future completes. Released when the future releases the reference to the running state
- private Set<Throwable> seenExceptions = null;
+ private @Nullable Set<Throwable> seenExceptions = null;
private int remaining;
AggregateFutureState(int remainingFutures) {
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
index 58a7057db..1e9cff859 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
@@ -16,13 +16,16 @@ package com.google.common.util.concurrent;
import com.google.common.base.Function;
import java.util.concurrent.Executor;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Hidden superclass of {@link FluentFuture} that provides us a place to declare special GWT
* versions of the {@link FluentFuture#catching(Class, com.google.common.base.Function)
* FluentFuture.catching} family of methods. Those versions have slightly different signatures.
*/
-abstract class GwtFluentFutureCatchingSpecialization<V> extends AbstractFuture<V> {
+@ElementTypesAreNonnullByDefault
+abstract class GwtFluentFutureCatchingSpecialization<V extends @Nullable Object>
+ extends AbstractFuture<V> {
/*
* In the GWT versions of the methods (below), every exceptionType parameter is required to be
* Class<Throwable>. To handle only certain kinds of exceptions under GWT, you'll need to write
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
index 4ce990d32..f5e05b213 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
@@ -16,12 +16,14 @@ package com.google.common.util.concurrent;
import com.google.common.base.Function;
import java.util.concurrent.Executor;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Hidden superclass of {@link Futures} that provides us a place to declare special GWT versions of
* the {@link Futures#catching(ListenableFuture, Class, com.google.common.base.Function)
* Futures.catching} family of methods. Those versions have slightly different signatures.
*/
+@ElementTypesAreNonnullByDefault
abstract class GwtFuturesCatchingSpecialization {
/*
* In the GWT versions of the methods (below), every exceptionType parameter is required to be
@@ -29,7 +31,7 @@ abstract class GwtFuturesCatchingSpecialization {
* your own instanceof tests.
*/
- public static <V> ListenableFuture<V> catching(
+ public static <V extends @Nullable Object> ListenableFuture<V> catching(
ListenableFuture<? extends V> input,
Class<Throwable> exceptionType,
Function<? super Throwable, ? extends V> fallback,
@@ -37,7 +39,7 @@ abstract class GwtFuturesCatchingSpecialization {
return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
}
- public static <V> ListenableFuture<V> catchingAsync(
+ public static <V extends @Nullable Object> ListenableFuture<V> catchingAsync(
ListenableFuture<? extends V> input,
Class<Throwable> exceptionType,
AsyncFunction<? super Throwable, ? extends V> fallback,
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/InterruptibleTask.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/InterruptibleTask.java
index 1cd9f3e73..8d4217bbd 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/InterruptibleTask.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/InterruptibleTask.java
@@ -18,8 +18,11 @@ package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedCastNullableTToT;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
/** Emulation for InterruptibleTask in GWT. */
-abstract class InterruptibleTask<T> implements Runnable {
+@ElementTypesAreNonnullByDefault
+abstract class InterruptibleTask<T extends @Nullable Object> implements Runnable {
@Override
public void run() {
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java
index f5e92eb8f..345fb94c2 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java
@@ -14,31 +14,29 @@
package com.google.common.util.concurrent;
-import elemental2.promise.IThenable;
-import elemental2.promise.Promise;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
+import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsOptional;
+import jsinterop.annotations.JsPackage;
+import jsinterop.annotations.JsType;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Java super source for ListenableFuture, implementing a structural thenable via a default method.
* For restrictions, please refer to the documentation of the then() method.
- *
- * <p>This class is not (explicitly) implementing IThenable<V> because "then" is overloaded there
- * and the single parameter version would need to be marked native, which does not seem to be
- * feasible in interfaces (see "subclassing a class with overloaded methods" in jsinterop
- * documentation).
*/
-public interface ListenableFuture<V> extends Future<V>, Thenable<V> {
+@ElementTypesAreNonnullByDefault
+public interface ListenableFuture<V extends @Nullable Object> extends Future<V>, IThenable<V> {
void addListener(Runnable listener, Executor executor);
/** Note that this method is not expected to be overridden. */
@JsMethod
@Override
- default <R> IThenable<R> then(
- @JsOptional ThenOnFulfilledCallbackFn<? super V, ? extends R> onFulfilled,
- @JsOptional ThenOnRejectedCallbackFn<? extends R> onRejected) {
+ default <R extends @Nullable Object> IThenable<R> then(
+ @JsOptional IThenOnFulfilledCallbackFn<? super V, ? extends R> onFulfilled,
+ @JsOptional IThenOnRejectedCallbackFn<? extends R> onRejected) {
return new Promise<V>(
(resolve, reject) -> {
Futures.addCallback(
@@ -56,14 +54,54 @@ public interface ListenableFuture<V> extends Future<V>, Thenable<V> {
},
MoreExecutors.directExecutor());
})
- .then(
- (IThenable.ThenOnFulfilledCallbackFn) onFulfilled,
- (IThenable.ThenOnRejectedCallbackFn) onRejected);
+ .then(onFulfilled, onRejected);
}
+}
+
+/**
+ * Subset of the elemental2 IThenable interface without the single-parameter overload, which allows
+ * us to implement it using a default implementation in J2cl ListenableFuture.
+ */
+@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "IThenable")
+interface IThenable<T extends @Nullable Object> {
+ <V extends @Nullable Object> IThenable<V> then(
+ @JsOptional IThenOnFulfilledCallbackFn<? super T, ? extends V> onFulfilled,
+ @JsOptional IThenOnRejectedCallbackFn<? extends V> onRejected);
- // TODO(b/141673833): If this would work, it would allow us to implement IThenable properly:
- // default <R> Promise<R> then(IThenable.ThenOnFulfilledCallbackFn<? super V, ? extends R>
- // onFulfilled) {
- // return then(onFulfilled, null);
- // }
+ @JsFunction
+ interface IThenOnFulfilledCallbackFn<T extends @Nullable Object, V extends @Nullable Object> {
+ V onInvoke(T p0);
+ }
+
+ @JsFunction
+ interface IThenOnRejectedCallbackFn<V extends @Nullable Object> {
+ V onInvoke(Object p0);
+ }
+}
+
+/** Subset of the elemental2 Promise API. */
+@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Promise")
+class Promise<T extends @Nullable Object> implements IThenable<T> {
+
+ @JsFunction
+ interface PromiseExecutorCallbackFn<T extends @Nullable Object> {
+ @JsFunction
+ interface ResolveCallbackFn<T extends @Nullable Object> {
+ void onInvoke(T value);
+ }
+
+ @JsFunction
+ interface RejectCallbackFn {
+ void onInvoke(Object error);
+ }
+
+ void onInvoke(ResolveCallbackFn<T> resolve, RejectCallbackFn reject);
+ }
+
+ public Promise(PromiseExecutorCallbackFn<T> executor) {}
+
+ @Override
+ public native <V extends @Nullable Object> Promise<V> then(
+ @JsOptional IThenOnFulfilledCallbackFn<? super T, ? extends V> onFulfilled,
+ @JsOptional IThenOnRejectedCallbackFn<? extends V> onRejected);
}
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Platform.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Platform.java
index c5f606d88..430e1abd7 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Platform.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Platform.java
@@ -16,7 +16,9 @@
package com.google.common.util.concurrent;
+
/** Methods factored out so that they can be emulated differently in GWT. */
+@ElementTypesAreNonnullByDefault
final class Platform {
static boolean isInstanceOfThrowableClass(Throwable t, Class<? extends Throwable> expectedClass) {
/*
@@ -26,5 +28,7 @@ final class Platform {
return true;
}
+ static void restoreInterruptIfIsInterruptedException(Throwable t) {}
+
private Platform() {}
}
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Thenable.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Thenable.java
deleted file mode 100644
index db468efea..000000000
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Thenable.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2015 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.util.concurrent;
-
-import elemental2.promise.IThenable;
-import jsinterop.annotations.JsFunction;
-import jsinterop.annotations.JsOptional;
-import jsinterop.annotations.JsPackage;
-import jsinterop.annotations.JsType;
-
-/**
- * Subset of the elemental2 IThenable interface without the single-parameter overload, which allows
- * us to implement it using a default implementation in J2cl ListenableFuture.
- */
-@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "IThenable")
-interface Thenable<T> {
- <V> IThenable<V> then(
- @JsOptional ThenOnFulfilledCallbackFn<? super T, ? extends V> onFulfilled,
- @JsOptional ThenOnRejectedCallbackFn<? extends V> onRejected);
-
- @JsFunction
- interface ThenOnFulfilledCallbackFn<T, V> {
- V onInvoke(T p0);
- }
-
- @JsFunction
- interface ThenOnRejectedCallbackFn<V> {
- V onInvoke(Object p0);
- }
-}
diff --git a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Uninterruptibles.java b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Uninterruptibles.java
index 1926678ec..add601819 100644
--- a/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Uninterruptibles.java
+++ b/guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Uninterruptibles.java
@@ -16,15 +16,20 @@
package com.google.common.util.concurrent;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Emulation of Uninterruptibles in GWT. */
+@ElementTypesAreNonnullByDefault
public final class Uninterruptibles {
private Uninterruptibles() {}
- public static <V> V getUninterruptibly(Future<V> future) throws ExecutionException {
+ @CanIgnoreReturnValue
+ public static <V extends @Nullable Object> V getUninterruptibly(Future<V> future)
+ throws ExecutionException {
try {
return future.get();
} catch (InterruptedException e) {
diff --git a/guava-gwt/src/com/google/common/util/concurrent/Concurrent.gwt.xml b/guava-gwt/src/com/google/common/util/concurrent/Concurrent.gwt.xml
index 2fdeb6b88..35108a7c8 100644
--- a/guava-gwt/src/com/google/common/util/concurrent/Concurrent.gwt.xml
+++ b/guava-gwt/src/com/google/common/util/concurrent/Concurrent.gwt.xml
@@ -33,5 +33,4 @@
<inherits name="com.google.common.collect.Collect" />
<inherits name="com.google.gwt.core.Core" />
<inherits name="com.google.gwt.user.User" />
-<inherits name="elemental2.promise.Promise" />
</module>
diff --git a/guava-testlib/README.md b/guava-testlib/README.md
index d4810e3a3..141ad989c 100644
--- a/guava-testlib/README.md
+++ b/guava-testlib/README.md
@@ -13,7 +13,7 @@ To add a dependency on Guava testlib using Maven, use the following:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
<scope>test</scope>
</dependency>
```
@@ -22,7 +22,7 @@ To add a dependency using Gradle:
```gradle
dependencies {
- test 'com.google.guava:guava-testlib:31.1-jre'
+ test 'com.google.guava:guava-testlib:32.1.2-jre'
}
```
diff --git a/guava-testlib/pom.xml b/guava-testlib/pom.xml
index 19ce18a60..c603c1c01 100644
--- a/guava-testlib/pom.xml
+++ b/guava-testlib/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
</parent>
<artifactId>guava-testlib</artifactId>
<name>Guava Testing Library</name>
@@ -38,7 +38,8 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <scope>compile</scope><!-- testlib must carry these transitively -->
+ <!-- *not* <scope>test</scope>; <scope>compile</scope> is right so that guava-testlib users get junit transitively. -->
+ <version>4.13.2</version>
</dependency>
<dependency>
<!--
@@ -46,7 +47,15 @@
-->
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
+ <version>${truth.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <!-- use the guava we're building. -->
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
</dependencies>
<build>
diff --git a/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java b/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java
index c5191be96..23420c375 100644
--- a/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/AbstractCollectionTester.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
import org.junit.Ignore;
@@ -41,6 +42,7 @@ public abstract class AbstractCollectionTester<E>
// TODO: dispose of this once collection is encapsulated.
@Override
+ @CanIgnoreReturnValue
protected Collection<E> resetContainer(Collection<E> newContents) {
collection = super.resetContainer(newContents);
return collection;
diff --git a/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java b/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java
index b86ef1750..a3d0de047 100644
--- a/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/AbstractContainerTester.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper;
import java.util.ArrayList;
import java.util.Arrays;
@@ -61,6 +62,7 @@ public abstract class AbstractContainerTester<C, E>
* @see #resetContainer(Object) resetContainer(C)
* @return the new container instance.
*/
+ @CanIgnoreReturnValue
protected C resetContainer() {
return resetContainer(getSubjectGenerator().createTestSubject());
}
@@ -75,6 +77,7 @@ public abstract class AbstractContainerTester<C, E>
* @return the new container instance
* @param newValue the new container instance
*/
+ @CanIgnoreReturnValue
protected C resetContainer(C newValue) {
container = newValue;
return container;
@@ -207,7 +210,7 @@ public abstract class AbstractContainerTester<C, E>
/**
* Returns the {@linkplain #getSampleElements() sample elements} as ordered by {@link
- * TestContainerGenerator#order(List)}. Tests should used this method only if they declare
+ * TestContainerGenerator#order(List)}. Tests should use this method only if they declare
* requirement {@link com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}.
*/
protected List<E> getOrderedElements() {
diff --git a/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java b/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java
index f1b8f86d1..e9242a794 100644
--- a/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java
@@ -31,6 +31,7 @@ import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Most of the logic for {@link IteratorTester} and {@link ListIteratorTester}.
@@ -146,9 +147,9 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
* {@link #previousElements} if the reverse is true, or -- overriding both of these -- {@code
* null} if {@code remove()} or {@code add()} has been called more recently than either. We use
* this to determine which stack to pop from on a call to {@code remove()} (or to pop from and
- * push to on a call to {@code set()}.
+ * push to on a call to {@code set()}).
*/
- Stack<E> stackWithLastReturnedElementAtTop = null;
+ @Nullable Stack<E> stackWithLastReturnedElementAtTop = null;
MultiExceptionListIterator(List<E> expectedElements) {
Helpers.addAll(nextElements, Helpers.reverse(expectedElements));
@@ -379,7 +380,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
}
private interface IteratorOperation {
- Object execute(Iterator<?> iterator);
+ @Nullable Object execute(Iterator<?> iterator);
}
/**
@@ -465,7 +466,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
private static final IteratorOperation REMOVE_METHOD =
new IteratorOperation() {
@Override
- public Object execute(Iterator<?> iterator) {
+ public @Nullable Object execute(Iterator<?> iterator) {
iterator.remove();
return null;
}
@@ -491,7 +492,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
final Object toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
- public Object execute(Iterator<?> iterator) {
+ public @Nullable Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<Object> rawIterator = (ListIterator<Object>) iterator;
rawIterator.add(toInsert);
@@ -504,7 +505,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
final E toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
- public Object execute(Iterator<?> iterator) {
+ public @Nullable Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<E> li = (ListIterator<E>) iterator;
li.set(toInsert);
diff --git a/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java b/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java
index 5e0de3ccc..2f3229717 100644
--- a/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/AbstractMapTester.java
@@ -23,6 +23,7 @@ import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Ignore;
/**
@@ -167,7 +168,7 @@ public abstract class AbstractMapTester<K, V>
}
}
- private static boolean equal(Object a, Object b) {
+ private static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java b/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java
index dc1e1a067..adbc8dcc6 100644
--- a/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java
@@ -18,6 +18,7 @@ package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* This abstract base class for testers allows the framework to inject needed information after
@@ -34,8 +35,8 @@ import junit.framework.TestCase;
public class AbstractTester<G> extends TestCase {
private G subjectGenerator;
private String suiteName;
- private Runnable setUp;
- private Runnable tearDown;
+ private @Nullable Runnable setUp;
+ private @Nullable Runnable tearDown;
// public so that it can be referenced in generated GWT tests.
@Override
@@ -54,7 +55,8 @@ public class AbstractTester<G> extends TestCase {
}
// public so that it can be referenced in generated GWT tests.
- public final void init(G subjectGenerator, String suiteName, Runnable setUp, Runnable tearDown) {
+ public final void init(
+ G subjectGenerator, String suiteName, @Nullable Runnable setUp, @Nullable Runnable tearDown) {
this.subjectGenerator = subjectGenerator;
this.suiteName = suiteName;
this.setUp = setUp;
diff --git a/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java b/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
index 384770989..cf3a11eab 100644
--- a/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
+++ b/guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
@@ -18,6 +18,7 @@ package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Simple base class to verify that we handle generics correctly.
@@ -38,7 +39,7 @@ public class BaseComparable implements Comparable<BaseComparable>, Serializable
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
if (other == null) {
return false;
} else if (other instanceof BaseComparable) {
diff --git a/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java b/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java
index d80f5a93c..b96e1d07b 100644
--- a/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java
+++ b/guava-testlib/src/com/google/common/collect/testing/DerivedGenerator.java
@@ -24,7 +24,7 @@ import com.google.common.annotations.GwtCompatible;
* collection generator.
*
* <p>{@code GwtTestSuiteGenerator} expects every {@code DerivedIterator} implementation to provide
- * a one-arg constructor accepting its inner generator as an argument). This requirement enables it
+ * a one-arg constructor accepting its inner generator as an argument. This requirement enables it
* to generate source code (since GWT cannot use reflection to generate the suites).
*
* @author Chris Povirk
diff --git a/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java b/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java
new file mode 100644
index 000000000..80379ccb8
--- /dev/null
+++ b/guava-testlib/src/com/google/common/collect/testing/ElementTypesAreNonnullByDefault.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2021 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.testing;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.google.common.annotations.GwtCompatible;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import javax.annotation.Nonnull;
+import javax.annotation.meta.TypeQualifierDefault;
+
+/**
+ * Marks all "top-level" types as non-null in a way that is recognized by Kotlin. Note that this
+ * unfortunately includes type-variable usages, so we also provide {@link ParametricNullness} to
+ * "undo" it as best we can.
+ */
+@GwtCompatible
+@Retention(RUNTIME)
+@Target(TYPE)
+@TypeQualifierDefault({FIELD, METHOD, PARAMETER})
+@Nonnull
+@interface ElementTypesAreNonnullByDefault {}
diff --git a/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java b/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java
index db086aa30..bf15135dc 100644
--- a/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java
+++ b/guava-testlib/src/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilder.java
@@ -24,6 +24,7 @@ import com.google.common.collect.testing.features.ConflictingRequirementsExcepti
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import com.google.common.collect.testing.features.TesterRequirements;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@@ -38,6 +39,7 @@ import java.util.logging.Logger;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests the object generated
@@ -61,12 +63,13 @@ public abstract class FeatureSpecificTestSuiteBuilder<
// Test Data
- private G subjectGenerator;
+ private @Nullable G subjectGenerator;
// Gets run before every test.
private Runnable setUp;
// Gets run at the conclusion of every test.
private Runnable tearDown;
+ @CanIgnoreReturnValue
protected B usingGenerator(G subjectGenerator) {
this.subjectGenerator = subjectGenerator;
return self();
@@ -76,6 +79,7 @@ public abstract class FeatureSpecificTestSuiteBuilder<
return subjectGenerator;
}
+ @CanIgnoreReturnValue
public B withSetUp(Runnable setUp) {
this.setUp = setUp;
return self();
@@ -85,6 +89,7 @@ public abstract class FeatureSpecificTestSuiteBuilder<
return setUp;
}
+ @CanIgnoreReturnValue
public B withTearDown(Runnable tearDown) {
this.tearDown = tearDown;
return self();
@@ -102,10 +107,12 @@ public abstract class FeatureSpecificTestSuiteBuilder<
* Configures this builder to produce tests appropriate for the given features. This method may be
* called more than once to add features in multiple groups.
*/
+ @CanIgnoreReturnValue
public B withFeatures(Feature<?>... features) {
return withFeatures(Arrays.asList(features));
}
+ @CanIgnoreReturnValue
public B withFeatures(Iterable<? extends Feature<?>> features) {
for (Feature<?> feature : features) {
this.features.add(feature);
@@ -119,9 +126,10 @@ public abstract class FeatureSpecificTestSuiteBuilder<
// Name
- private String name;
+ private @Nullable String name;
/** Configures this builder produce a TestSuite with the given name. */
+ @CanIgnoreReturnValue
public B named(String name) {
if (name.contains("(")) {
throw new IllegalArgumentException(
@@ -147,10 +155,12 @@ public abstract class FeatureSpecificTestSuiteBuilder<
* semantics of an implementation disagree in unforeseen ways with the semantics expected by a
* test, or to keep dependent builds clean in spite of an erroneous test.
*/
+ @CanIgnoreReturnValue
public B suppressing(Method... methods) {
return suppressing(Arrays.asList(methods));
}
+ @CanIgnoreReturnValue
public B suppressing(Collection<Method> methods) {
suppressedTests.addAll(methods);
return self();
diff --git a/guava-testlib/src/com/google/common/collect/testing/Helpers.java b/guava-testlib/src/com/google/common/collect/testing/Helpers.java
index aac71cc4e..290e8e300 100644
--- a/guava-testlib/src/com/google/common/collect/testing/Helpers.java
+++ b/guava-testlib/src/com/google/common/collect/testing/Helpers.java
@@ -23,8 +23,11 @@ import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Method;
+import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -39,38 +42,41 @@ import java.util.Map.Entry;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
+import org.checkerframework.checker.nullness.qual.Nullable;
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class Helpers {
// Clone of Objects.equal
- static boolean equal(Object a, Object b) {
+ static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
// Clone of Lists.newArrayList
- public static <E> List<E> copyToList(Iterable<? extends E> elements) {
+ public static <E extends @Nullable Object> List<E> copyToList(Iterable<? extends E> elements) {
List<E> list = new ArrayList<>();
addAll(list, elements);
return list;
}
- public static <E> List<E> copyToList(E[] elements) {
+ public static <E extends @Nullable Object> List<E> copyToList(E[] elements) {
return copyToList(Arrays.asList(elements));
}
// Clone of Sets.newLinkedHashSet
- public static <E> Set<E> copyToSet(Iterable<? extends E> elements) {
+ public static <E extends @Nullable Object> Set<E> copyToSet(Iterable<? extends E> elements) {
Set<E> set = new LinkedHashSet<>();
addAll(set, elements);
return set;
}
- public static <E> Set<E> copyToSet(E[] elements) {
+ public static <E extends @Nullable Object> Set<E> copyToSet(E[] elements) {
return copyToSet(Arrays.asList(elements));
}
// Would use Maps.immutableEntry
- public static <K, V> Entry<K, V> mapEntry(K key, V value) {
+ public static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> mapEntry(
+ K key, V value) {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
@@ -180,7 +186,9 @@ public class Helpers {
}
}
- public static <E> boolean addAll(Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
+ @CanIgnoreReturnValue
+ public static <E extends @Nullable Object> boolean addAll(
+ Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
boolean modified = false;
for (E e : elementsToAdd) {
modified |= addTo.add(e);
@@ -250,17 +258,26 @@ public class Helpers {
throw assertionFailedError;
}
- public static <K, V> Comparator<Entry<K, V>> entryComparator(
- Comparator<? super K> keyComparator) {
- return new Comparator<Entry<K, V>>() {
- @Override
- @SuppressWarnings("unchecked") // no less safe than putting it in the map!
- public int compare(Entry<K, V> a, Entry<K, V> b) {
+ private static class EntryComparator<K extends @Nullable Object, V extends @Nullable Object>
+ implements Comparator<Entry<K, V>> {
+ final @Nullable Comparator<? super K> keyComparator;
+
+ public EntryComparator(@Nullable Comparator<? super K> keyComparator) {
+ this.keyComparator = keyComparator;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked") // no less safe than putting it in the map!
+ public int compare(Entry<K, V> a, Entry<K, V> b) {
return (keyComparator == null)
? ((Comparable) a.getKey()).compareTo(b.getKey())
: keyComparator.compare(a.getKey(), b.getKey());
- }
- };
+ }
+ }
+
+ public static <K, V> Comparator<Entry<K, V>> entryComparator(
+ @Nullable Comparator<? super K> keyComparator) {
+ return new EntryComparator<K, V>(keyComparator);
}
/**
@@ -290,7 +307,7 @@ public class Helpers {
* valuesInExpectedOrder.get(i)} and {@code tj = valuesInExpectedOrder.get(j)}.
* </ul>
*/
- public static <T> void testComparator(
+ public static <T extends @Nullable Object> void testComparator(
Comparator<? super T> comparator, List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
@@ -345,14 +362,47 @@ public class Helpers {
* @param delta the difference between the true size of the collection and the values returned by
* the size method
*/
- public static <T> Collection<T> misleadingSizeCollection(int delta) {
+ public static <T extends @Nullable Object> Collection<T> misleadingSizeCollection(int delta) {
// It would be nice to be able to return a real concurrent
// collection like ConcurrentLinkedQueue, so that e.g. concurrent
// iteration would work, but that would not be GWT-compatible.
- return new ArrayList<T>() {
+ // We are not "just" inheriting from ArrayList here as this doesn't work for J2kt.
+ return new AbstractList<T>() {
+ ArrayList<T> data = new ArrayList<>();
+
@Override
public int size() {
- return Math.max(0, super.size() + delta);
+ return Math.max(0, data.size() + delta);
+ }
+
+ @Override
+ public T get(int index) {
+ return data.get(index);
+ }
+
+ @Override
+ public T set(int index, T element) {
+ return data.set(index, element);
+ }
+
+ @Override
+ public boolean add(T element) {
+ return data.add(element);
+ }
+
+ @Override
+ public void add(int index, T element) {
+ data.add(index, element);
+ }
+
+ @Override
+ public T remove(int index) {
+ return data.remove(index);
+ }
+
+ @Override
+ public @Nullable Object[] toArray() {
+ return data.toArray();
}
};
}
@@ -363,7 +413,8 @@ public class Helpers {
* equals. This is used for testing unmodifiable collections of map entries; for example, it
* should not be possible to access the raw (modifiable) map entry via a nefarious equals method.
*/
- public static <K, V> Entry<K, V> nefariousMapEntry(K key, V value) {
+ public static <K extends @Nullable Object, V extends @Nullable Object>
+ Entry<K, V> nefariousMapEntry(K key, V value) {
return new Entry<K, V>() {
@Override
public K getKey() {
@@ -382,7 +433,7 @@ public class Helpers {
@SuppressWarnings("unchecked")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof Entry) {
Entry<K, V> e = (Entry<K, V>) o;
e.setValue(value); // muhahaha!
@@ -406,7 +457,7 @@ public class Helpers {
};
}
- static <E> List<E> castOrCopyToList(Iterable<E> iterable) {
+ static <E extends @Nullable Object> List<E> castOrCopyToList(Iterable<E> iterable) {
if (iterable instanceof List) {
return (List<E>) iterable;
}
@@ -426,6 +477,7 @@ public class Helpers {
}
};
+ @J2ktIncompatible
public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey(
List<Entry<K, V>> insertionOrder) {
sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER));
@@ -444,7 +496,7 @@ public class Helpers {
* values, it lies outside the submap/submultiset ranges we test, and the variety of tests that
* exercise null handling fail on those subcollections.
*/
- public abstract static class NullsBefore implements Comparator<String>, Serializable {
+ public abstract static class NullsBefore implements Comparator<@Nullable String>, Serializable {
/*
* We don't serialize this class in GWT, so we don't care about whether GWT will serialize this
* field.
@@ -460,7 +512,7 @@ public class Helpers {
}
@Override
- public int compare(String lhs, String rhs) {
+ public int compare(@Nullable String lhs, @Nullable String rhs) {
if (lhs == rhs) {
return 0;
}
@@ -484,7 +536,7 @@ public class Helpers {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof NullsBefore) {
NullsBefore other = (NullsBefore) obj;
return justAfterNull.equals(other.justAfterNull);
@@ -514,6 +566,7 @@ public class Helpers {
}
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public static Method getMethod(Class<?> clazz, String name) {
try {
diff --git a/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java b/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java
index 15d48dbbd..816a97377 100644
--- a/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java
+++ b/guava-testlib/src/com/google/common/collect/testing/MinimalIterable.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code Iterable} which throws an exception on all invocations of the {@link
@@ -63,7 +64,7 @@ public final class MinimalIterable<E> implements Iterable<E> {
return (MinimalIterable) of(elements.toArray());
}
- private Iterator<E> iterator;
+ private @Nullable Iterator<E> iterator;
private MinimalIterable(Iterator<E> iterator) {
this.iterator = iterator;
diff --git a/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java b/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java
index 9a87d244d..4027684b4 100644
--- a/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java
+++ b/guava-testlib/src/com/google/common/collect/testing/MinimalSet.java
@@ -22,6 +22,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A simplistic set which implements the bare minimum so that it can be used in tests without
@@ -63,7 +64,7 @@ public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> {
*/
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return (this.size() == that.size()) && this.containsAll(that);
diff --git a/guava-testlib/src/com/google/common/collect/testing/Platform.java b/guava-testlib/src/com/google/common/collect/testing/Platform.java
index a2c020c91..cfc7ac3b2 100644
--- a/guava-testlib/src/com/google/common/collect/testing/Platform.java
+++ b/guava-testlib/src/com/google/common/collect/testing/Platform.java
@@ -34,7 +34,7 @@ final class Platform {
// Class.cast is not supported in GWT. This method is a no-op in GWT.
static void checkCast(Class<?> clazz, Object obj) {
- clazz.cast(obj);
+ Object unused = clazz.cast(obj);
}
static String format(String template, Object... args) {
diff --git a/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java b/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java
index ac62d44b6..c94b81998 100644
--- a/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java
+++ b/guava-testlib/src/com/google/common/collect/testing/QueueTestSuiteBuilder.java
@@ -22,6 +22,7 @@ import com.google.common.collect.testing.testers.QueueOfferTester;
import com.google.common.collect.testing.testers.QueuePeekTester;
import com.google.common.collect.testing.testers.QueuePollTester;
import com.google.common.collect.testing.testers.QueueRemoveTester;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.List;
@@ -45,6 +46,7 @@ public final class QueueTestSuiteBuilder<E>
* collection that's both a queue and a list, to avoid running the common collection tests twice.
* By default, collection tests do run.
*/
+ @CanIgnoreReturnValue
public QueueTestSuiteBuilder<E> skipCollectionTests() {
runCollectionTests = false;
return this;
diff --git a/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java b/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java
index 5856e3b54..c284619da 100644
--- a/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java
+++ b/guava-testlib/src/com/google/common/collect/testing/SafeTreeMap.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtIncompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Collection;
@@ -28,6 +29,7 @@ import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A wrapper around {@code TreeMap} that aggressively checks to see if keys are mutually comparable.
@@ -75,12 +77,12 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> ceilingEntry(K key) {
+ public @Nullable Entry<K, V> ceilingEntry(K key) {
return delegate.ceilingEntry(checkValid(key));
}
@Override
- public K ceilingKey(K key) {
+ public @Nullable K ceilingKey(K key) {
return delegate.ceilingKey(checkValid(key));
}
@@ -162,7 +164,7 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> firstEntry() {
+ public @Nullable Entry<K, V> firstEntry() {
return delegate.firstEntry();
}
@@ -172,17 +174,17 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> floorEntry(K key) {
+ public @Nullable Entry<K, V> floorEntry(K key) {
return delegate.floorEntry(checkValid(key));
}
@Override
- public K floorKey(K key) {
+ public @Nullable K floorKey(K key) {
return delegate.floorKey(checkValid(key));
}
@Override
- public V get(Object key) {
+ public @Nullable V get(Object key) {
return delegate.get(checkValid(key));
}
@@ -197,12 +199,12 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> higherEntry(K key) {
+ public @Nullable Entry<K, V> higherEntry(K key) {
return delegate.higherEntry(checkValid(key));
}
@Override
- public K higherKey(K key) {
+ public @Nullable K higherKey(K key) {
return delegate.higherKey(checkValid(key));
}
@@ -217,7 +219,7 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> lastEntry() {
+ public @Nullable Entry<K, V> lastEntry() {
return delegate.lastEntry();
}
@@ -227,12 +229,12 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> lowerEntry(K key) {
+ public @Nullable Entry<K, V> lowerEntry(K key) {
return delegate.lowerEntry(checkValid(key));
}
@Override
- public K lowerKey(K key) {
+ public @Nullable K lowerKey(K key) {
return delegate.lowerKey(checkValid(key));
}
@@ -242,17 +244,17 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public Entry<K, V> pollFirstEntry() {
+ public @Nullable Entry<K, V> pollFirstEntry() {
return delegate.pollFirstEntry();
}
@Override
- public Entry<K, V> pollLastEntry() {
+ public @Nullable Entry<K, V> pollLastEntry() {
return delegate.pollLastEntry();
}
@Override
- public V put(K key, V value) {
+ public @Nullable V put(K key, V value) {
return delegate.put(checkValid(key), value);
}
@@ -265,7 +267,7 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
}
@Override
- public V remove(Object key) {
+ public @Nullable V remove(Object key) {
return delegate.remove(checkValid(key));
}
@@ -300,16 +302,17 @@ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V>
return delegate.values();
}
+ @CanIgnoreReturnValue
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
K k = (K) t;
- comparator().compare(k, k);
+ int unused = comparator().compare(k, k);
return t;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return delegate.equals(obj);
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java b/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java
index 91d9fd9f7..ddb628656 100644
--- a/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java
+++ b/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtIncompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
@@ -24,6 +25,7 @@ import java.util.Iterator;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A wrapper around {@code TreeSet} that aggressively checks to see if elements are mutually
@@ -81,7 +83,7 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E ceiling(E e) {
+ public @Nullable E ceiling(E e) {
return delegate.ceiling(checkValid(e));
}
@@ -126,7 +128,7 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E floor(E e) {
+ public @Nullable E floor(E e) {
return delegate.floor(checkValid(e));
}
@@ -141,7 +143,7 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E higher(E e) {
+ public @Nullable E higher(E e) {
return delegate.higher(checkValid(e));
}
@@ -161,17 +163,17 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
}
@Override
- public E lower(E e) {
+ public @Nullable E lower(E e) {
return delegate.lower(checkValid(e));
}
@Override
- public E pollFirst() {
+ public @Nullable E pollFirst() {
return delegate.pollFirst();
}
@Override
- public E pollLast() {
+ public @Nullable E pollLast() {
return delegate.pollLast();
}
@@ -228,16 +230,17 @@ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
return delegate.toArray(a);
}
+ @CanIgnoreReturnValue
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
E e = (E) t;
- comparator().compare(e, e);
+ int unused = comparator().compare(e, e);
return t;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return delegate.equals(obj);
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/SampleElements.java b/guava-testlib/src/com/google/common/collect/testing/SampleElements.java
index 400107dc5..9fed1fbe8 100644
--- a/guava-testlib/src/com/google/common/collect/testing/SampleElements.java
+++ b/guava-testlib/src/com/google/common/collect/testing/SampleElements.java
@@ -21,6 +21,7 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A container class for the five sample elements we need for testing.
@@ -143,7 +144,7 @@ public class SampleElements<E> implements Iterable<E> {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof Collider && ((Collider) obj).value == value;
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java b/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java
index 7944aaa6a..4a290860e 100644
--- a/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java
+++ b/guava-testlib/src/com/google/common/collect/testing/SortedMapTestSuiteBuilder.java
@@ -30,6 +30,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests a SortedMap
@@ -88,12 +89,12 @@ public class SortedMapTestSuiteBuilder<K, V> extends MapTestSuiteBuilder<K, V> {
* To avoid infinite recursion, test suites with these marker features won't have derived suites
* created for them.
*/
- enum NoRecurse implements Feature<Void> {
+ enum NoRecurse implements Feature<@Nullable Void> {
SUBMAP,
DESCENDING;
@Override
- public Set<Feature<? super Void>> getImpliedFeatures() {
+ public Set<Feature<? super @Nullable Void>> getImpliedFeatures() {
return Collections.emptySet();
}
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/SpliteratorTester.java b/guava-testlib/src/com/google/common/collect/testing/SpliteratorTester.java
index 9fad6e398..e0c2ebfea 100644
--- a/guava-testlib/src/com/google/common/collect/testing/SpliteratorTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/SpliteratorTester.java
@@ -30,6 +30,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
@@ -103,7 +104,7 @@ public final class SpliteratorTester<E> {
}
@Override
- GeneralSpliterator<E> trySplit() {
+ @Nullable GeneralSpliterator<E> trySplit() {
Spliterator<E> split = spliterator.trySplit();
return split == null ? null : new GeneralSpliteratorOfObject<>(split);
}
@@ -140,7 +141,7 @@ public final class SpliteratorTester<E> {
}
@Override
- GeneralSpliterator<E> trySplit() {
+ @Nullable GeneralSpliterator<E> trySplit() {
Spliterator.OfPrimitive<E, C, ?> split = spliterator.trySplit();
return split == null ? null : new GeneralSpliteratorOfPrimitive<>(split, consumerizer);
}
@@ -275,10 +276,12 @@ public final class SpliteratorTester<E> {
}
@SafeVarargs
+ @CanIgnoreReturnValue
public final Ordered expect(Object... elements) {
return expect(Arrays.asList(elements));
}
+ @CanIgnoreReturnValue
public final Ordered expect(Iterable<?> elements) {
List<List<E>> resultsForAllStrategies = new ArrayList<>();
for (Supplier<GeneralSpliterator<E>> spliteratorSupplier : spliteratorSuppliers) {
diff --git a/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java b/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java
index 69d263bda..3e1d3b4ee 100644
--- a/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java
+++ b/guava-testlib/src/com/google/common/collect/testing/UnhashableObject.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An unhashable object to be used in testing as values in our collections.
@@ -32,7 +33,7 @@ public class UnhashableObject implements Comparable<UnhashableObject> {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object instanceof UnhashableObject) {
UnhashableObject that = (UnhashableObject) object;
return this.value == that.value;
diff --git a/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java b/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java
index 6203e5148..cc627bb5c 100644
--- a/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java
+++ b/guava-testlib/src/com/google/common/collect/testing/features/CollectionSize.java
@@ -24,6 +24,7 @@ import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* When describing the features of the collection produced by a given generator (i.e. in a call to
@@ -59,7 +60,7 @@ public enum CollectionSize implements Feature<Collection>, Comparable<Collection
ANY(ZERO, ONE, SEVERAL);
private final Set<Feature<? super Collection>> implied;
- private final Integer numElements;
+ private final @Nullable Integer numElements;
CollectionSize(int numElements) {
this.implied = Collections.emptySet();
diff --git a/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java b/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java
index 2d11a0863..ce5b73f47 100644
--- a/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java
+++ b/guava-testlib/src/com/google/common/collect/testing/features/FeatureUtil.java
@@ -18,6 +18,7 @@ package com.google.common.collect.testing.features;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.Helpers;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
@@ -55,6 +56,7 @@ public class FeatureUtil {
* @param features the set of features to expand
* @return the same set of features, expanded with all implied features
*/
+ @CanIgnoreReturnValue
public static Set<Feature<?>> addImpliedFeatures(Set<Feature<?>> features) {
Queue<Feature<?>> queue = new ArrayDeque<>(features);
while (!queue.isEmpty()) {
@@ -254,6 +256,7 @@ public class FeatureUtil {
* @throws ConflictingRequirementsException if the additional requirements are inconsistent with
* the existing requirements
*/
+ @CanIgnoreReturnValue
private static TesterRequirements incorporateRequirements(
TesterRequirements requirements, TesterRequirements moreRequirements, Object source)
throws ConflictingRequirementsException {
diff --git a/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java b/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java
index 4780b1bf5..2290f296c 100644
--- a/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java
+++ b/guava-testlib/src/com/google/common/collect/testing/features/TesterRequirements.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import java.util.Collections;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Encapsulates the constraints that a class under test must satisfy in order for a tester method to
@@ -54,7 +55,7 @@ public final class TesterRequirements {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/features/package-info.java b/guava-testlib/src/com/google/common/collect/testing/features/package-info.java
new file mode 100644
index 000000000..88b611ca4
--- /dev/null
+++ b/guava-testlib/src/com/google/common/collect/testing/features/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.features;
diff --git a/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java b/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java
index 7f649e757..92d82c6af 100644
--- a/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultimapTester.java
@@ -23,6 +23,7 @@ import com.google.common.collect.Multimap;
import com.google.common.collect.testing.AbstractContainerTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
@@ -121,11 +122,13 @@ public abstract class AbstractMultimapTester<K, V, M extends Multimap<K, V>>
// TODO: dispose of this once collection is encapsulated.
@Override
+ @CanIgnoreReturnValue
protected M resetContainer(M newContents) {
multimap = super.resetContainer(newContents);
return multimap;
}
+ @CanIgnoreReturnValue
protected Multimap<K, V> resetContainer(Entry<K, V>... newContents) {
multimap = super.resetContainer(getSubjectGenerator().create((Object[]) newContents));
return multimap;
diff --git a/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java b/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java
index 03039706b..67d29198f 100644
--- a/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/google/MultisetSerializationTester.java
@@ -27,7 +27,7 @@ import org.junit.Ignore;
/**
* A generic JUnit test which tests multiset-specific serialization. Can't be invoked directly;
- * please see {@link com.google.common.collect.testing.MultisetTestSuiteBuilder}.
+ * please see {@link MultisetTestSuiteBuilder}.
*
* @author Louis Wasserman
*/
diff --git a/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java b/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java
index d5e69638f..878972c81 100644
--- a/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountConditionallyTester.java
@@ -24,6 +24,7 @@ import static java.util.Collections.nCopies;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.junit.Ignore;
/**
@@ -47,6 +48,7 @@ public class MultisetSetCountConditionallyTester<E> extends AbstractMultisetSetC
setCount(element, count);
}
+ @CanIgnoreReturnValue
private boolean setCount(E element, int count) {
return getMultiset().setCount(element, getMultiset().count(element), count);
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java b/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java
index ec5436dda..9cd7acee7 100644
--- a/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/google/MultisetSetCountUnconditionallyTester.java
@@ -17,6 +17,7 @@
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.junit.Ignore;
/**
@@ -41,6 +42,7 @@ public class MultisetSetCountUnconditionallyTester<E> extends AbstractMultisetSe
setCount(element, count);
}
+ @CanIgnoreReturnValue
private int setCount(E element, int count) {
return getMultiset().setCount(element, count);
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/google/package-info.java b/guava-testlib/src/com/google/common/collect/testing/google/package-info.java
new file mode 100644
index 000000000..57c1a21bb
--- /dev/null
+++ b/guava-testlib/src/com/google/common/collect/testing/google/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.google;
diff --git a/guava-testlib/src/com/google/common/collect/testing/package-info.java b/guava-testlib/src/com/google/common/collect/testing/package-info.java
new file mode 100644
index 000000000..15086f3ae
--- /dev/null
+++ b/guava-testlib/src/com/google/common/collect/testing/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing;
diff --git a/guava-testlib/src/com/google/common/collect/testing/suites/package-info.java b/guava-testlib/src/com/google/common/collect/testing/suites/package-info.java
new file mode 100644
index 000000000..2c2113bb3
--- /dev/null
+++ b/guava-testlib/src/com/google/common/collect/testing/suites/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.suites;
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java
index 46bd52942..05f72dfd3 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/AbstractListIndexOfTester.java
@@ -23,6 +23,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Ignore;
/**
@@ -34,7 +35,7 @@ import org.junit.Ignore;
@Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
public abstract class AbstractListIndexOfTester<E> extends AbstractListTester<E> {
/** Override to call {@code indexOf()} or {@code lastIndexOf()}. */
- protected abstract int find(Object o);
+ protected abstract int find(@Nullable Object o);
/** Override to return "indexOf" or "lastIndexOf()" for use in failure messages. */
protected abstract String getMethodName();
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java
index 848fdd663..c2a0b68ef 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/CollectionCreationTester.java
@@ -52,7 +52,8 @@ public class CollectionCreationTester<E> extends AbstractCollectionTester<E> {
E[] array = createArrayWithNullElement();
try {
- getSubjectGenerator().create(array);
+ // TODO(kak): remove unused capture
+ Object unused = getSubjectGenerator().create(array);
fail("Creating a collection containing null should fail");
} catch (NullPointerException expected) {
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java
index 0d5909737..75fc8b677 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/CollectionRemoveAllTester.java
@@ -29,6 +29,7 @@ import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
+import java.util.AbstractSet;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -92,7 +93,7 @@ public class CollectionRemoveAllTester<E> extends AbstractCollectionTester<E> {
}
}
- /** Trigger the {@code other.size() >= this.size()} case in {@link AbstractSet#removeAll()}. */
+ /** Trigger the {@code other.size() >= this.size()} case in {@link AbstractSet#removeAll}. */
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_somePresentLargeCollectionToRemove() {
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java
index 6cf5be232..955123658 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/ConcurrentMapPutIfAbsentTester.java
@@ -25,6 +25,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import org.junit.Ignore;
@@ -130,6 +131,7 @@ public class ConcurrentMapPutIfAbsentTester<K, V> extends AbstractMapTester<K, V
"Should not contain null after unsupported putIfAbsent(present, null)");
}
+ @CanIgnoreReturnValue
private V putIfAbsent(Entry<K, V> entry) {
return getMap().putIfAbsent(entry.getKey(), entry.getValue());
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java
index 553b69358..7a60add7c 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/ListSubListTester.java
@@ -326,7 +326,7 @@ public class ListSubListTester<E> extends AbstractListTester<E> {
/**
* Returns the {@link Method} instance for {@link
- * #testSubList_originalListSetAffectsSubListLargeList()} ()} so that tests of {@link
+ * #testSubList_originalListSetAffectsSubListLargeList()} so that tests of {@link
* CopyOnWriteArrayList} can suppress them with {@code
* FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570631">Sun bug 6570631</a> is fixed.
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/MapMergeTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/MapMergeTester.java
index c001afa00..5fb9735ef 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/MapMergeTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/MapMergeTester.java
@@ -29,6 +29,7 @@ import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.lang.reflect.Method;
+import java.util.Hashtable;
import java.util.Map;
import junit.framework.AssertionFailedError;
import org.junit.Ignore;
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/MapPutIfAbsentTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/MapPutIfAbsentTester.java
index c9aa930eb..093b27cc5 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/MapPutIfAbsentTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/MapPutIfAbsentTester.java
@@ -26,6 +26,7 @@ import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Map;
+import java.util.Map.Entry;
import org.junit.Ignore;
/**
@@ -102,7 +103,7 @@ public class MapPutIfAbsentTester<K, V> extends AbstractMapTester<K, V> {
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
- public void testPutIfAbsent_nullValueUnsupported() {
+ public void testPutIfAbsent_nullValueUnsupportedAndKeyAbsent() {
try {
getMap().putIfAbsent(k3(), null);
fail("putIfAbsent(key, null) should throw");
@@ -110,12 +111,12 @@ public class MapPutIfAbsentTester<K, V> extends AbstractMapTester<K, V> {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
- "Should not contain null value after unsupported put(key, null)");
+ "Should not contain null value after unsupported putIfAbsent(key, null)");
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
- public void testPutIfAbsent_putWithNullValueUnsupported() {
+ public void testPutIfAbsent_nullValueUnsupportedAndKeyPresent() {
try {
getMap().putIfAbsent(k0(), null);
} catch (NullPointerException tolerated) {
@@ -124,4 +125,13 @@ public class MapPutIfAbsentTester<K, V> extends AbstractMapTester<K, V> {
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null after unsupported putIfAbsent(present, null)");
}
+
+ @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
+ public void testPut_nullValueSupported() {
+ Entry<K, V> nullValueEntry = entry(k3(), null);
+ assertNull(
+ "putIfAbsent(key, null) should return null",
+ getMap().putIfAbsent(nullValueEntry.getKey(), nullValueEntry.getValue()));
+ expectAdded(nullValueEntry);
+ }
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java b/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java
index c9a745d4a..b123f5bc5 100644
--- a/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/MapPutTester.java
@@ -28,6 +28,7 @@ import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -245,6 +246,7 @@ public class MapPutTester<K, V> extends AbstractMapTester<K, V> {
expectAdded(nullKeyValueEntry);
}
+ @CanIgnoreReturnValue
private V put(Entry<K, V> entry) {
return getMap().put(entry.getKey(), entry.getValue());
}
diff --git a/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java b/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java
new file mode 100644
index 000000000..fa9439065
--- /dev/null
+++ b/guava-testlib/src/com/google/common/collect/testing/testers/package-info.java
@@ -0,0 +1,2 @@
+@com.google.errorprone.annotations.CheckReturnValue
+package com.google.common.collect.testing.testers;
diff --git a/guava-testlib/src/com/google/common/escape/testing/package-info.java b/guava-testlib/src/com/google/common/escape/testing/package-info.java
index 869884734..6b5061469 100644
--- a/guava-testlib/src/com/google/common/escape/testing/package-info.java
+++ b/guava-testlib/src/com/google/common/escape/testing/package-info.java
@@ -17,7 +17,7 @@
/**
* Testing utilities for use in tests of {@code com.google.common.escape}.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java b/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
index 1e31bbfb4..1836b9ded 100644
--- a/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
+++ b/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java
@@ -20,8 +20,8 @@ import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.testing.AbstractPackageSanityTests.Chopper.suffix;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
@@ -101,11 +101,12 @@ import org.junit.Test;
* @author Ben Yu
* @since 14.0
*/
-@Beta
// TODO: Switch to JUnit 4 and use @Parameterized and @BeforeClass
// Note: @Test annotations are deliberate, as some subclasses specify @RunWith(JUnit4).
@GwtIncompatible
+@J2ktIncompatible
@J2ObjCIncompatible // com.google.common.reflect.ClassPath
+@ElementTypesAreNonnullByDefault
public abstract class AbstractPackageSanityTests extends TestCase {
/**
@@ -325,7 +326,7 @@ public abstract class AbstractPackageSanityTests extends TestCase {
/**
* Finds the classes not ending with a test suffix and not covered by an explicit test whose name
- * is {@code explicitTestName}.
+ * is {@code explicitTestNames}.
*/
@VisibleForTesting
List<Class<?>> findClassesToTest(
diff --git a/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java b/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java
index 1325d7f8c..0071feacf 100644
--- a/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java
+++ b/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java
@@ -19,6 +19,7 @@ package com.google.common.testing;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Defaults;
@@ -172,6 +173,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 12.0
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
public final class ArbitraryInstances {
private static final Ordering<Field> BY_FIELD_NAME =
@@ -359,7 +362,7 @@ public final class ArbitraryInstances {
}
if (type.isEnum()) {
T[] enumConstants = type.getEnumConstants();
- return (enumConstants.length == 0) ? null : enumConstants[0];
+ return (enumConstants == null || enumConstants.length == 0) ? null : enumConstants[0];
}
if (type.isArray()) {
return createEmptyArray(type);
@@ -506,11 +509,12 @@ public final class ArbitraryInstances {
}
// Always equal is a valid total ordering. And it works for any Object.
- private static final class AlwaysEqual extends Ordering<Object> implements Serializable {
+ private static final class AlwaysEqual extends Ordering<@Nullable Object>
+ implements Serializable {
private static final AlwaysEqual INSTANCE = new AlwaysEqual();
@Override
- public int compare(Object o1, Object o2) {
+ public int compare(@Nullable Object o1, @Nullable Object o2) {
return 0;
}
diff --git a/guava-testlib/src/com/google/common/testing/ClassSanityTester.java b/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
index 0c8daf08e..d327666fe 100644
--- a/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
+++ b/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
@@ -21,8 +21,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.testing.NullPointerTester.isNullable;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
@@ -41,6 +41,7 @@ import com.google.common.reflect.TypeToken;
import com.google.common.testing.NullPointerTester.Visibility;
import com.google.common.testing.RelationshipTester.Item;
import com.google.common.testing.RelationshipTester.ItemReporter;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@@ -78,8 +79,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Ben Yu
* @since 14.0
*/
-@Beta
@GwtIncompatible
+@J2ktIncompatible
public final class ClassSanityTester {
private static final Ordering<Invokable<?, ?>> BY_METHOD_NAME =
@@ -133,6 +134,7 @@ public final class ClassSanityTester {
* Object#equals} because more than one sample instances are needed for testing inequality. To set
* distinct values for equality testing, use {@link #setDistinctValues} instead.
*/
+ @CanIgnoreReturnValue
public <T> ClassSanityTester setDefault(Class<T> type, T value) {
nullPointerTester.setDefault(type, value);
defaultValues.putInstance(type, value);
@@ -154,6 +156,7 @@ public final class ClassSanityTester {
* @return this tester instance
* @since 17.0
*/
+ @CanIgnoreReturnValue
public <T> ClassSanityTester setDistinctValues(Class<T> type, T value1, T value2) {
checkNotNull(type);
checkNotNull(value1);
@@ -335,11 +338,13 @@ public final class ClassSanityTester {
* or factory method to be constructed.
*/
<T> @Nullable T instantiate(Class<T> cls)
- throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException,
+ throws ParameterNotInstantiableException,
+ IllegalAccessException,
+ InvocationTargetException,
FactoryMethodReturnsNullException {
if (cls.isEnum()) {
T[] constants = cls.getEnumConstants();
- if (constants.length > 0) {
+ if (constants != null && constants.length > 0) {
return constants[0];
} else {
return null;
@@ -427,6 +432,7 @@ public final class ClassSanityTester {
*
* @return this tester object
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester thatReturn(Class<?> returnType) {
this.returnTypeToTest = returnType;
return this;
@@ -440,6 +446,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testNulls() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
Object instance = instantiate(factory);
@@ -468,6 +475,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testEquals() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
try {
@@ -487,6 +495,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testSerializable() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
Object instance = instantiate(factory);
@@ -512,6 +521,7 @@ public final class ClassSanityTester {
*
* @return this tester
*/
+ @CanIgnoreReturnValue
public FactoryMethodReturnValueTester testEqualsAndSerializable() throws Exception {
for (Invokable<?, ?> factory : getFactoriesToTest()) {
try {
@@ -566,7 +576,7 @@ public final class ClassSanityTester {
IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException {
List<Parameter> params = factory.getParameters();
List<FreshValueGenerator> argGenerators = Lists.newArrayListWithCapacity(params.size());
- List<Object> args = Lists.newArrayListWithCapacity(params.size());
+ List<@Nullable Object> args = Lists.newArrayListWithCapacity(params.size());
for (Parameter param : params) {
FreshValueGenerator generator = newFreshValueGenerator();
argGenerators.add(generator);
@@ -705,9 +715,9 @@ public final class ClassSanityTester {
for (Invokable<?, ?> factory : factories) {
factory.setAccessible(true);
}
- // Sorts methods/constructors with least number of parameters first since it's likely easier to
- // fill dummy parameter values for them. Ties are broken by name then by the string form of the
- // parameter list.
+ // Sorts methods/constructors with the least number of parameters first since it's likely easier
+ // to fill dummy parameter values for them. Ties are broken by name then by the string form of
+ // the parameter list.
return BY_NUMBER_OF_PARAMETERS
.compound(BY_METHOD_NAME)
.compound(BY_PARAMETERS)
@@ -824,7 +834,7 @@ public final class ClassSanityTester {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof SerializableDummyProxy;
}
diff --git a/guava-testlib/src/com/google/common/testing/ClusterException.java b/guava-testlib/src/com/google/common/testing/ClusterException.java
index 7665ab1d4..2b8d4eb77 100644
--- a/guava-testlib/src/com/google/common/testing/ClusterException.java
+++ b/guava-testlib/src/com/google/common/testing/ClusterException.java
@@ -59,20 +59,21 @@ import java.util.Collections;
* @author Luiz-Otavio Zorzella
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
final class ClusterException extends RuntimeException {
- public final Collection<? extends Throwable> exceptions;
+ final Collection<? extends Throwable> exceptions;
private ClusterException(Collection<? extends Throwable> exceptions) {
super(
exceptions.size() + " exceptions were thrown. The first exception is listed as a cause.",
exceptions.iterator().next());
- ArrayList<Throwable> temp = new ArrayList<>(exceptions);
+ ArrayList<? extends Throwable> temp = new ArrayList<>(exceptions);
this.exceptions = Collections.unmodifiableCollection(temp);
}
- /** @see #create(Collection) */
- public static RuntimeException create(Throwable... exceptions) {
+ /** See {@link #create(Collection)}. */
+ static RuntimeException create(Throwable... exceptions) {
ArrayList<Throwable> temp = new ArrayList<>(Arrays.asList(exceptions));
return create(temp);
}
@@ -96,7 +97,7 @@ final class ClusterException extends RuntimeException {
* @throws NullPointerException if {@code exceptions} is null
* @throws IllegalArgumentException if {@code exceptions} is empty
*/
- public static RuntimeException create(Collection<? extends Throwable> exceptions) {
+ static RuntimeException create(Collection<? extends Throwable> exceptions) {
if (exceptions.size() == 0) {
throw new IllegalArgumentException("Can't create an ExceptionCollection with no exceptions");
}
diff --git a/guava-testlib/src/com/google/common/testing/CollectorTester.java b/guava-testlib/src/com/google/common/testing/CollectorTester.java
index ab6e544d8..656edbd41 100644
--- a/guava-testlib/src/com/google/common/testing/CollectorTester.java
+++ b/guava-testlib/src/com/google/common/testing/CollectorTester.java
@@ -20,10 +20,10 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
-import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.function.BiPredicate;
@@ -46,12 +46,15 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 21.0
*/
@GwtCompatible
-public final class CollectorTester<T, A, R> {
+@ElementTypesAreNonnullByDefault
+public final class CollectorTester<
+ T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object> {
/**
* Creates a {@code CollectorTester} for the specified {@code Collector}. The result of the {@code
- * Collector} will be compared to the expected value using {@link Object.equals}.
+ * Collector} will be compared to the expected value using {@link Object#equals}.
*/
- public static <T, A, R> CollectorTester<T, A, R> of(Collector<T, A, R> collector) {
+ public static <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
+ CollectorTester<T, A, R> of(Collector<T, A, R> collector) {
return of(collector, Objects::equals);
}
@@ -59,8 +62,9 @@ public final class CollectorTester<T, A, R> {
* Creates a {@code CollectorTester} for the specified {@code Collector}. The result of the {@code
* Collector} will be compared to the expected value using the specified {@code equivalence}.
*/
- public static <T, A, R> CollectorTester<T, A, R> of(
- Collector<T, A, R> collector, BiPredicate<? super R, ? super R> equivalence) {
+ public static <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
+ CollectorTester<T, A, R> of(
+ Collector<T, A, R> collector, BiPredicate<? super R, ? super R> equivalence) {
return new CollectorTester<>(collector, equivalence);
}
@@ -81,7 +85,8 @@ public final class CollectorTester<T, A, R> {
/** Get one accumulator and accumulate the elements into it sequentially. */
SEQUENTIAL {
@Override
- final <T, A, R> A result(Collector<T, A, R> collector, Iterable<T> inputs) {
+ final <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
+ A result(Collector<T, A, R> collector, Iterable<T> inputs) {
A accum = collector.supplier().get();
for (T input : inputs) {
collector.accumulator().accept(accum, input);
@@ -92,7 +97,8 @@ public final class CollectorTester<T, A, R> {
/** Get one accumulator for each element and merge the accumulators left-to-right. */
MERGE_LEFT_ASSOCIATIVE {
@Override
- final <T, A, R> A result(Collector<T, A, R> collector, Iterable<T> inputs) {
+ final <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
+ A result(Collector<T, A, R> collector, Iterable<T> inputs) {
A accum = collector.supplier().get();
for (T input : inputs) {
A newAccum = collector.supplier().get();
@@ -105,7 +111,8 @@ public final class CollectorTester<T, A, R> {
/** Get one accumulator for each element and merge the accumulators right-to-left. */
MERGE_RIGHT_ASSOCIATIVE {
@Override
- final <T, A, R> A result(Collector<T, A, R> collector, Iterable<T> inputs) {
+ final <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
+ A result(Collector<T, A, R> collector, Iterable<T> inputs) {
List<A> stack = new ArrayList<>();
for (T input : inputs) {
A newAccum = collector.supplier().get();
@@ -121,16 +128,17 @@ public final class CollectorTester<T, A, R> {
return pop(stack);
}
- <E> void push(List<E> stack, E value) {
+ <E extends @Nullable Object> void push(List<E> stack, E value) {
stack.add(value);
}
- <E> E pop(List<E> stack) {
+ <E extends @Nullable Object> E pop(List<E> stack) {
return stack.remove(stack.size() - 1);
}
};
- abstract <T, A, R> A result(Collector<T, A, R> collector, Iterable<T> inputs);
+ abstract <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
+ A result(Collector<T, A, R> collector, Iterable<T> inputs);
}
/**
@@ -138,7 +146,8 @@ public final class CollectorTester<T, A, R> {
* inputs, regardless of how the elements are divided.
*/
@SafeVarargs
- public final CollectorTester<T, A, R> expectCollects(@Nullable R expectedResult, T... inputs) {
+ @CanIgnoreReturnValue
+ public final CollectorTester<T, A, R> expectCollects(R expectedResult, T... inputs) {
List<T> list = Arrays.asList(inputs);
doExpectCollects(expectedResult, list);
if (collector.characteristics().contains(Collector.Characteristics.UNORDERED)) {
@@ -148,8 +157,8 @@ public final class CollectorTester<T, A, R> {
return this;
}
- private void doExpectCollects(@Nullable R expectedResult, List<T> inputs) {
- for (CollectStrategy scheme : EnumSet.allOf(CollectStrategy.class)) {
+ private void doExpectCollects(R expectedResult, List<T> inputs) {
+ for (CollectStrategy scheme : CollectStrategy.values()) {
A finalAccum = scheme.result(collector, inputs);
if (collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
assertEquivalent(expectedResult, (R) finalAccum);
@@ -158,7 +167,7 @@ public final class CollectorTester<T, A, R> {
}
}
- private void assertEquivalent(@Nullable R expected, @Nullable R actual) {
+ private void assertEquivalent(R expected, R actual) {
assertTrue(
"Expected " + expected + " got " + actual + " modulo equivalence " + equivalence,
equivalence.test(expected, actual));
diff --git a/guava-testlib/src/com/google/common/testing/DummyProxy.java b/guava-testlib/src/com/google/common/testing/DummyProxy.java
index 85e229d51..7b2525c72 100644
--- a/guava-testlib/src/com/google/common/testing/DummyProxy.java
+++ b/guava-testlib/src/com/google/common/testing/DummyProxy.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.testing.NullPointerTester.isNullable;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.reflect.AbstractInvocationHandler;
@@ -30,6 +31,7 @@ import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Generates a dummy interface proxy that simply returns a dummy value for each method.
@@ -37,6 +39,8 @@ import java.util.Set;
* @author Ben Yu
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
abstract class DummyProxy {
/**
@@ -59,7 +63,7 @@ abstract class DummyProxy {
}
/** Returns the dummy return value for {@code returnType}. */
- abstract <R> R dummyReturnValue(TypeToken<R> returnType);
+ abstract <R> @Nullable R dummyReturnValue(TypeToken<R> returnType);
private class DummyHandler extends AbstractInvocationHandler implements Serializable {
private final TypeToken<?> interfaceType;
@@ -69,7 +73,7 @@ abstract class DummyProxy {
}
@Override
- protected Object handleInvocation(Object proxy, Method method, Object[] args) {
+ protected @Nullable Object handleInvocation(Object proxy, Method method, Object[] args) {
Invokable<?, ?> invokable = interfaceType.method(method);
ImmutableList<Parameter> params = invokable.getParameters();
for (int i = 0; i < args.length; i++) {
@@ -87,7 +91,7 @@ abstract class DummyProxy {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof DummyHandler) {
DummyHandler that = (DummyHandler) obj;
return identity().equals(that.identity());
diff --git a/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java b/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java
new file mode 100644
index 000000000..1362176b5
--- /dev/null
+++ b/guava-testlib/src/com/google/common/testing/ElementTypesAreNonnullByDefault.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2021 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.testing;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.google.common.annotations.GwtCompatible;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import javax.annotation.Nonnull;
+import javax.annotation.meta.TypeQualifierDefault;
+
+/**
+ * Marks all "top-level" types as non-null in a way that is recognized by Kotlin. Note that this
+ * unfortunately includes type-variable usages, so we also provide {@link ParametricNullness} to
+ * "undo" it as best we can.
+ */
+@GwtCompatible
+@Retention(RUNTIME)
+@Target(TYPE)
+@TypeQualifierDefault({FIELD, METHOD, PARAMETER})
+@Nonnull
+@interface ElementTypesAreNonnullByDefault {}
diff --git a/guava-testlib/src/com/google/common/testing/EqualsTester.java b/guava-testlib/src/com/google/common/testing/EqualsTester.java
index 9c93c9a49..d4484702a 100644
--- a/guava-testlib/src/com/google/common/testing/EqualsTester.java
+++ b/guava-testlib/src/com/google/common/testing/EqualsTester.java
@@ -22,10 +22,12 @@ import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import java.util.ArrayList;
import java.util.List;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester for equals() and hashCode() methods of a class.
@@ -74,6 +76,7 @@ import java.util.List;
* @since 10.0
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public final class EqualsTester {
private static final int REPETITIONS = 3;
@@ -93,13 +96,23 @@ public final class EqualsTester {
* Adds {@code equalityGroup} with objects that are supposed to be equal to each other and not
* equal to any other equality groups added to this tester.
*/
- public EqualsTester addEqualityGroup(Object... equalityGroup) {
+ @CanIgnoreReturnValue
+ public EqualsTester addEqualityGroup(@Nullable Object @Nullable ... equalityGroup) {
checkNotNull(equalityGroup);
- equalityGroups.add(ImmutableList.copyOf(equalityGroup));
+ List<Object> list = new ArrayList<>(equalityGroup.length);
+ for (int i = 0; i < equalityGroup.length; i++) {
+ Object element = equalityGroup[i];
+ if (element == null) {
+ throw new NullPointerException("at index " + i);
+ }
+ list.add(element);
+ }
+ equalityGroups.add(list);
return this;
}
/** Run tests on equals method, throwing a failure on an invalid test */
+ @CanIgnoreReturnValue
public EqualsTester testEquals() {
RelationshipTester<Object> delegate =
new RelationshipTester<>(
diff --git a/guava-testlib/src/com/google/common/testing/EquivalenceTester.java b/guava-testlib/src/com/google/common/testing/EquivalenceTester.java
index 8de2625d0..ec34752c5 100644
--- a/guava-testlib/src/com/google/common/testing/EquivalenceTester.java
+++ b/guava-testlib/src/com/google/common/testing/EquivalenceTester.java
@@ -25,6 +25,7 @@ import com.google.common.base.Equivalence;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.testing.RelationshipTester.ItemReporter;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.List;
/**
@@ -49,6 +50,7 @@ import java.util.List;
* @since 10.0
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public final class EquivalenceTester<T> {
private static final int REPETITIONS = 3;
@@ -69,11 +71,13 @@ public final class EquivalenceTester<T> {
* Adds a group of objects that are supposed to be equivalent to each other and not equivalent to
* objects in any other equivalence group added to this tester.
*/
+ @CanIgnoreReturnValue
public EquivalenceTester<T> addEquivalenceGroup(T first, T... rest) {
addEquivalenceGroup(Lists.asList(first, rest));
return this;
}
+ @CanIgnoreReturnValue
public EquivalenceTester<T> addEquivalenceGroup(Iterable<T> group) {
delegate.addRelatedGroup(group);
items.addAll(ImmutableList.copyOf(group));
@@ -81,6 +85,7 @@ public final class EquivalenceTester<T> {
}
/** Run tests on equivalence methods, throwing a failure on an invalid test */
+ @CanIgnoreReturnValue
public EquivalenceTester<T> test() {
for (int run = 0; run < REPETITIONS; run++) {
testItems();
diff --git a/guava-testlib/src/com/google/common/testing/FakeTicker.java b/guava-testlib/src/com/google/common/testing/FakeTicker.java
index d18e6bce7..2c3e798ff 100644
--- a/guava-testlib/src/com/google/common/testing/FakeTicker.java
+++ b/guava-testlib/src/com/google/common/testing/FakeTicker.java
@@ -20,7 +20,9 @@ import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ticker;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@@ -35,6 +37,7 @@ import java.util.concurrent.atomic.AtomicLong;
* @author Jige Yu
* @since 10.0
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible
public class FakeTicker extends Ticker {
@@ -43,12 +46,14 @@ public class FakeTicker extends Ticker {
/** Advances the ticker value by {@code time} in {@code timeUnit}. */
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public FakeTicker advance(long time, TimeUnit timeUnit) {
return advance(timeUnit.toNanos(time));
}
/** Advances the ticker value by {@code nanoseconds}. */
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public FakeTicker advance(long nanoseconds) {
nanos.addAndGet(nanoseconds);
return this;
@@ -60,6 +65,8 @@ public class FakeTicker extends Ticker {
* @since 28.0
*/
@GwtIncompatible
+ @J2ktIncompatible
+ @CanIgnoreReturnValue
public FakeTicker advance(java.time.Duration duration) {
return advance(duration.toNanos());
}
@@ -71,6 +78,7 @@ public class FakeTicker extends Ticker {
* queried.
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public FakeTicker setAutoIncrementStep(long autoIncrementStep, TimeUnit timeUnit) {
checkArgument(autoIncrementStep >= 0, "May not auto-increment by a negative amount");
this.autoIncrementStepNanos = timeUnit.toNanos(autoIncrementStep);
@@ -86,6 +94,8 @@ public class FakeTicker extends Ticker {
* @since 28.0
*/
@GwtIncompatible
+ @J2ktIncompatible
+ @CanIgnoreReturnValue
public FakeTicker setAutoIncrementStep(java.time.Duration autoIncrementStep) {
return setAutoIncrementStep(autoIncrementStep.toNanos(), TimeUnit.NANOSECONDS);
}
diff --git a/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java b/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java
index 605d3a055..c0d2c6a01 100644
--- a/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java
+++ b/guava-testlib/src/com/google/common/testing/ForwardingWrapperTester.java
@@ -23,17 +23,20 @@ import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Reflection;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester to ensure forwarding wrapper works by delegating calls to the corresponding method with
@@ -53,6 +56,8 @@ import java.util.concurrent.atomic.AtomicInteger;
* @since 14.0
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
public final class ForwardingWrapperTester {
private boolean testsEquals = false;
@@ -61,6 +66,7 @@ public final class ForwardingWrapperTester {
* Asks for {@link Object#equals} and {@link Object#hashCode} to be tested. That is, forwarding
* wrappers of equal instances should be equal.
*/
+ @CanIgnoreReturnValue
public ForwardingWrapperTester includingEquals() {
this.testsEquals = true;
return this;
@@ -171,9 +177,9 @@ public final class ForwardingWrapperTester {
wrapperFunction.apply(proxy).toString());
}
- private static Object[] getParameterValues(Method method) {
+ private static @Nullable Object[] getParameterValues(Method method) {
FreshValueGenerator paramValues = new FreshValueGenerator();
- List<Object> passedArgs = Lists.newArrayList();
+ List<@Nullable Object> passedArgs = Lists.newArrayList();
for (Class<?> paramType : method.getParameterTypes()) {
passedArgs.add(paramValues.generateFresh(paramType));
}
@@ -185,8 +191,8 @@ public final class ForwardingWrapperTester {
private final Class<T> interfaceType;
private final Method method;
- private final Object[] passedArgs;
- private final Object returnValue;
+ private final @Nullable Object[] passedArgs;
+ private final @Nullable Object returnValue;
private final AtomicInteger called = new AtomicInteger();
InteractionTester(Class<T> interfaceType, Method method) {
@@ -197,8 +203,8 @@ public final class ForwardingWrapperTester {
}
@Override
- protected Object handleInvocation(Object p, Method calledMethod, Object[] args)
- throws Throwable {
+ protected @Nullable Object handleInvocation(
+ Object p, Method calledMethod, @Nullable Object[] args) throws Throwable {
assertEquals(method, calledMethod);
assertEquals(method + " invoked more than once.", 0, called.get());
for (int i = 0; i < passedArgs.length; i++) {
diff --git a/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java b/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
index bb51e408b..0e0d9b13b 100644
--- a/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
+++ b/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Equivalence;
@@ -130,6 +131,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Ben Yu
*/
@GwtIncompatible
+@J2ktIncompatible
class FreshValueGenerator {
private static final ImmutableMap<Class<?>, Method> GENERATORS;
@@ -201,7 +203,7 @@ class FreshValueGenerator {
* Generates an instance for {@code type} using the current {@link #freshness}. The generated
* instance may or may not be unique across different calls.
*/
- private Object generate(TypeToken<?> type) {
+ private @Nullable Object generate(TypeToken<?> type) {
Class<?> rawType = type.getRawType();
List<Object> samples = sampleInstances.get(rawType);
Object sample = pickInstance(samples, null);
@@ -212,7 +214,7 @@ class FreshValueGenerator {
return pickInstance(rawType.getEnumConstants(), null);
}
if (type.isArray()) {
- TypeToken<?> componentType = type.getComponentType();
+ TypeToken<?> componentType = checkNotNull(type.getComponentType());
Object array = Array.newInstance(componentType.getRawType(), 1);
Array.set(array, 0, generate(componentType));
return array;
@@ -258,7 +260,7 @@ class FreshValueGenerator {
return defaultGenerate(rawType);
}
- private <T> T defaultGenerate(Class<T> rawType) {
+ private <T> @Nullable T defaultGenerate(Class<T> rawType) {
if (rawType.isInterface()) {
// always create a new proxy
return newProxy(rawType);
@@ -291,7 +293,7 @@ class FreshValueGenerator {
}
@Override
- protected Object handleInvocation(Object proxy, Method method, Object[] args) {
+ protected Object handleInvocation(Object proxy, Method method, @Nullable Object[] args) {
return interfaceMethodCalled(interfaceType, method);
}
@@ -647,7 +649,7 @@ class FreshValueGenerator {
}
@Generates
- <T> Ordering<T> generateOrdering() {
+ <T extends @Nullable Object> Ordering<T> generateOrdering() {
return new Ordering<T>() {
@Override
public int compare(T left, T right) {
@@ -930,14 +932,12 @@ class FreshValueGenerator {
}
@Generates
- static <R, C, V> Table<R, C, V> generateTable(
- @Nullable R row, @Nullable C column, @Nullable V value) {
+ static <R, C, V> Table<R, C, V> generateTable(R row, C column, V value) {
return generateHashBasedTable(row, column, value);
}
@Generates
- static <R, C, V> HashBasedTable<R, C, V> generateHashBasedTable(
- @Nullable R row, @Nullable C column, @Nullable V value) {
+ static <R, C, V> HashBasedTable<R, C, V> generateHashBasedTable(R row, C column, V value) {
HashBasedTable<R, C, V> table = HashBasedTable.create();
table.put(row, column, value);
return table;
diff --git a/guava-testlib/src/com/google/common/testing/GcFinalization.java b/guava-testlib/src/com/google/common/testing/GcFinalization.java
index da6aa2211..cf3409ac3 100644
--- a/guava-testlib/src/com/google/common/testing/GcFinalization.java
+++ b/guava-testlib/src/com/google/common/testing/GcFinalization.java
@@ -19,6 +19,7 @@ package com.google.common.testing;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.lang.ref.WeakReference;
@@ -103,7 +104,9 @@ import java.util.concurrent.TimeoutException;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@J2ObjCIncompatible // gc
+@ElementTypesAreNonnullByDefault
public final class GcFinalization {
private GcFinalization() {}
diff --git a/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java b/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java
new file mode 100644
index 000000000..2203162bf
--- /dev/null
+++ b/guava-testlib/src/com/google/common/testing/IgnoreJRERequirement.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2019 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.testing;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@interface IgnoreJRERequirement {}
diff --git a/guava-testlib/src/com/google/common/testing/NullPointerTester.java b/guava-testlib/src/com/google/common/testing/NullPointerTester.java
index 3eb317605..5b14fa5eb 100644
--- a/guava-testlib/src/com/google/common/testing/NullPointerTester.java
+++ b/guava-testlib/src/com/google/common/testing/NullPointerTester.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Objects;
import com.google.common.collect.ClassToInstanceMap;
@@ -32,6 +33,7 @@ import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
@@ -45,7 +47,6 @@ import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
-import java.util.function.Function;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -54,7 +55,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* A test utility that verifies that your methods and constructors throw {@link
* NullPointerException} or {@link UnsupportedOperationException} whenever null is passed to a
* parameter whose declaration or type isn't annotated with an annotation with the simple name
- * {@code Nullable}, {@code CheckForNull}, {@link NullableType}, or {@link NullableDecl}.
+ * {@code Nullable}, {@code CheckForNull}, {@code NullableType}, or {@code NullableDecl}.
*
* <p>The tested methods and constructors are invoked -- each time with one parameter being null and
* the rest not null -- and the test fails if no expected exception is thrown. {@code
@@ -68,6 +69,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 10.0
*/
@GwtIncompatible
+@J2ktIncompatible
+@ElementTypesAreNonnullByDefault
public final class NullPointerTester {
private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create();
@@ -75,10 +78,27 @@ public final class NullPointerTester {
private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE;
+ public NullPointerTester() {
+ try {
+ /*
+ * Converter.apply has a non-nullable parameter type but doesn't throw for null arguments. For
+ * more information, see the comments in that class.
+ *
+ * We already know that that's how it behaves, and subclasses of Converter can't change that
+ * behavior. So there's no sense in making all subclass authors exclude the method from any
+ * NullPointerTester tests that they have.
+ */
+ ignoredMembers.add(Converter.class.getMethod("apply", Object.class));
+ } catch (NoSuchMethodException shouldBeImpossible) {
+ // OK, fine: If it doesn't exist, then there's chance that we're going to be asked to test it.
+ }
+ }
+
/**
* Sets a default value that can be used for any parameter of type {@code type}. Returns this
* object.
*/
+ @CanIgnoreReturnValue
public <T> NullPointerTester setDefault(Class<T> type, T value) {
defaults.putInstance(type, checkNotNull(value));
return this;
@@ -89,6 +109,7 @@ public final class NullPointerTester {
*
* @since 13.0
*/
+ @CanIgnoreReturnValue
public NullPointerTester ignore(Method method) {
ignoredMembers.add(checkNotNull(method));
return this;
@@ -99,6 +120,7 @@ public final class NullPointerTester {
*
* @since 22.0
*/
+ @CanIgnoreReturnValue
public NullPointerTester ignore(Constructor<?> constructor) {
ignoredMembers.add(checkNotNull(constructor));
return this;
@@ -306,7 +328,7 @@ public final class NullPointerTester {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof Signature) {
Signature that = (Signature) obj;
return name.equals(that.name) && parameterTypes.equals(that.parameterTypes);
@@ -329,11 +351,18 @@ public final class NullPointerTester {
* static
*/
private void testParameter(
- Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
+ @Nullable Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
+ /*
+ * com.google.common is starting to rely on type-use annotations, which aren't visible under
+ * Android VMs. So we skip testing there.
+ */
+ if (isAndroid() && Reflection.getPackageName(testedClass).startsWith("com.google.common")) {
+ return;
+ }
if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
return; // there's nothing to test
}
- Object[] params = buildParamList(invokable, paramIndex);
+ @Nullable Object[] params = buildParamList(invokable, paramIndex);
try {
@SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong.
Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
@@ -369,9 +398,10 @@ public final class NullPointerTester {
}
}
- private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
+ private @Nullable Object[] buildParamList(
+ Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
ImmutableList<Parameter> params = invokable.getParameters();
- Object[] args = new Object[params.size()];
+ @Nullable Object[] args = new Object[params.size()];
for (int i = 0; i < args.length; i++) {
Parameter param = params.get(i);
@@ -387,7 +417,7 @@ public final class NullPointerTester {
return args;
}
- private <T> T getDefaultValue(TypeToken<T> type) {
+ private <T> @Nullable T getDefaultValue(TypeToken<T> type) {
// We assume that all defaults are generics-safe, even if they aren't,
// we take the risk.
@SuppressWarnings("unchecked")
@@ -455,7 +485,7 @@ public final class NullPointerTester {
private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
return new DummyProxy() {
@Override
- <R> R dummyReturnValue(TypeToken<R> returnType) {
+ <R> @Nullable R dummyReturnValue(TypeToken<R> returnType) {
return getDefaultValue(returnType);
}
}.newProxy(type);
@@ -474,37 +504,17 @@ public final class NullPointerTester {
}
private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES =
- ImmutableSet.of(
- "CheckForNull", "Nullable", "NullableDecl", "NullableType", "ParametricNullness");
+ ImmutableSet.of("CheckForNull", "Nullable", "NullableDecl", "NullableType");
static boolean isNullable(Invokable<?, ?> invokable) {
- return isNullable(invokable.getAnnotatedReturnType().getAnnotations())
- || isNullable(invokable.getAnnotations());
+ return NULLNESS_ANNOTATION_READER.isNullable(invokable);
}
static boolean isNullable(Parameter param) {
- return isNullable(param.getAnnotatedType().getAnnotations())
- || isNullable(param.getAnnotations())
- || isNullableTypeVariable(param.getAnnotatedType().getType());
- }
-
- private static boolean isNullableTypeVariable(Type type) {
- if (!(type instanceof TypeVariable)) {
- return false;
- }
- TypeVariable<?> var = (TypeVariable<?>) type;
- AnnotatedType[] bounds = GET_ANNOTATED_BOUNDS.apply(var);
- for (AnnotatedType bound : bounds) {
- // Until Java 15, the isNullableTypeVariable case here won't help:
- // https://bugs.openjdk.java.net/browse/JDK-8202469
- if (isNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) {
- return true;
- }
- }
- return false;
+ return NULLNESS_ANNOTATION_READER.isNullable(param);
}
- private static boolean isNullable(Annotation[] annotations) {
+ private static boolean containsNullable(Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) {
return true;
@@ -513,27 +523,6 @@ public final class NullPointerTester {
return false;
}
- // This is currently required because of j2objc restrictions.
- private static final Function<TypeVariable<?>, AnnotatedType[]> GET_ANNOTATED_BOUNDS =
- initGetAnnotatedBounds();
-
- private static Function<TypeVariable<?>, AnnotatedType[]> initGetAnnotatedBounds() {
- AnnotatedType[] noBounds = new AnnotatedType[0];
- Method getAnnotatedBounds;
- try {
- getAnnotatedBounds = TypeVariable.class.getMethod("getAnnotatedBounds");
- } catch (ReflectiveOperationException e) {
- return v -> noBounds;
- }
- return v -> {
- try {
- return (AnnotatedType[]) getAnnotatedBounds.invoke(v);
- } catch (ReflectiveOperationException e) {
- return noBounds;
- }
- };
- }
-
private boolean isIgnored(Member member) {
return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member);
}
@@ -597,4 +586,87 @@ public final class NullPointerTester {
public abstract boolean isExpectedType(Throwable cause);
}
+
+ private static boolean annotatedTypeExists() {
+ try {
+ Class.forName("java.lang.reflect.AnnotatedType");
+ } catch (ClassNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
+
+ private static final NullnessAnnotationReader NULLNESS_ANNOTATION_READER =
+ annotatedTypeExists()
+ ? NullnessAnnotationReader.FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS
+ : NullnessAnnotationReader.FROM_DECLARATION_ANNOTATIONS_ONLY;
+
+ /**
+ * Looks for declaration nullness annotations and, if supported, type-use nullness annotations.
+ *
+ * <p>Under Android VMs, the methods for retrieving type-use annotations don't exist. This means
+ * that {@link NullPointerException} may misbehave under Android when used on classes that rely on
+ * type-use annotations.
+ *
+ * <p>Under j2objc, the necessary APIs exist, but some (perhaps all) return stub values, like
+ * empty arrays. Presumably {@link NullPointerException} could likewise misbehave under j2objc,
+ * but I don't know that anyone uses it there, anyway.
+ */
+ private enum NullnessAnnotationReader {
+ // Usages (which are unsafe only for Android) are guarded by the annotatedTypeExists() check.
+ @SuppressWarnings({"Java7ApiChecker", "AndroidApiChecker", "DoNotCall", "deprecation"})
+ FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS {
+ @Override
+ @IgnoreJRERequirement
+ boolean isNullable(Invokable<?, ?> invokable) {
+ return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(invokable)
+ || containsNullable(invokable.getAnnotatedReturnType().getAnnotations());
+ // TODO(cpovirk): Should we also check isNullableTypeVariable?
+ }
+
+ @Override
+ @IgnoreJRERequirement
+ boolean isNullable(Parameter param) {
+ return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(param)
+ || containsNullable(param.getAnnotatedType().getAnnotations())
+ || isNullableTypeVariable(param.getAnnotatedType().getType());
+ }
+
+ @IgnoreJRERequirement
+ boolean isNullableTypeVariable(Type type) {
+ if (!(type instanceof TypeVariable)) {
+ return false;
+ }
+ TypeVariable<?> typeVar = (TypeVariable<?>) type;
+ for (AnnotatedType bound : typeVar.getAnnotatedBounds()) {
+ // Until Java 15, the isNullableTypeVariable case here won't help:
+ // https://bugs.openjdk.java.net/browse/JDK-8202469
+ if (containsNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) {
+ return true;
+ }
+ }
+ return false;
+ }
+ },
+ FROM_DECLARATION_ANNOTATIONS_ONLY {
+ @Override
+ boolean isNullable(Invokable<?, ?> invokable) {
+ return containsNullable(invokable.getAnnotations());
+ }
+
+ @Override
+ boolean isNullable(Parameter param) {
+ return containsNullable(param.getAnnotations());
+ }
+ };
+
+ abstract boolean isNullable(Invokable<?, ?> invokable);
+
+ abstract boolean isNullable(Parameter param);
+ }
+
+ private static boolean isAndroid() {
+ // Arguably it would make more sense to test "can we see type-use annotations" directly....
+ return checkNotNull(System.getProperty("java.runtime.name", "")).contains("Android");
+ }
}
diff --git a/guava-testlib/src/com/google/common/testing/Platform.java b/guava-testlib/src/com/google/common/testing/Platform.java
index b107966ec..bbad5598d 100644
--- a/guava-testlib/src/com/google/common/testing/Platform.java
+++ b/guava-testlib/src/com/google/common/testing/Platform.java
@@ -31,6 +31,7 @@ import java.io.ObjectOutputStream;
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
final class Platform {
/** Serializes and deserializes the specified object. */
@SuppressWarnings("unchecked")
diff --git a/guava-testlib/src/com/google/common/testing/RelationshipTester.java b/guava-testlib/src/com/google/common/testing/RelationshipTester.java
index d5b9b6a18..d1caedd4e 100644
--- a/guava-testlib/src/com/google/common/testing/RelationshipTester.java
+++ b/guava-testlib/src/com/google/common/testing/RelationshipTester.java
@@ -22,6 +22,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.List;
import junit.framework.AssertionFailedError;
@@ -32,6 +33,7 @@ import junit.framework.AssertionFailedError;
* @author Gregory Kick
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
final class RelationshipTester<T> {
static class ItemReporter {
@@ -66,6 +68,7 @@ final class RelationshipTester<T> {
}
// TODO(cpovirk): should we reject null items, since the tests already check null automatically?
+ @CanIgnoreReturnValue
public RelationshipTester<T> addRelatedGroup(Iterable<? extends T> group) {
groups.add(ImmutableList.copyOf(group));
return this;
diff --git a/guava-testlib/src/com/google/common/testing/SerializableTester.java b/guava-testlib/src/com/google/common/testing/SerializableTester.java
index c4e6d236e..c2f8cc169 100644
--- a/guava-testlib/src/com/google/common/testing/SerializableTester.java
+++ b/guava-testlib/src/com/google/common/testing/SerializableTester.java
@@ -17,6 +17,7 @@
package com.google.common.testing;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
@@ -32,6 +33,7 @@ import junit.framework.AssertionFailedError;
* @since 10.0
*/
@GwtCompatible // but no-op!
+@ElementTypesAreNonnullByDefault
public final class SerializableTester {
private SerializableTester() {}
@@ -50,6 +52,7 @@ public final class SerializableTester {
* @throws RuntimeException if the specified object was not successfully serialized or
* deserialized
*/
+ @CanIgnoreReturnValue
public static <T> T reserialize(T object) {
return Platform.reserialize(object);
}
@@ -81,6 +84,7 @@ public final class SerializableTester {
* @throws AssertionFailedError if the re-serialized object is not equal to the original object,
* or if the hashcodes are different.
*/
+ @CanIgnoreReturnValue
public static <T> T reserializeAndAssert(T object) {
T copy = reserialize(object);
new EqualsTester().addEqualityGroup(object, copy).testEquals();
diff --git a/guava-testlib/src/com/google/common/testing/SloppyTearDown.java b/guava-testlib/src/com/google/common/testing/SloppyTearDown.java
index 95ff34e33..10d9dc04e 100644
--- a/guava-testlib/src/com/google/common/testing/SloppyTearDown.java
+++ b/guava-testlib/src/com/google/common/testing/SloppyTearDown.java
@@ -16,7 +16,6 @@
package com.google.common.testing;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -30,8 +29,8 @@ import java.util.logging.Logger;
* @author Luiz-Otavio Zorzella
* @since 10.0
*/
-@Beta
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public abstract class SloppyTearDown implements TearDown {
private static final Logger logger = Logger.getLogger(SloppyTearDown.class.getName());
diff --git a/guava-testlib/src/com/google/common/testing/TearDown.java b/guava-testlib/src/com/google/common/testing/TearDown.java
index 9582525a5..0259a1f3b 100644
--- a/guava-testlib/src/com/google/common/testing/TearDown.java
+++ b/guava-testlib/src/com/google/common/testing/TearDown.java
@@ -16,7 +16,6 @@
package com.google.common.testing;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
@@ -25,9 +24,9 @@ import com.google.common.annotations.GwtCompatible;
* @author Kevin Bourrillion
* @since 10.0
*/
-@Beta
@FunctionalInterface
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public interface TearDown {
/**
* Performs a <b>single</b> tear-down operation. See test-libraries-for-java's {@code
diff --git a/guava-testlib/src/com/google/common/testing/TearDownAccepter.java b/guava-testlib/src/com/google/common/testing/TearDownAccepter.java
index bad1f1997..ec4319bab 100644
--- a/guava-testlib/src/com/google/common/testing/TearDownAccepter.java
+++ b/guava-testlib/src/com/google/common/testing/TearDownAccepter.java
@@ -16,9 +16,8 @@
package com.google.common.testing;
-import com.google.common.annotations.Beta;
-import com.google.errorprone.annotations.DoNotMock;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.DoNotMock;
/**
* Any object which can accept registrations of {@link TearDown} instances.
@@ -26,9 +25,9 @@ import com.google.common.annotations.GwtCompatible;
* @author Kevin Bourrillion
* @since 10.0
*/
-@Beta
@DoNotMock("Implement with a lambda")
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public interface TearDownAccepter {
/**
* Registers a TearDown implementor which will be run after the test proper.
diff --git a/guava-testlib/src/com/google/common/testing/TearDownStack.java b/guava-testlib/src/com/google/common/testing/TearDownStack.java
index bab025a61..c22b54c40 100644
--- a/guava-testlib/src/com/google/common/testing/TearDownStack.java
+++ b/guava-testlib/src/com/google/common/testing/TearDownStack.java
@@ -18,7 +18,6 @@ package com.google.common.testing;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.errorprone.annotations.concurrent.GuardedBy;
@@ -36,8 +35,8 @@ import java.util.logging.Logger;
* @author Kevin Bourrillion
* @since 10.0
*/
-@Beta
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public class TearDownStack implements TearDownAccepter {
private static final Logger logger = Logger.getLogger(TearDownStack.class.getName());
diff --git a/guava-testlib/src/com/google/common/testing/TestLogHandler.java b/guava-testlib/src/com/google/common/testing/TestLogHandler.java
index 41dca2ec8..e481a2f19 100644
--- a/guava-testlib/src/com/google/common/testing/TestLogHandler.java
+++ b/guava-testlib/src/com/google/common/testing/TestLogHandler.java
@@ -16,6 +16,7 @@
package com.google.common.testing;
+
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.Collections;
@@ -52,6 +53,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 10.0
*/
@GwtCompatible
+@ElementTypesAreNonnullByDefault
public class TestLogHandler extends Handler {
/** We will keep a private list of all logged records */
private final List<LogRecord> list = new ArrayList<>();
@@ -59,7 +61,9 @@ public class TestLogHandler extends Handler {
/** Adds the most recently logged record to our list. */
@Override
public synchronized void publish(@Nullable LogRecord record) {
- list.add(record);
+ if (record != null) {
+ list.add(record);
+ }
}
@Override
diff --git a/guava-testlib/src/com/google/common/testing/package-info.java b/guava-testlib/src/com/google/common/testing/package-info.java
index e6762f98c..3c0849ffc 100644
--- a/guava-testlib/src/com/google/common/testing/package-info.java
+++ b/guava-testlib/src/com/google/common/testing/package-info.java
@@ -15,8 +15,9 @@
*/
/**
- * This package contains testing utilities. It is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Testing utilities. This package is a part of the open-source <a
+ * href="https://github.com/google/guava">Guava</a> library.
*/
+@com.google.errorprone.annotations.CheckReturnValue
@javax.annotation.ParametersAreNonnullByDefault
package com.google.common.testing;
diff --git a/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java b/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java
index b5bec2c09..abe419e05 100644
--- a/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java
+++ b/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java
@@ -19,7 +19,6 @@ package com.google.common.util.concurrent.testing;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.CancellationException;
@@ -31,6 +30,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Abstract test case parent for anything implementing {@link ListenableFuture}. Tests the two get
@@ -39,7 +39,6 @@ import junit.framework.TestCase;
* @author Sven Mawson
* @since 10.0
*/
-@Beta
@GwtIncompatible
public abstract class AbstractListenableFutureTest extends TestCase {
@@ -63,7 +62,7 @@ public abstract class AbstractListenableFutureTest extends TestCase {
/** Constructs a listenable future with a value available after the latch has counted down. */
protected abstract <V> ListenableFuture<V> createListenableFuture(
- V value, Exception except, CountDownLatch waitOn);
+ V value, @Nullable Exception except, CountDownLatch waitOn);
/** Tests that the {@link Future#get()} method blocks until a value is available. */
public void testGetBlocksUntilValueAvailable() throws Throwable {
diff --git a/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java b/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java
index a2fe4f447..87eb73aa9 100644
--- a/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java
+++ b/guava-testlib/src/com/google/common/util/concurrent/testing/MockFutureListener.java
@@ -19,7 +19,6 @@ package com.google.common.util.concurrent.testing;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.CountDownLatch;
@@ -32,7 +31,6 @@ import junit.framework.Assert;
* @author Nishant Thakkar
* @since 10.0
*/
-@Beta
@GwtIncompatible
public class MockFutureListener implements Runnable {
private final CountDownLatch countDownLatch;
diff --git a/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java b/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java
index dc2c40d37..ffbf3842f 100644
--- a/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java
+++ b/guava-testlib/src/com/google/common/util/concurrent/testing/TestingExecutors.java
@@ -30,7 +30,10 @@ import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
/**
@@ -39,7 +42,6 @@ import java.util.concurrent.TimeUnit;
* @author Chris Nokleberg
* @since 14.0
*/
-@Beta
@GwtIncompatible
public final class TestingExecutors {
private TestingExecutors() {}
@@ -88,9 +90,10 @@ public final class TestingExecutors {
* invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the tasks may
* already have been executed.
*
- * @since 15.0
+ * @since 32.0.0 (taking the place of a method with a different return type from 15.0)
*/
- public static SameThreadScheduledExecutorService sameThreadScheduledExecutor() {
+ @Beta
+ public static ListeningScheduledExecutorService sameThreadScheduledExecutor() {
return new SameThreadScheduledExecutorService();
}
diff --git a/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java b/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java
index 4d617d64d..92ee857d9 100644
--- a/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java
+++ b/guava-testlib/test/com/google/common/collect/testing/FeatureSpecificTestSuiteBuilderTest.java
@@ -22,32 +22,16 @@ import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestResult;
-import org.junit.Ignore;
-/** @author Max Ross */
+/**
+ * @author Max Ross
+ */
public class FeatureSpecificTestSuiteBuilderTest extends TestCase {
-
- private static boolean testWasRun;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- testWasRun = false;
- }
-
- @Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
- public static final class MyAbstractTester extends AbstractTester<Void> {
- public void testNothing() {
- testWasRun = true;
- }
- }
-
private static final class MyTestSuiteBuilder
extends FeatureSpecificTestSuiteBuilder<MyTestSuiteBuilder, String> {
-
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
- return Collections.<Class<? extends AbstractTester>>singletonList(MyAbstractTester.class);
+ return Collections.<Class<? extends AbstractTester>>singletonList(MyTester.class);
}
}
@@ -80,8 +64,9 @@ public class FeatureSpecificTestSuiteBuilderTest extends TestCase {
.withTearDown(tearDownRunnable)
.createTestSuite();
TestResult result = new TestResult();
+ int timesMyTesterWasRunBeforeSuite = MyTester.timesTestClassWasRun;
test.run(result);
- assertTrue(testWasRun);
+ assertEquals(timesMyTesterWasRunBeforeSuite + 1, MyTester.timesTestClassWasRun);
assertTrue(setUp[0]);
assertTrue(tearDown[0]);
}
diff --git a/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java b/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java
index 283f51efe..b44811e33 100644
--- a/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java
+++ b/guava-testlib/test/com/google/common/collect/testing/IteratorTesterTest.java
@@ -233,7 +233,7 @@ public class IteratorTesterTest extends TestCase {
@Override
public Integer next() {
// We should throw here, but we won't!
- return null;
+ return 0;
}
@Override
diff --git a/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java b/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java
index 5fd0d0368..84447b789 100644
--- a/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java
+++ b/guava-testlib/test/com/google/common/collect/testing/MapTestSuiteBuilderTests.java
@@ -46,6 +46,7 @@ import java.util.function.Predicate;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests {@link MapTestSuiteBuilder} by using it against maps that have various negative behaviors.
@@ -107,7 +108,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public String put(String key, String value) {
+ public @Nullable String put(String key, String value) {
checkNotNull(key);
return map.put(key, value);
}
@@ -139,7 +140,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return map.equals(o);
}
@@ -149,7 +150,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public String remove(Object key) {
+ public @Nullable String remove(Object key) {
return map.remove(key);
}
@@ -200,7 +201,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return next.equals(obj);
}
@@ -249,7 +250,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return map.entrySet().equals(o);
}
@@ -260,7 +261,7 @@ public final class MapTestSuiteBuilderTests extends TestCase {
}
@Override
- public String put(String key, String value) {
+ public @Nullable String put(String key, String value) {
checkNotNull(value);
return map.put(key, value);
}
diff --git a/guava-testlib/test/com/google/common/collect/testing/MyTester.java b/guava-testlib/test/com/google/common/collect/testing/MyTester.java
new file mode 100644
index 000000000..de79059a6
--- /dev/null
+++ b/guava-testlib/test/com/google/common/collect/testing/MyTester.java
@@ -0,0 +1,38 @@
+/*
+ * 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.testing;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.junit.Ignore;
+
+/** Support class added to a suite as part of {@link FeatureSpecificTestSuiteBuilderTest}. */
+/*
+ * @Ignore affects the Android test runner (and only the Android test runner): It respects JUnit 4
+ * annotations even on JUnit 3 tests.
+ *
+ * TODO(b/225350400): Remove @Ignore, which doesn't seem like it should be necessary and probably
+ * soon won't be.
+ */
+@SuppressWarnings("JUnit4ClassUsedInJUnit3")
+@Ignore
+public final class MyTester extends AbstractTester<@Nullable Void> {
+ static int timesTestClassWasRun = 0;
+
+ public void testNothing() {
+ timesTestClassWasRun++;
+ }
+}
diff --git a/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java b/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java
new file mode 100644
index 000000000..46d76a353
--- /dev/null
+++ b/guava-testlib/test/com/google/common/collect/testing/ReserializedSafeTreeMapMapInterfaceTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2010 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.testing;
+
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.testing.SerializableTester;
+import java.util.NavigableMap;
+import java.util.SortedMap;
+
+@GwtIncompatible // SerializableTester
+public class ReserializedSafeTreeMapMapInterfaceTest
+ extends SortedMapInterfaceTest<String, Integer> {
+ public ReserializedSafeTreeMapMapInterfaceTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ NavigableMap<String, Integer> map = new SafeTreeMap<>();
+ map.put("one", 1);
+ map.put("two", 2);
+ map.put("three", 3);
+ return SerializableTester.reserialize(map);
+ }
+
+ @Override
+ protected SortedMap<String, Integer> makeEmptyMap() throws UnsupportedOperationException {
+ NavigableMap<String, Integer> map = new SafeTreeMap<>();
+ return SerializableTester.reserialize(map);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java b/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java
index f03ff0a09..67aa9f7f9 100644
--- a/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java
+++ b/guava-testlib/test/com/google/common/collect/testing/SafeTreeMapTest.java
@@ -110,36 +110,4 @@ public class SafeTreeMapTest extends TestCase {
Lists.newArrayList(map.values()),
Lists.newArrayList(SerializableTester.reserialize(map.values())));
}
-
- @GwtIncompatible // SerializableTester
- public static class ReserializedMapTests extends SortedMapInterfaceTest<String, Integer> {
- public ReserializedMapTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- NavigableMap<String, Integer> map = new SafeTreeMap<>();
- map.put("one", 1);
- map.put("two", 2);
- map.put("three", 3);
- return SerializableTester.reserialize(map);
- }
-
- @Override
- protected SortedMap<String, Integer> makeEmptyMap() throws UnsupportedOperationException {
- NavigableMap<String, Integer> map = new SafeTreeMap<>();
- return SerializableTester.reserialize(map);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
- }
}
diff --git a/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java b/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
index dfd26a0c7..ecca9c873 100644
--- a/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
+++ b/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java
@@ -131,6 +131,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ArbitraryInstances}.
@@ -481,7 +482,7 @@ public class ArbitraryInstancesTest extends TestCase {
}
public static class WithNullConstant {
- public static final WithNullConstant NULL = null;
+ public static final @Nullable WithNullConstant NULL = null;
private WithNullConstant() {}
}
@@ -504,7 +505,7 @@ public class ArbitraryInstancesTest extends TestCase {
private static class FirstConstantIsNull {
// To test that null constant is ignored
@SuppressWarnings("unused")
- public static final FirstConstantIsNull FIRST = null;
+ public static final @Nullable FirstConstantIsNull FIRST = null;
public static final FirstConstantIsNull SECOND = new FirstConstantIsNull();
}
diff --git a/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java b/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
index c5db2d575..ac4e05fba 100644
--- a/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
+++ b/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
@@ -45,6 +45,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Ben Yu
*/
+@AndroidIncompatible // NullPointerTester refuses to run for c.g.c under Android
public class ClassSanityTesterTest extends TestCase {
private final ClassSanityTester tester = new ClassSanityTester();
@@ -212,11 +213,11 @@ public class ClassSanityTesterTest extends TestCase {
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface
public void testEqualsAndSerializableOnReturnValues_good() throws Exception {
tester
- .forAllPublicStaticMethods(GoodEqualsAndSerialiableFactory.class)
+ .forAllPublicStaticMethods(GoodEqualsAndSerializableFactory.class)
.testEqualsAndSerializable();
}
- public static class GoodEqualsAndSerialiableFactory {
+ public static class GoodEqualsAndSerializableFactory {
public static Object good(AnInterface s) {
return Functions.constant(s);
}
@@ -314,7 +315,7 @@ public class ClassSanityTesterTest extends TestCase {
try {
tester.testEquals(BadEquals.class);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains("create(null)");
+ assertThat(expected).hasMessageThat().contains("create(null)");
return;
}
fail("should have failed");
@@ -324,7 +325,7 @@ public class ClassSanityTesterTest extends TestCase {
try {
tester.testEquals(BadEqualsWithParameterizedType.class);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains("create([[1]])");
+ assertThat(expected).hasMessageThat().contains("create([[1]])");
return;
}
fail("should have failed");
@@ -367,7 +368,7 @@ public class ClassSanityTesterTest extends TestCase {
try {
tester.testEquals(cls);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains(cls.getSimpleName() + "(");
+ assertThat(expected).hasMessageThat().contains(cls.getSimpleName() + "(");
return;
}
fail("should have failed for " + cls);
@@ -432,8 +433,8 @@ public class ClassSanityTesterTest extends TestCase {
tester.testNulls(GoodNulls.class);
}
- public void testNoNullCheckNeededDespitNotInstantiable() throws Exception {
- tester.doTestNulls(NoNullCheckNeededDespitNotInstantiable.class, Visibility.PACKAGE);
+ public void testNoNullCheckNeededDespiteNotInstantiable() throws Exception {
+ tester.doTestNulls(NoNullCheckNeededDespiteNotInstantiable.class, Visibility.PACKAGE);
}
public void testNulls_interface() {
@@ -482,9 +483,10 @@ public class ClassSanityTesterTest extends TestCase {
public void testInstantiate_factoryMethodReturnsNullButNotAnnotated() throws Exception {
try {
- tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class);
+ FactoryMethodReturnsNullButNotAnnotated unused =
+ tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class);
} catch (AssertionFailedError expected) {
- assertThat(expected.getMessage()).contains("@Nullable");
+ assertThat(expected).hasMessageThat().contains("@Nullable");
return;
}
fail("should have failed");
@@ -810,8 +812,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameIntegerInstance) {
SameIntegerInstance that = (SameIntegerInstance) obj;
return i == that.i;
@@ -833,8 +835,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameLongInstance) {
SameLongInstance that = (SameLongInstance) obj;
return i == that.i;
@@ -856,8 +858,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameFloatInstance) {
SameFloatInstance that = (SameFloatInstance) obj;
return i == that.i;
@@ -879,8 +881,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameDoubleInstance) {
SameDoubleInstance that = (SameDoubleInstance) obj;
return i == that.i;
@@ -902,8 +904,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameShortInstance) {
SameShortInstance that = (SameShortInstance) obj;
return i == that.i;
@@ -925,8 +927,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- @SuppressWarnings("NumericEquality")
- public boolean equals(Object obj) {
+ @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"})
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameByteInstance) {
SameByteInstance that = (SameByteInstance) obj;
return i == that.i;
@@ -948,7 +950,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ @SuppressWarnings("BoxedPrimitiveEquality")
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameCharacterInstance) {
SameCharacterInstance that = (SameCharacterInstance) obj;
return i == that.i;
@@ -970,7 +973,8 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ @SuppressWarnings("BoxedPrimitiveEquality")
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameBooleanInstance) {
SameBooleanInstance that = (SameBooleanInstance) obj;
return i == that.i;
@@ -992,7 +996,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameStringInstance) {
SameStringInstance that = (SameStringInstance) obj;
return s == that.s;
@@ -1014,7 +1018,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameObjectInstance) {
SameObjectInstance that = (SameObjectInstance) obj;
return s == that.s;
@@ -1036,7 +1040,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameInterfaceInstance) {
SameInterfaceInstance that = (SameInterfaceInstance) obj;
return s == that.s;
@@ -1058,7 +1062,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof SameListInstance) {
SameListInstance that = (SameListInstance) obj;
return s == that.s;
@@ -1090,7 +1094,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof UsesReferentialEquality) {
UsesReferentialEquality that = (UsesReferentialEquality) obj;
return s == that.s;
@@ -1112,7 +1116,7 @@ public class ClassSanityTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof UsesEnum) {
UsesEnum that = (UsesEnum) obj;
return s == that.s;
@@ -1160,9 +1164,9 @@ public class ClassSanityTesterTest extends TestCase {
public void failsToRejectNull(@SuppressWarnings("unused") String s) {}
}
- public static class NoNullCheckNeededDespitNotInstantiable {
+ public static class NoNullCheckNeededDespiteNotInstantiable {
- public NoNullCheckNeededDespitNotInstantiable(NotInstantiable x) {
+ public NoNullCheckNeededDespiteNotInstantiable(NotInstantiable x) {
checkNotNull(x);
}
@@ -1285,7 +1289,7 @@ public class ClassSanityTesterTest extends TestCase {
public ConstructorParameterSingleValue(@SuppressWarnings("unused") Singleton s) {}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof ConstructorParameterSingleValue;
}
diff --git a/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java b/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java
index d615af663..b6b1914eb 100644
--- a/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java
+++ b/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java
@@ -23,6 +23,7 @@ import com.google.common.collect.Sets;
import java.util.Set;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link EqualsTester}.
@@ -114,7 +115,7 @@ public class EqualsTesterTest extends TestCase {
}
/** Test proper handling of case where an object is not equal to itself */
- public void testNonreflexiveEquals() {
+ public void testNonReflexiveEquals() {
Object obj = new NonReflexiveObject();
equalsTester.addEqualityGroup(obj);
try {
@@ -302,7 +303,7 @@ public class EqualsTesterTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (!(o instanceof ValidTestObject)) {
return false;
}
@@ -337,7 +338,7 @@ public class EqualsTesterTest extends TestCase {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (!(o instanceof InvalidHashCodeObject)) {
return false;
}
@@ -356,7 +357,7 @@ public class EqualsTesterTest extends TestCase {
private static class NonReflexiveObject {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return false;
}
@@ -370,7 +371,7 @@ public class EqualsTesterTest extends TestCase {
private static class InvalidEqualsNullObject {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return o == this || o == null;
}
@@ -384,7 +385,7 @@ public class EqualsTesterTest extends TestCase {
private static class InvalidEqualsIncompatibleClassObject {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return o != null;
}
@@ -413,7 +414,7 @@ public class EqualsTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof NamedObject) {
NamedObject that = (NamedObject) obj;
return name.equals(that.name) || peerNames.contains(that.name);
@@ -440,7 +441,7 @@ public class EqualsTesterTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj != null && obj.toString().equals(toString());
}
diff --git a/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java b/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java
index 865c198e7..fedc36088 100644
--- a/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java
+++ b/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java
@@ -113,7 +113,7 @@ public class EquivalenceTesterTest extends TestCase {
fail();
}
- public void testTest_trasitive() {
+ public void testTest_transitive() {
Object group1Item1 = new TestObject(1, 1);
Object group1Item2 = new TestObject(1, 2);
Object group1Item3 = new TestObject(1, 3);
diff --git a/guava-testlib/test/com/google/common/testing/FakeTickerTest.java b/guava-testlib/test/com/google/common/testing/FakeTickerTest.java
index 1372b4545..5120119db 100644
--- a/guava-testlib/test/com/google/common/testing/FakeTickerTest.java
+++ b/guava-testlib/test/com/google/common/testing/FakeTickerTest.java
@@ -26,6 +26,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link FakeTicker}.
@@ -119,9 +120,9 @@ public class FakeTickerTest extends TestCase {
int numberOfThreads = 64;
runConcurrentTest(
numberOfThreads,
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
// adds two nanoseconds to the ticker
ticker.advance(1L);
Thread.sleep(10);
@@ -143,10 +144,10 @@ public class FakeTickerTest extends TestCase {
int numberOfThreads = 64;
runConcurrentTest(
numberOfThreads,
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
- ticker.read();
+ public @Nullable Void call() throws Exception {
+ long unused = ticker.read();
return null;
}
});
@@ -156,7 +157,7 @@ public class FakeTickerTest extends TestCase {
/** Runs {@code callable} concurrently {@code numberOfThreads} times. */
@GwtIncompatible // concurrency
- private void runConcurrentTest(int numberOfThreads, final Callable<Void> callable)
+ private void runConcurrentTest(int numberOfThreads, final Callable<@Nullable Void> callable)
throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
final CountDownLatch startLatch = new CountDownLatch(numberOfThreads);
@@ -165,9 +166,9 @@ public class FakeTickerTest extends TestCase {
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError =
executorService.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
startLatch.countDown();
startLatch.await();
callable.call();
diff --git a/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java b/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java
index 645eda015..7fe3a6080 100644
--- a/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java
+++ b/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java
@@ -25,6 +25,7 @@ import java.util.WeakHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link GcFinalization}.
@@ -32,6 +33,7 @@ import junit.framework.TestCase;
* @author Martin Buchholz
* @author mike nonemacher
*/
+@AndroidIncompatible // depends on details of gc
public class GcFinalizationTest extends TestCase {
@@ -54,7 +56,7 @@ public class GcFinalizationTest extends TestCase {
}
public void testAwaitDone_Future() {
- final SettableFuture<Void> future = SettableFuture.create();
+ final SettableFuture<@Nullable Void> future = SettableFuture.create();
Object x =
new Object() {
@Override
@@ -69,7 +71,7 @@ public class GcFinalizationTest extends TestCase {
}
public void testAwaitDone_Future_Cancel() {
- final SettableFuture<Void> future = SettableFuture.create();
+ final SettableFuture<@Nullable Void> future = SettableFuture.create();
Object x =
new Object() {
@Override
@@ -161,7 +163,7 @@ public class GcFinalizationTest extends TestCase {
public void testAwaitDone_Future_Interrupted_Interrupted() {
Interruptenator interruptenator = new Interruptenator(Thread.currentThread());
try {
- final SettableFuture<Void> future = SettableFuture.create();
+ final SettableFuture<@Nullable Void> future = SettableFuture.create();
try {
GcFinalization.awaitDone(future);
fail("should throw");
diff --git a/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java b/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
index a5a20ec3a..050f05f6d 100644
--- a/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
+++ b/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
@@ -37,6 +37,7 @@ import com.google.common.collect.Table;
import com.google.common.reflect.TypeToken;
import com.google.common.testing.NullPointerTester.Visibility;
import com.google.common.testing.anotherpackage.SomeClassThatDoesNotUseNullable;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
@@ -55,6 +56,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Mick Killianey
*/
@SuppressWarnings("CheckReturnValue")
+@AndroidIncompatible // NullPointerTester refuses to run for c.g.c under Android
public class NullPointerTesterTest extends TestCase {
/** Non-NPE RuntimeException. */
@@ -383,7 +385,7 @@ public class NullPointerTesterTest extends TestCase {
}
/** Method that decides how to react to parameters. */
- public void reactToNullParameters(Object first, Object second) {
+ public void reactToNullParameters(@Nullable Object first, @Nullable Object second) {
if (first == null) {
actionWhenFirstParamIsNull.act();
}
@@ -962,6 +964,7 @@ public class NullPointerTesterTest extends TestCase {
private final Map<Integer, Object> arguments = Maps.newHashMap();
+ @CanIgnoreReturnValue
final DefaultValueChecker runTester() {
new NullPointerTester().testInstanceMethods(this, Visibility.PACKAGE);
return this;
@@ -1444,7 +1447,7 @@ public class NullPointerTesterTest extends TestCase {
static class OverridesEquals {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return true;
}
}
diff --git a/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java b/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
index 753c4ab63..e950c9968 100644
--- a/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
+++ b/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
@@ -19,6 +19,7 @@ package com.google.common.testing;
import java.io.Serializable;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link SerializableTester}.
@@ -82,7 +83,7 @@ public class SerializableTesterTest extends TestCase {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return (other instanceof ClassWhichIsAlwaysEqualButHasDifferentHashcodes);
}
}
@@ -91,7 +92,7 @@ public class SerializableTesterTest extends TestCase {
private static final long serialVersionUID = 1L;
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm);
}
@@ -106,7 +107,7 @@ public class SerializableTesterTest extends TestCase {
private static class OtherForm implements Serializable {
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm);
}
diff --git a/guava-testlib/test/com/google/common/testing/TearDownStackTest.java b/guava-testlib/test/com/google/common/testing/TearDownStackTest.java
index 5a4f9ede4..63e162f75 100644
--- a/guava-testlib/test/com/google/common/testing/TearDownStackTest.java
+++ b/guava-testlib/test/com/google/common/testing/TearDownStackTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** @author Luiz-Otavio "Z" Zorzella */
@GwtCompatible
@@ -146,7 +147,7 @@ public class TearDownStackTest extends TestCase {
private static final class SimpleTearDown implements TearDown {
boolean ran = false;
- Callback callback = null;
+ @Nullable Callback callback = null;
public SimpleTearDown() {}
diff --git a/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java b/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java
index 6e3bf2397..bd823f8f6 100644
--- a/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java
+++ b/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java
@@ -28,12 +28,14 @@ import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.common.testing.ForwardingWrapperTester;
import com.google.common.testing.NullPointerTester;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ForwardingWrapperTester}. Live in a different package to detect reflection
@@ -119,7 +121,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
@SuppressWarnings("EqualsHashCode")
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof ForwardingRunnable) {
ForwardingRunnable that = (ForwardingRunnable) o;
return runnable.equals(that.runnable);
@@ -141,7 +143,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
public Runnable apply(final Runnable runnable) {
return new ForwardingRunnable(runnable) {
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof ForwardingRunnable) {
ForwardingRunnable that = (ForwardingRunnable) o;
return runnable.equals(that.runnable);
@@ -255,7 +257,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
new Function<Adder, Adder>() {
@Override
public Adder apply(Adder adder) {
- return new FailsToPropagageException(adder);
+ return new FailsToPropagateException(adder);
}
},
"add(",
@@ -373,10 +375,10 @@ public class ForwardingWrapperTesterTest extends TestCase {
}
}
- private static class FailsToPropagageException implements Adder {
+ private static class FailsToPropagateException implements Adder {
private final Adder adder;
- FailsToPropagageException(Adder adder) {
+ FailsToPropagateException(Adder adder) {
this.adder = adder;
}
@@ -530,7 +532,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
private interface Equals {
@Override
- boolean equals(Object obj);
+ boolean equals(@Nullable Object obj);
@Override
int hashCode();
@@ -579,6 +581,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
/** An interface for the 2 ways that a chaining call might be defined. */
private interface ChainingCalls {
// A method that is defined to 'return this'
+ @CanIgnoreReturnValue
ChainingCalls chainingCall();
// A method that just happens to return a ChainingCalls object
ChainingCalls nonChainingCall();
@@ -591,6 +594,7 @@ public class ForwardingWrapperTesterTest extends TestCase {
this.delegate = delegate;
}
+ @CanIgnoreReturnValue
@Override
public ForwardingChainingCalls chainingCall() {
delegate.chainingCall();
diff --git a/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java b/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java
index 9dee99b7a..73a9da53a 100644
--- a/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/base/CharMatcherBenchmark.java
@@ -130,9 +130,9 @@ public class CharMatcherBenchmark {
list.set(list.indexOf(0), list.get(0));
list.set(0, 0);
}
- // Get threshold in the range [0, length], rounding up to ensure that non
- // zero percent values result in a non-zero threshold (so we always have at
- // least one matching character).
+ // Get threshold in the range [0, length], rounding up to ensure that
+ // non-zero percent values result in a non-zero threshold (so we always
+ // have at least one matching character).
int threshold = ((percent * length) + 99) / 100;
StringBuilder builder = new StringBuilder(length);
for (int n = 0; n < length; n++) {
diff --git a/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java b/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java
index 43fc75cff..592e80b64 100644
--- a/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/cache/ChainBenchmark.java
@@ -20,12 +20,14 @@ import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.cache.LocalCache.Segment;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Benchmark for {@code LocalCache.Segment.removeEntryFromChain}.
*
* @author Charles Fry
*/
+@SuppressWarnings("CheckReturnValue")
public class ChainBenchmark {
@Param({"1", "2", "3", "4", "5", "6"})
@@ -33,7 +35,7 @@ public class ChainBenchmark {
private Segment<Object, Object> segment;
private ReferenceEntry<Object, Object> head;
- private ReferenceEntry<Object, Object> chain;
+ private @Nullable ReferenceEntry<Object, Object> chain;
@SuppressWarnings("GuardedBy")
@BeforeExperiment
diff --git a/guava-tests/benchmark/com/google/common/cache/MapMakerComparisonBenchmark.java b/guava-tests/benchmark/com/google/common/cache/MapMakerComparisonBenchmark.java
index 5fa6cbc94..7641ce424 100644
--- a/guava-tests/benchmark/com/google/common/cache/MapMakerComparisonBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/cache/MapMakerComparisonBenchmark.java
@@ -26,6 +26,7 @@ import java.util.Map;
*
* @author Nikita Sidorov
*/
+@SuppressWarnings("CheckReturnValue")
public class MapMakerComparisonBenchmark {
private static final String TEST_KEY = "test key";
private static final String TEST_VALUE = "test value";
diff --git a/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java b/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
index 2b7ef36c7..2b6a8c011 100644
--- a/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
@@ -28,7 +28,7 @@ public class InternersBenchmark {
int weakInterner(int reps) {
Interner<String> interner = Interners.newWeakInterner();
for (int i = 0; i < reps; i++) {
- interner.intern(Double.toHexString(Math.random()));
+ String unused = interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
@@ -37,7 +37,7 @@ public class InternersBenchmark {
int strongInterner(int reps) {
Interner<String> interner = Interners.newStrongInterner();
for (int i = 0; i < reps; i++) {
- interner.intern(Double.toHexString(Math.random()));
+ String unused = interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
diff --git a/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java b/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
index 239a033f7..08755044c 100644
--- a/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
@@ -25,6 +25,7 @@ import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Benchmarks to compare performance of MinMaxPriorityQueue and PriorityQueue.
@@ -90,7 +91,7 @@ public class MinMaxPriorityQueueBenchmark {
}
@Override
- public T poll() {
+ public @Nullable T poll() {
return mmHeap.pollLast();
}
}
diff --git a/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java b/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java
index 0fa3e2a88..925db1a02 100644
--- a/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/hash/ChecksumBenchmark.java
@@ -63,12 +63,19 @@ public class ChecksumBenchmark {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
CRC32 checksum = new CRC32();
- checksum.update(testBytes);
+ checksum.update(testBytes, 0, testBytes.length);
result = (byte) (result ^ checksum.getValue());
}
return result;
}
+ // CRC32C
+
+ @Benchmark
+ byte crc32cHashFunction(int reps) {
+ return runHashFunction(reps, Hashing.crc32c());
+ }
+
// Adler32
@Benchmark
@@ -81,7 +88,7 @@ public class ChecksumBenchmark {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
Adler32 checksum = new Adler32();
- checksum.update(testBytes);
+ checksum.update(testBytes, 0, testBytes.length);
result = (byte) (result ^ checksum.getValue());
}
return result;
diff --git a/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java b/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java
index ee81ea125..f82a0c3e6 100644
--- a/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/io/ByteSourceAsCharSourceReadBenchmark.java
@@ -78,7 +78,7 @@ public class ByteSourceAsCharSourceReadBenchmark {
return new String(buffer, 0, bufIndex);
}
// otherwise we got the size wrong. This can happen if the size changes between when
- // we called sizeIfKnown and when we started reading the file (or i guess if
+ // we called sizeIfKnown and when we started reading the file (or I guess if
// maxCharsPerByte is wrong)
// Fallback to an incremental approach
StringBuilder builder = new StringBuilder(bufIndex + 32);
diff --git a/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java b/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java
index 52532bb61..0b9c87489 100644
--- a/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/io/CharStreamsCopyBenchmark.java
@@ -21,6 +21,7 @@ import com.google.caliper.api.VmOptions;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
+import java.nio.Buffer;
import java.nio.CharBuffer;
import java.util.Random;
@@ -40,10 +41,10 @@ public class CharStreamsCopyBenchmark {
CharBuffer buf = CharStreams.createBuffer();
long total = 0;
while (from.read(buf) != -1) {
- buf.flip();
+ ((Buffer) buf).flip();
to.append(buf);
total += buf.remaining();
- buf.clear();
+ ((Buffer) buf).clear();
}
return total;
}
diff --git a/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java b/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java
index 6830482c2..d97c2d56d 100644
--- a/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/math/QuantilesBenchmark.java
@@ -50,7 +50,7 @@ public class QuantilesBenchmark {
}
private double[] dataset(int i) {
- // We must test on a fresh clone of the dataset each time. Doing sorts and quickselects on an
+ // We must test on a fresh clone of the dataset each time. Doing sorts and quickselects on a
// dataset which is already sorted or partially sorted is cheating.
return datasets[i & 0xFF].clone();
}
diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java b/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
index ed2784083..946b85109 100644
--- a/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
@@ -440,7 +440,7 @@ public class ExecutionListBenchmark {
static final Logger log = Logger.getLogger(NewExecutionListWithoutReverse.class.getName());
@GuardedBy("this")
- private RunnableExecutorPair runnables;
+ private @Nullable RunnableExecutorPair runnables;
@GuardedBy("this")
private boolean executed;
@@ -504,10 +504,10 @@ public class ExecutionListBenchmark {
static final Logger log = Logger.getLogger(NewExecutionListQueue.class.getName());
@GuardedBy("this")
- private RunnableExecutorPair head;
+ private @Nullable RunnableExecutorPair head;
@GuardedBy("this")
- private RunnableExecutorPair tail;
+ private @Nullable RunnableExecutorPair tail;
@GuardedBy("this")
private boolean executed;
@@ -671,7 +671,7 @@ public class ExecutionListBenchmark {
// Volatile because this is written on one thread and read on another with no synchronization.
@Nullable volatile RunnableExecutorPair next;
- RunnableExecutorPair(Runnable runnable, Executor executor) {
+ RunnableExecutorPair(@Nullable Runnable runnable, @Nullable Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java b/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java
index c25a8ff31..98b696b4b 100644
--- a/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java
+++ b/guava-tests/benchmark/com/google/common/util/concurrent/FuturesGetCheckedBenchmark.java
@@ -34,7 +34,7 @@ import com.google.common.util.concurrent.FuturesGetChecked.GetCheckedTypeValidat
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
-import java.security.acl.NotOwnerException;
+import java.security.KeyException;
import java.util.List;
import java.util.TooManyListenersException;
import java.util.concurrent.BrokenBarrierException;
@@ -93,7 +93,7 @@ public class FuturesGetCheckedBenchmark {
ExecutionException.class,
GeneralSecurityException.class,
InvalidPreferencesFormatException.class,
- NotOwnerException.class,
+ KeyException.class,
RefreshFailedException.class,
TimeoutException.class,
TooManyListenersException.class,
diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java b/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
index dafb39b6f..7b9be17ec 100644
--- a/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
+++ b/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
@@ -51,7 +51,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Justin T. Sampson
* @param <E> the type of elements held in this collection
*/
-@CanIgnoreReturnValue
+// TODO(kak): consider removing some of the @CanIgnoreReturnValue annotations as appropriate
public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E> {
@@ -213,6 +213,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws IllegalStateException if this queue is full
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue
@Override
public boolean add(E e) {
return super.add(e);
@@ -226,6 +227,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue
@Override
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
@@ -249,6 +251,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
+ @CanIgnoreReturnValue
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
@@ -285,8 +288,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
- public E poll() {
+ public @Nullable E poll() {
final Monitor monitor = this.monitor;
if (monitor.enterIf(notEmpty)) {
try {
@@ -299,8 +303,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
- public E poll(long timeout, TimeUnit unit) throws InterruptedException {
+ public @Nullable E poll(long timeout, TimeUnit unit) throws InterruptedException {
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notEmpty, timeout, unit)) {
try {
@@ -313,6 +318,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
public E take() throws InterruptedException {
final Monitor monitor = this.monitor;
@@ -324,8 +330,9 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
- public E peek() {
+ public @Nullable E peek() {
final Monitor monitor = this.monitor;
if (monitor.enterIf(notEmpty)) {
try {
@@ -345,6 +352,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @return the number of elements in this queue
*/
+ @CanIgnoreReturnValue
@Override
public int size() {
final Monitor monitor = this.monitor;
@@ -367,6 +375,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* inspecting {@code remainingCapacity} because it may be the case that another thread is about to
* insert or remove an element.
*/
+ @CanIgnoreReturnValue
@Override
public int remainingCapacity() {
final Monitor monitor = this.monitor;
@@ -387,6 +396,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
*/
+ @CanIgnoreReturnValue
@Override
public boolean remove(@Nullable Object o) {
if (o == null) return false;
@@ -417,6 +427,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
*/
+ @CanIgnoreReturnValue
@Override
public boolean contains(@Nullable Object o) {
if (o == null) return false;
@@ -447,6 +458,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @return an array containing all of the elements in this queue
*/
+ @CanIgnoreReturnValue
@Override
public Object[] toArray() {
final E[] items = this.items;
@@ -495,6 +507,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* the runtime type of every element in this queue
* @throws NullPointerException if the specified array is null
*/
+ @CanIgnoreReturnValue
@Override
public <T> T[] toArray(T[] a) {
final E[] items = this.items;
@@ -522,6 +535,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue
@Override
public String toString() {
final Monitor monitor = this.monitor;
@@ -563,6 +577,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c) {
if (c == null) throw new NullPointerException();
@@ -597,6 +612,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null) throw new NullPointerException();
@@ -634,6 +650,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
*
* @return an iterator over the elements in this queue in proper sequence
*/
+ @CanIgnoreReturnValue
@Override
public Iterator<E> iterator() {
final Monitor monitor = this.monitor;
@@ -655,7 +672,7 @@ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
* we must return it in the following next() call even if it was in the process of being removed
* when hasNext() was called.
*/
- private E nextItem;
+ private @Nullable E nextItem;
/**
* Index of element returned by most recent call to next. Reset to -1 if this element is deleted
diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java b/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
index 16b648b86..25ec5812f 100644
--- a/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
+++ b/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
@@ -76,7 +76,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Justin T. Sampson
* @param <E> the type of elements held in this collection
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E> {
@@ -152,6 +151,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* in the priority queue according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean add(E e) {
return offer(e);
@@ -166,6 +166,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* in the priority queue according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean offer(E e) {
final Monitor monitor = this.monitor;
@@ -193,6 +194,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* in the priority queue according to the priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean offer(E e, long timeout, TimeUnit unit) {
checkNotNull(unit);
@@ -213,8 +215,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
offer(e); // never need to block
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public E poll() {
+ public @Nullable E poll() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
@@ -224,8 +227,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public E poll(long timeout, TimeUnit unit) throws InterruptedException {
+ public @Nullable E poll(long timeout, TimeUnit unit) throws InterruptedException {
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notEmpty, timeout, unit)) {
try {
@@ -238,6 +242,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public E take() throws InterruptedException {
final Monitor monitor = this.monitor;
@@ -249,8 +254,9 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
- public E peek() {
+ public @Nullable E peek() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
@@ -267,10 +273,12 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @return the comparator used to order the elements in this queue, or {@code null} if this queue
* uses the natural ordering of its elements
*/
+ @CanIgnoreReturnValue // pushed down from class to method
public Comparator<? super E> comparator() {
return q.comparator();
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int size() {
final Monitor monitor = this.monitor;
@@ -288,6 +296,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
*
* @return {@code Integer.MAX_VALUE}
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int remainingCapacity() {
return Integer.MAX_VALUE;
@@ -302,6 +311,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean remove(@Nullable Object o) {
final Monitor monitor = this.monitor;
@@ -321,6 +331,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean contains(@Nullable Object o) {
final Monitor monitor = this.monitor;
@@ -344,6 +355,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
*
* @return an array containing all of the elements in this queue
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public Object[] toArray() {
final Monitor monitor = this.monitor;
@@ -384,6 +396,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* the runtime type of every element in this queue
* @throws NullPointerException if the specified array is null
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public <T> T[] toArray(T[] a) {
final Monitor monitor = this.monitor;
@@ -395,6 +408,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
}
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public String toString() {
final Monitor monitor = this.monitor;
@@ -412,6 +426,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int drainTo(Collection<? super E> c) {
if (c == null) throw new NullPointerException();
@@ -437,6 +452,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null) throw new NullPointerException();
@@ -481,6 +497,7 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
*
* @return an iterator over the elements in this queue
*/
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public Iterator<E> iterator() {
return new Itr(toArray());
@@ -497,11 +514,13 @@ public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
this.array = array;
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public boolean hasNext() {
return cursor < array.length;
}
+ @CanIgnoreReturnValue // pushed down from class to method
@Override
public E next() {
if (cursor >= array.length) throw new NoSuchElementException();
diff --git a/guava-tests/pom.xml b/guava-tests/pom.xml
index b7728d8b1..d14fe5869 100644
--- a/guava-tests/pom.xml
+++ b/guava-tests/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
</parent>
<artifactId>guava-tests</artifactId>
<name>Guava Unit Tests</name>
@@ -36,30 +36,38 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
+ <version>4.13.2</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
+ <version>4.11.0</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
+ <version>${truth.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth.extensions</groupId>
<artifactId>truth-java8-extension</artifactId>
+ <version>${truth.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.jimfs</groupId>
<artifactId>jimfs</artifactId>
+ <version>1.2</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.caliper</groupId>
<artifactId>caliper</artifactId>
+ <version>1.0-beta-3</version>
+ <scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -84,13 +92,6 @@
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
- <id>default-jar</id>
- <goals><goal>jar</goal></goals>
- <configuration>
- <skipIfEmpty>true</skipIfEmpty>
- </configuration>
- </execution>
- <execution>
<id>create-test-jar</id>
<goals><goal>test-jar</goal></goals>
</execution>
diff --git a/guava-tests/test/com/google/common/base/AbstractIteratorTest.java b/guava-tests/test/com/google/common/base/AbstractIteratorTest.java
index ddb7d7097..b1cdae52e 100644
--- a/guava-tests/test/com/google/common/base/AbstractIteratorTest.java
+++ b/guava-tests/test/com/google/common/base/AbstractIteratorTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.GcFinalization;
import java.lang.ref.WeakReference;
import java.util.Iterator;
@@ -50,8 +51,7 @@ public class AbstractIteratorTest extends TestCase {
case 2:
return endOfData();
default:
- fail("Should not have been invoked again");
- return null;
+ throw new AssertionError("Should not have been invoked again");
}
}
};
@@ -85,12 +85,12 @@ public class AbstractIteratorTest extends TestCase {
@Override
public Integer computeNext() {
if (haveBeenCalled) {
- fail("Should not have been called again");
+ throw new AssertionError("Should not have been called again");
} else {
haveBeenCalled = true;
sneakyThrow(new SomeCheckedException());
+ throw new AssertionError(); // unreachable
}
- return null; // never reached
}
};
@@ -173,6 +173,8 @@ public class AbstractIteratorTest extends TestCase {
@GwtIncompatible // weak references
+ @J2ktIncompatible
+ @AndroidIncompatible // depends on details of GC
public void testFreesNextReference() {
Iterator<Object> itr =
new AbstractIterator<Object>() {
@@ -191,7 +193,7 @@ public class AbstractIteratorTest extends TestCase {
@Override
protected Integer computeNext() {
boolean unused = hasNext();
- return null;
+ throw new AssertionError();
}
};
try {
diff --git a/guava-tests/test/com/google/common/base/AndroidIncompatible.java b/guava-tests/test/com/google/common/base/AndroidIncompatible.java
index 5e190a3e1..9ed987a26 100644
--- a/guava-tests/test/com/google/common/base/AndroidIncompatible.java
+++ b/guava-tests/test/com/google/common/base/AndroidIncompatible.java
@@ -30,7 +30,7 @@ import java.lang.annotation.Target;
/**
* Signifies that a test should not be run under Android. This annotation is respected only by our
* Google-internal Android suite generators. Note that those generators also suppress any test
- * annotated with MediumTest or LargeTest.
+ * annotated with LargeTest.
*
* <p>Why use a custom annotation instead of {@code android.test.suitebuilder.annotation.Suppress}?
* I'm not completely sure that this is the right choice, but it has various advantages:
diff --git a/guava-tests/test/com/google/common/base/AsciiTest.java b/guava-tests/test/com/google/common/base/AsciiTest.java
index 9e6b0e41a..371a6a304 100644
--- a/guava-tests/test/com/google/common/base/AsciiTest.java
+++ b/guava-tests/test/com/google/common/base/AsciiTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import junit.framework.TestCase;
/**
@@ -138,6 +139,7 @@ public class AsciiTest extends TestCase {
assertFalse(Ascii.equalsIgnoreCase("[", "{"));
}
+ @J2ktIncompatible
@GwtIncompatible // String.toUpperCase() has browser semantics
public void testEqualsIgnoreCaseUnicodeEquivalence() {
// Note that it's possible in future that the JDK's idea to toUpperCase() or equalsIgnoreCase()
diff --git a/guava-tests/test/com/google/common/base/CaseFormatTest.java b/guava-tests/test/com/google/common/base/CaseFormatTest.java
index f08d9f936..57c7e1725 100644
--- a/guava-tests/test/com/google/common/base/CaseFormatTest.java
+++ b/guava-tests/test/com/google/common/base/CaseFormatTest.java
@@ -24,6 +24,7 @@ import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
@@ -46,6 +47,7 @@ public class CaseFormatTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullArguments() {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/base/CharMatcherTest.java b/guava-tests/test/com/google/common/base/CharMatcherTest.java
index 49bdbbaff..d78327ef0 100644
--- a/guava-tests/test/com/google/common/base/CharMatcherTest.java
+++ b/guava-tests/test/com/google/common/base/CharMatcherTest.java
@@ -27,6 +27,7 @@ import static com.google.common.base.CharMatcher.whitespace;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Sets;
import com.google.common.testing.NullPointerTester;
import java.util.Arrays;
@@ -43,8 +44,10 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class CharMatcherTest extends TestCase {
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStaticNullPointers() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -90,6 +93,7 @@ public class CharMatcherTest extends TestCase {
// The next tests require ICU4J and have, at least for now, been sliced out
// of the open-source view of the tests.
+ @J2ktIncompatible
@GwtIncompatible // Character.isISOControl
public void testJavaIsoControl() {
for (int c = 0; c <= Character.MAX_VALUE; c++) {
@@ -108,6 +112,7 @@ public class CharMatcherTest extends TestCase {
// method, but by overall "scenario". Also, the variety of actual tests we
// do borders on absurd overkill. Better safe than sorry, though?
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
public void testSetBits() {
doTestSetBits(CharMatcher.any());
@@ -128,6 +133,7 @@ public class CharMatcherTest extends TestCase {
doTestSetBits(inRange('A', 'Z').and(inRange('F', 'K').negate()));
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
private void doTestSetBits(CharMatcher matcher) {
BitSet bitset = new BitSet();
@@ -151,6 +157,7 @@ public class CharMatcherTest extends TestCase {
doTestEmpty(forPredicate(Predicates.equalTo('c')));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNull() throws Exception {
doTestNull(CharMatcher.any());
@@ -196,6 +203,7 @@ public class CharMatcherTest extends TestCase {
assertEquals(0, matcher.countIn(""));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
private static void doTestNull(CharMatcher matcher) throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -644,6 +652,14 @@ public class CharMatcherTest extends TestCase {
assertEquals("12 &gt; 5", is('>').replaceFrom("12 > 5", "&gt;"));
}
+ public void testRetainFrom() {
+ assertEquals("aaa", is('a').retainFrom("bazaar"));
+ assertEquals("z", is('z').retainFrom("bazaar"));
+ assertEquals("!", is('!').retainFrom("!@#$%^&*()-="));
+ assertEquals("", is('x').retainFrom("bazaar"));
+ assertEquals("", is('a').retainFrom(""));
+ }
+
public void testPrecomputedOptimizations() {
// These are testing behavior that's never promised by the API.
// Some matchers are so efficient that it is a waste of effort to
@@ -664,11 +680,13 @@ public class CharMatcherTest extends TestCase {
assertSame(CharMatcher.any(), CharMatcher.any().precomputed());
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
private static BitSet bitSet(String chars) {
return bitSet(chars.toCharArray());
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.BitSet
private static BitSet bitSet(char[] chars) {
BitSet tmp = new BitSet();
@@ -678,6 +696,7 @@ public class CharMatcherTest extends TestCase {
return tmp;
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.Random, java.util.BitSet
public void testSmallCharMatcher() {
CharMatcher len1 = SmallCharMatcher.from(bitSet("#"), "#");
diff --git a/guava-tests/test/com/google/common/base/CharsetsTest.java b/guava-tests/test/com/google/common/base/CharsetsTest.java
index c968c8d39..8ff80d0f7 100644
--- a/guava-tests/test/com/google/common/base/CharsetsTest.java
+++ b/guava-tests/test/com/google/common/base/CharsetsTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.charset.Charset;
import java.util.Arrays;
import junit.framework.TestCase;
@@ -30,11 +31,13 @@ import junit.framework.TestCase;
@GwtCompatible(emulated = true)
public class CharsetsTest extends TestCase {
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUsAscii() {
assertEquals(Charset.forName("US-ASCII"), Charsets.US_ASCII);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testIso88591() {
assertEquals(Charset.forName("ISO-8859-1"), Charsets.ISO_8859_1);
@@ -44,21 +47,25 @@ public class CharsetsTest extends TestCase {
assertEquals(Charset.forName("UTF-8"), Charsets.UTF_8);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16be() {
assertEquals(Charset.forName("UTF-16BE"), Charsets.UTF_16BE);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16le() {
assertEquals(Charset.forName("UTF-16LE"), Charsets.UTF_16LE);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testUtf16() {
assertEquals(Charset.forName("UTF-16"), Charsets.UTF_16);
}
+ @J2ktIncompatible
@GwtIncompatible // Non-UTF-8 Charset
public void testWhyUsAsciiIsDangerous() {
byte[] b1 = "朝日新聞".getBytes(Charsets.US_ASCII);
diff --git a/guava-tests/test/com/google/common/base/EnumsTest.java b/guava-tests/test/com/google/common/base/EnumsTest.java
index d8b13af75..66dfe591a 100644
--- a/guava-tests/test/com/google/common/base/EnumsTest.java
+++ b/guava-tests/test/com/google/common/base/EnumsTest.java
@@ -20,8 +20,8 @@ import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.common.truth.Truth.assertThat;
-import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.GcFinalization;
@@ -44,7 +44,8 @@ import junit.framework.TestCase;
*
* @author Steve McKay
*/
-@GwtCompatible(emulated = true)
+@GwtIncompatible
+@J2ktIncompatible
public class EnumsTest extends TestCase {
private enum TestEnum {
@@ -80,7 +81,9 @@ public class EnumsTest extends TestCase {
}
+ @J2ktIncompatible
@GwtIncompatible // weak references
+ @AndroidIncompatible // depends on details of GC and classloading
public void testGetIfPresent_doesNotPreventClassUnloading() throws Exception {
WeakReference<?> shadowLoaderReference = doTestClassUnloading();
GcFinalization.awaitClear(shadowLoaderReference);
@@ -91,6 +94,7 @@ public class EnumsTest extends TestCase {
// new ClassLoader. If Enums.getIfPresent does caching that prevents the shadow TestEnum
// (and therefore its ClassLoader) from being unloaded, then this WeakReference will never be
// cleared.
+ @J2ktIncompatible
@GwtIncompatible // weak references
private WeakReference<?> doTestClassUnloading() throws Exception {
URLClassLoader shadowLoader = new URLClassLoader(getClassPathUrls(), null);
@@ -112,6 +116,7 @@ public class EnumsTest extends TestCase {
return new WeakReference<>(shadowLoader);
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_convert() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertEquals(TestEnum.CHEETO, converter.convert("CHEETO"));
@@ -121,6 +126,7 @@ public class EnumsTest extends TestCase {
assertNull(converter.reverse().convert(null));
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_convertError() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
try {
@@ -130,6 +136,7 @@ public class EnumsTest extends TestCase {
}
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_reverse() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertEquals("CHEETO", converter.reverse().convert(TestEnum.CHEETO));
@@ -137,19 +144,22 @@ public class EnumsTest extends TestCase {
assertEquals("POODLE", converter.reverse().convert(TestEnum.POODLE));
}
- @GwtIncompatible // NullPointerTester
+ @J2ktIncompatible
+ @GwtIncompatible // stringConverter
public void testStringConverter_nullPointerTester() throws Exception {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicInstanceMethods(converter);
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_nullConversions() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertNull(converter.convert(null));
assertNull(converter.reverse().convert(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Class.getName()
public void testStringConverter_toString() {
assertEquals(
@@ -157,10 +167,12 @@ public class EnumsTest extends TestCase {
Enums.stringConverter(TestEnum.class).toString());
}
+ @GwtIncompatible // stringConverter
public void testStringConverter_serialization() {
SerializableTester.reserializeAndAssert(Enums.stringConverter(TestEnum.class));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
@@ -176,6 +188,7 @@ public class EnumsTest extends TestCase {
BAR
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testGetField() {
Field foo = Enums.getField(AnEnum.FOO);
@@ -187,6 +200,7 @@ public class EnumsTest extends TestCase {
assertFalse(bar.isAnnotationPresent(ExampleAnnotation.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Class.getClassLoader()
private URL[] getClassPathUrls() {
ClassLoader classLoader = getClass().getClassLoader();
@@ -200,6 +214,7 @@ public class EnumsTest extends TestCase {
* System#getProperty system property}.
*/
// TODO(b/65488446): Make this a public API.
+ @J2ktIncompatible
@GwtIncompatible
private static ImmutableList<URL> parseJavaClassPath() {
ImmutableList.Builder<URL> urls = ImmutableList.builder();
diff --git a/guava-tests/test/com/google/common/base/EquivalenceTest.java b/guava-tests/test/com/google/common/base/EquivalenceTest.java
index 07c86eae8..46b191a22 100644
--- a/guava-tests/test/com/google/common/base/EquivalenceTest.java
+++ b/guava-tests/test/com/google/common/base/EquivalenceTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Equivalence.Wrapper;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.EqualsTester;
@@ -31,6 +32,7 @@ import junit.framework.TestCase;
*
* @author Jige Yu
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class EquivalenceTest extends TestCase {
@SuppressWarnings("unchecked") // varargs
@@ -81,6 +83,7 @@ public class EquivalenceTest extends TestCase {
assertSame(test, wrapper.get());
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
SerializableTester.reserializeAndAssert(LENGTH_EQUIVALENCE.wrap("hello"));
@@ -157,10 +160,16 @@ public class EquivalenceTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
- public void testNulls() {
- new NullPointerTester().testAllPublicStaticMethods(Equivalence.class);
- new NullPointerTester().testAllPublicInstanceMethods(Equivalence.equals());
- new NullPointerTester().testAllPublicInstanceMethods(Equivalence.identity());
+ public void testNulls() throws NoSuchMethodException {
+ NullPointerTester tester = new NullPointerTester();
+ // Necessary until JDK15:
+ // https://bugs.openjdk.org/browse/JDK-8202469
+ tester.ignore(Equivalence.class.getMethod("wrap", Object.class));
+
+ tester.testAllPublicStaticMethods(Equivalence.class);
+ tester.testAllPublicInstanceMethods(Equivalence.equals());
+ tester.testAllPublicInstanceMethods(Equivalence.identity());
}
}
diff --git a/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java b/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
index 3b5fd1d74..08ead4365 100644
--- a/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
+++ b/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
@@ -25,15 +25,20 @@ import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collections;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link FinalizableReferenceQueue}.
*
* @author Bob Lee
*/
+// - depends on details of GC and classloading
+// - .class files aren't available
+// - possibly no real concept of separate ClassLoaders?
+@AndroidIncompatible
public class FinalizableReferenceQueueTest extends TestCase {
- private FinalizableReferenceQueue frq;
+ private @Nullable FinalizableReferenceQueue frq;
@Override
protected void tearDown() throws Exception {
@@ -80,7 +85,7 @@ public class FinalizableReferenceQueueTest extends TestCase {
}
/** If we don't keep a strong reference to the reference object, it won't be enqueued. */
- FinalizableWeakReference<Object> reference;
+ @Nullable FinalizableWeakReference<Object> reference;
/** Create the FRQ in a method that goes out of scope so that we're sure it will be reclaimed. */
private void weaklyReferenceQueue() {
@@ -102,7 +107,6 @@ public class FinalizableReferenceQueueTest extends TestCase {
};
}
- @AndroidIncompatible // no concept of separate ClassLoaders
public void testDecoupledLoader() {
FinalizableReferenceQueue.DecoupledLoader decoupledLoader =
new FinalizableReferenceQueue.DecoupledLoader() {
@@ -142,7 +146,6 @@ public class FinalizableReferenceQueueTest extends TestCase {
}
}
- @AndroidIncompatible // TODO(cpovirk): How significant is this failure?
public void testGetFinalizerUrl() {
assertNotNull(getClass().getResource("internal/Finalizer.class"));
}
diff --git a/guava-tests/test/com/google/common/base/FunctionsTest.java b/guava-tests/test/com/google/common/base/FunctionsTest.java
index 1411c192b..75b7a9d56 100644
--- a/guava-tests/test/com/google/common/base/FunctionsTest.java
+++ b/guava-tests/test/com/google/common/base/FunctionsTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.testing.ClassSanityTester;
@@ -27,6 +28,7 @@ import com.google.common.testing.SerializableTester;
import java.io.Serializable;
import java.util.Map;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Functions}.
@@ -35,6 +37,7 @@ import junit.framework.TestCase;
* @author Vlad Patryshev
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class FunctionsTest extends TestCase {
public void testIdentity_same() {
@@ -48,6 +51,7 @@ public class FunctionsTest extends TestCase {
assertNotSame(new Long(135135L), identity.apply(new Long(135135L)));
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIdentitySerializable() {
checkCanReserializeSingleton(Functions.identity());
@@ -73,11 +77,13 @@ public class FunctionsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testToStringFunctionSerializable() {
checkCanReserializeSingleton(Functions.toStringFunction());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
@@ -107,6 +113,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithoutDefaultSerializable() {
checkCanReserialize(Functions.forMap(ImmutableMap.of(1, 2)));
@@ -132,6 +139,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithDefault_includeSerializable() {
Map<String, Integer> map = Maps.newHashMap();
@@ -152,6 +160,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithDefaultSerializable() {
checkCanReserialize(Functions.forMap(ImmutableMap.of(1, 2), 3));
@@ -171,6 +180,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForMapWithDefault_null_compareWithSerializable() {
ImmutableMap<String, Integer> map = ImmutableMap.of("One", 1);
@@ -235,6 +245,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testComposition_includeReserializabled() {
Map<String, Integer> mJapaneseToInteger = Maps.newHashMap();
@@ -273,9 +284,9 @@ public class FunctionsTest extends TestCase {
Functions.compose(numberToSpanish, japaneseToInteger);
}
- private static class HashCodeFunction implements Function<Object, Integer> {
+ private static class HashCodeFunction implements Function<@Nullable Object, Integer> {
@Override
- public Integer apply(Object o) {
+ public Integer apply(@Nullable Object o) {
return (o == null) ? 0 : o.hashCode();
}
}
@@ -332,6 +343,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForPredicateSerializable() {
checkCanReserialize(Functions.forPredicate(Predicates.equalTo(5)));
@@ -361,6 +373,7 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testConstantSerializable() {
checkCanReserialize(Functions.constant(5));
@@ -378,7 +391,7 @@ public class FunctionsTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof CountingSupplier) {
return this.value == ((CountingSupplier) obj).value;
}
@@ -406,16 +419,19 @@ public class FunctionsTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testForSupplierSerializable() {
checkCanReserialize(Functions.forSupplier(new CountingSupplier()));
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testNulls() throws Exception {
new ClassSanityTester().forAllPublicStaticMethods(Functions.class).testNulls();
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException: com.google.common.base.Function
// (I suspect that this and the other similar failures happen with ArbitraryInstances proxies.)
@@ -423,6 +439,7 @@ public class FunctionsTest extends TestCase {
new ClassSanityTester().forAllPublicStaticMethods(Functions.class).testEqualsAndSerializable();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
private static <Y> void checkCanReserialize(Function<? super Integer, Y> f) {
Function<? super Integer, Y> g = SerializableTester.reserializeAndAssert(f);
@@ -443,6 +460,7 @@ public class FunctionsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
private static <Y> void checkCanReserializeSingleton(Function<? super String, Y> f) {
Function<? super String, Y> g = SerializableTester.reserializeAndAssert(f);
diff --git a/guava-tests/test/com/google/common/base/JoinerTest.java b/guava-tests/test/com/google/common/base/JoinerTest.java
index d9ed34721..c5eb73d53 100644
--- a/guava-tests/test/com/google/common/base/JoinerTest.java
+++ b/guava-tests/test/com/google/common/base/JoinerTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
@@ -33,6 +34,7 @@ import java.util.Map.Entry;
import java.util.Set;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Joiner}.
@@ -40,6 +42,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class JoinerTest extends TestCase {
private static final Joiner J = Joiner.on("-");
@@ -162,12 +165,13 @@ public class JoinerTest extends TestCase {
private static final Appendable NASTY_APPENDABLE =
new Appendable() {
@Override
- public Appendable append(CharSequence csq) throws IOException {
+ public Appendable append(@Nullable CharSequence csq) throws IOException {
throw new IOException();
}
@Override
- public Appendable append(CharSequence csq, int start, int end) throws IOException {
+ public Appendable append(@Nullable CharSequence csq, int start, int end)
+ throws IOException {
throw new IOException();
}
@@ -359,6 +363,7 @@ public class JoinerTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // StringBuilder.append in GWT invokes Object.toString(), unlike the JRE version.
public void testDontConvertCharSequenceToString() {
assertEquals("foo,foo", Joiner.on(",").join(new DontStringMeBro(), new DontStringMeBro()));
@@ -367,6 +372,7 @@ public class JoinerTest extends TestCase {
Joiner.on(",").useForNull("bar").join(new DontStringMeBro(), null, new DontStringMeBro()));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/base/MoreObjectsTest.java b/guava-tests/test/com/google/common/base/MoreObjectsTest.java
new file mode 100644
index 000000000..6a7149d17
--- /dev/null
+++ b/guava-tests/test/com/google/common/base/MoreObjectsTest.java
@@ -0,0 +1,497 @@
+/*
+ * Copyright (C) 2014 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.base;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.testing.NullPointerTester;
+import java.util.Arrays;
+import java.util.Map;
+import junit.framework.TestCase;
+
+/** Tests for {@link MoreObjects}. */
+@GwtCompatible(emulated = true)
+public class MoreObjectsTest extends TestCase {
+ public void testFirstNonNull_withNonNull() {
+ String s1 = "foo";
+ String s2 = MoreObjects.firstNonNull(s1, "bar");
+ assertSame(s1, s2);
+
+ Long n1 = 42L;
+ Long n2 = MoreObjects.firstNonNull(null, n1);
+ assertSame(n1, n2);
+
+ Boolean b1 = true;
+ Boolean b2 = MoreObjects.firstNonNull(b1, null);
+ assertSame(b1, b2);
+ }
+
+ public void testFirstNonNull_throwsNullPointerException() {
+ try {
+ MoreObjects.firstNonNull(null, null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testToStringHelperWithArrays() {
+ String[] strings = {"hello", "world"};
+ int[] ints = {2, 42};
+ Object[] objects = {"obj"};
+ String[] arrayWithNull = {null};
+ Object[] empty = {};
+ String toTest =
+ MoreObjects.toStringHelper("TSH")
+ .add("strings", strings)
+ .add("ints", ints)
+ .add("objects", objects)
+ .add("arrayWithNull", arrayWithNull)
+ .add("empty", empty)
+ .toString();
+ assertEquals(
+ "TSH{strings=[hello, world], ints=[2, 42], objects=[obj], arrayWithNull=[null], empty=[]}",
+ toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_instance() {
+ String toTest = MoreObjects.toStringHelper(this).toString();
+ assertEquals("MoreObjectsTest{}", toTest);
+ }
+
+ public void testConstructorLenient_instance() {
+ String toTest = MoreObjects.toStringHelper(this).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_innerClass() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ public void testConstructorLenient_innerClass() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_anonymousClass() {
+ String toTest = MoreObjects.toStringHelper(new Object() {}).toString();
+ assertEquals("{}", toTest);
+ }
+
+ public void testConstructorLenient_anonymousClass() {
+ String toTest = MoreObjects.toStringHelper(new Object() {}).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testConstructor_classObject() {
+ String toTest = MoreObjects.toStringHelper(TestClass.class).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ public void testConstructorLenient_classObject() {
+ String toTest = MoreObjects.toStringHelper(TestClass.class).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ public void testConstructor_stringObject() {
+ String toTest = MoreObjects.toStringHelper("FooBar").toString();
+ assertEquals("FooBar{}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringHelper_localInnerClass() {
+ // Local inner classes have names ending like "Outer.$1Inner"
+ class LocalInnerClass {}
+ String toTest = MoreObjects.toStringHelper(new LocalInnerClass()).toString();
+ assertEquals("LocalInnerClass{}", toTest);
+ }
+
+ public void testToStringHelperLenient_localInnerClass() {
+ class LocalInnerClass {}
+ String toTest = MoreObjects.toStringHelper(new LocalInnerClass()).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringHelper_localInnerNestedClass() {
+ class LocalInnerClass {
+ class LocalInnerNestedClass {}
+ }
+ String toTest =
+ MoreObjects.toStringHelper(new LocalInnerClass().new LocalInnerNestedClass()).toString();
+ assertEquals("LocalInnerNestedClass{}", toTest);
+ }
+
+ public void testToStringHelperLenient_localInnerNestedClass() {
+ class LocalInnerClass {
+ class LocalInnerNestedClass {}
+ }
+ String toTest =
+ MoreObjects.toStringHelper(new LocalInnerClass().new LocalInnerNestedClass()).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringHelper_moreThanNineAnonymousClasses() {
+ // The nth anonymous class has a name ending like "Outer.$n"
+ Object o1 = new Object() {};
+ Object o2 = new Object() {};
+ Object o3 = new Object() {};
+ Object o4 = new Object() {};
+ Object o5 = new Object() {};
+ Object o6 = new Object() {};
+ Object o7 = new Object() {};
+ Object o8 = new Object() {};
+ Object o9 = new Object() {};
+ Object o10 = new Object() {};
+ String toTest = MoreObjects.toStringHelper(o10).toString();
+ assertEquals("{}", toTest);
+ }
+
+ public void testToStringHelperLenient_moreThanNineAnonymousClasses() {
+ // The nth anonymous class has a name ending like "Outer.$n"
+ Object o1 = new Object() {};
+ Object o2 = new Object() {};
+ Object o3 = new Object() {};
+ Object o4 = new Object() {};
+ Object o5 = new Object() {};
+ Object o6 = new Object() {};
+ Object o7 = new Object() {};
+ Object o8 = new Object() {};
+ Object o9 = new Object() {};
+ Object o10 = new Object() {};
+ String toTest = MoreObjects.toStringHelper(o10).toString();
+ assertTrue(toTest, toTest.matches(".*\\{\\}"));
+ }
+
+ // all remaining test are on an inner class with various fields
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_oneField() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString();
+ assertEquals("TestClass{field1=Hello}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_oneIntegerField() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", new Integer(42)).toString();
+ assertEquals("TestClass{field1=42}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_nullInteger() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", (Integer) null).toString();
+ assertEquals("TestClass{field1=null}", toTest);
+ }
+
+ public void testToStringLenient_oneField() {
+ String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString();
+ assertTrue(toTest, toTest.matches(".*\\{field1\\=Hello\\}"));
+ }
+
+ public void testToStringLenient_oneIntegerField() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", new Integer(42)).toString();
+ assertTrue(toTest, toTest.matches(".*\\{field1\\=42\\}"));
+ }
+
+ public void testToStringLenient_nullInteger() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).add("field1", (Integer) null).toString();
+ assertTrue(toTest, toTest.matches(".*\\{field1\\=null\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_complexFields() {
+ Map<String, Integer> map =
+ ImmutableMap.<String, Integer>builder().put("abc", 1).put("def", 2).put("ghi", 3).build();
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", "This is string.")
+ .add("field2", Arrays.asList("abc", "def", "ghi"))
+ .add("field3", map)
+ .toString();
+ final String expected =
+ "TestClass{"
+ + "field1=This is string., field2=[abc, def, ghi], field3={abc=1, def=2, ghi=3}}";
+
+ assertEquals(expected, toTest);
+ }
+
+ public void testToStringLenient_complexFields() {
+ Map<String, Integer> map =
+ ImmutableMap.<String, Integer>builder().put("abc", 1).put("def", 2).put("ghi", 3).build();
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", "This is string.")
+ .add("field2", Arrays.asList("abc", "def", "ghi"))
+ .add("field3", map)
+ .toString();
+ final String expectedRegex =
+ ".*\\{"
+ + "field1\\=This is string\\., "
+ + "field2\\=\\[abc, def, ghi\\], "
+ + "field3=\\{abc\\=1, def\\=2, ghi\\=3\\}\\}";
+
+ assertTrue(toTest, toTest.matches(expectedRegex));
+ }
+
+ public void testToString_addWithNullName() {
+ MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass());
+ try {
+ helper.add(null, "Hello");
+ fail("No exception was thrown.");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_addWithNullValue() {
+ final String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString();
+
+ assertEquals("TestClass{Hello=null}", result);
+ }
+
+ public void testToStringLenient_addWithNullValue() {
+ final String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString();
+ assertTrue(result, result.matches(".*\\{Hello\\=null\\}"));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_ToStringTwice() {
+ MoreObjects.ToStringHelper helper =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", 1)
+ .addValue("value1")
+ .add("field2", "value2");
+ final String expected = "TestClass{field1=1, value1, field2=value2}";
+
+ assertEquals(expected, helper.toString());
+ // Call toString again
+ assertEquals(expected, helper.toString());
+
+ // Make sure the cached value is reset when we modify the helper at all
+ final String expected2 = "TestClass{field1=1, value1, field2=value2, 2}";
+ helper.addValue(2);
+ assertEquals(expected2, helper.toString());
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_addValue() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", 1)
+ .addValue("value1")
+ .add("field2", "value2")
+ .addValue(2)
+ .toString();
+ final String expected = "TestClass{field1=1, value1, field2=value2, 2}";
+
+ assertEquals(expected, toTest);
+ }
+
+ public void testToStringLenient_addValue() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", 1)
+ .addValue("value1")
+ .add("field2", "value2")
+ .addValue(2)
+ .toString();
+ final String expected = ".*\\{field1\\=1, value1, field2\\=value2, 2\\}";
+
+ assertTrue(toTest, toTest.matches(expected));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToString_addValueWithNullValue() {
+ final String result =
+ MoreObjects.toStringHelper(new TestClass())
+ .addValue(null)
+ .addValue("Hello")
+ .addValue(null)
+ .toString();
+ final String expected = "TestClass{null, Hello, null}";
+
+ assertEquals(expected, result);
+ }
+
+ public void testToStringLenient_addValueWithNullValue() {
+ final String result =
+ MoreObjects.toStringHelper(new TestClass())
+ .addValue(null)
+ .addValue("Hello")
+ .addValue(null)
+ .toString();
+ final String expected = ".*\\{null, Hello, null\\}";
+
+ assertTrue(result, result.matches(expected));
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_oneField() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).omitNullValues().add("field1", null).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyFieldsFirstNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .add("field1", null)
+ .add("field2", "Googley")
+ .add("field3", "World")
+ .toString();
+ assertEquals("TestClass{field2=Googley, field3=World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyFieldsOmitAfterNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", null)
+ .add("field2", "Googley")
+ .add("field3", "World")
+ .omitNullValues()
+ .toString();
+ assertEquals("TestClass{field2=Googley, field3=World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyFieldsLastNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .add("field1", "Hello")
+ .add("field2", "Googley")
+ .add("field3", null)
+ .toString();
+ assertEquals("TestClass{field1=Hello, field2=Googley}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_oneValue() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass()).omitNullValues().addValue(null).toString();
+ assertEquals("TestClass{}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyValuesFirstNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .addValue(null)
+ .addValue("Googley")
+ .addValue("World")
+ .toString();
+ assertEquals("TestClass{Googley, World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_manyValuesLastNull() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .addValue("Hello")
+ .addValue("Googley")
+ .addValue(null)
+ .toString();
+ assertEquals("TestClass{Hello, Googley}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_differentOrder() {
+ String expected = "TestClass{field1=Hello, field2=Googley, field3=World}";
+ String toTest1 =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .add("field1", "Hello")
+ .add("field2", "Googley")
+ .add("field3", "World")
+ .toString();
+ String toTest2 =
+ MoreObjects.toStringHelper(new TestClass())
+ .add("field1", "Hello")
+ .add("field2", "Googley")
+ .omitNullValues()
+ .add("field3", "World")
+ .toString();
+ assertEquals(expected, toTest1);
+ assertEquals(expected, toTest2);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible // Class names are obfuscated in GWT
+ public void testToStringOmitNullValues_canBeCalledManyTimes() {
+ String toTest =
+ MoreObjects.toStringHelper(new TestClass())
+ .omitNullValues()
+ .omitNullValues()
+ .add("field1", "Hello")
+ .omitNullValues()
+ .add("field2", "Googley")
+ .omitNullValues()
+ .add("field3", "World")
+ .toString();
+ assertEquals("TestClass{field1=Hello, field2=Googley, field3=World}", toTest);
+ }
+
+ @J2ktIncompatible
+ @GwtIncompatible("NullPointerTester")
+ public void testNulls() throws Exception {
+ NullPointerTester tester = new NullPointerTester();
+ tester.ignore(MoreObjects.class.getMethod("firstNonNull", Object.class, Object.class));
+ tester.testAllPublicStaticMethods(MoreObjects.class);
+ tester.testAllPublicInstanceMethods(MoreObjects.toStringHelper(new TestClass()));
+ }
+
+ /** Test class for testing formatting of inner classes. */
+ private static class TestClass {}
+}
diff --git a/guava-tests/test/com/google/common/base/ObjectsTest.java b/guava-tests/test/com/google/common/base/ObjectsTest.java
index 03881402a..34428e223 100644
--- a/guava-tests/test/com/google/common/base/ObjectsTest.java
+++ b/guava-tests/test/com/google/common/base/ObjectsTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import junit.framework.TestCase;
@@ -58,6 +59,7 @@ public class ObjectsTest extends TestCase {
assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(2, 3, 1));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/base/OptionalTest.java b/guava-tests/test/com/google/common/base/OptionalTest.java
index f8d83337c..cdb9b7fa6 100644
--- a/guava-tests/test/com/google/common/base/OptionalTest.java
+++ b/guava-tests/test/com/google/common/base/OptionalTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.EqualsTester;
@@ -29,12 +30,14 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Optional}.
*
* @author Kurt Alfred Kluever
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public final class OptionalTest extends TestCase {
public void testToJavaUtil_static() {
@@ -200,12 +203,13 @@ public final class OptionalTest extends TestCase {
Optional<String> unused =
Optional.of("a")
.transform(
- new Function<String, String>() {
- @Override
- public String apply(String input) {
- return null;
- }
- });
+ (Function<String, String>)
+ new Function<String, @Nullable String>() {
+ @Override
+ public @Nullable String apply(String input) {
+ return null;
+ }
+ });
fail("Should throw if Function returns null.");
} catch (NullPointerException expected) {
}
@@ -216,12 +220,13 @@ public final class OptionalTest extends TestCase {
Optional.absent(),
Optional.absent()
.transform(
- new Function<Object, Object>() {
- @Override
- public Object apply(Object input) {
- return null;
- }
- }));
+ (Function<Object, Object>)
+ new Function<Object, @Nullable Object>() {
+ @Override
+ public @Nullable Object apply(Object input) {
+ return null;
+ }
+ }));
}
public void testEqualsAndHashCode() {
@@ -315,6 +320,7 @@ public final class OptionalTest extends TestCase {
Number value = first.or(0.5); // fine
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester npTester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/base/PreconditionsTest.java b/guava-tests/test/com/google/common/base/PreconditionsTest.java
index 1add44d32..6209d3a06 100644
--- a/guava-tests/test/com/google/common/base/PreconditionsTest.java
+++ b/guava-tests/test/com/google/common/base/PreconditionsTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
@@ -31,6 +32,7 @@ import java.util.Arrays;
import java.util.List;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Preconditions}.
@@ -38,6 +40,9 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
* @author Jared Levy
*/
+@ElementTypesAreNonnullByDefault
+@J2ktIncompatible // TODO(b/278877942): Enable
+@SuppressWarnings("LenientFormatStringValidation") // Intentional for testing
@GwtCompatible(emulated = true)
public class PreconditionsTest extends TestCase {
public void testCheckArgument_simple_success() {
@@ -384,6 +389,7 @@ public class PreconditionsTest extends TestCase {
}
@GwtIncompatible("Reflection")
+ @J2ktIncompatible
public void testAllOverloads_checkArgument() throws Exception {
for (ImmutableList<Class<?>> sig : allSignatures(boolean.class)) {
Method checkArgumentMethod =
@@ -401,6 +407,7 @@ public class PreconditionsTest extends TestCase {
}
@GwtIncompatible("Reflection")
+ @J2ktIncompatible
public void testAllOverloads_checkState() throws Exception {
for (ImmutableList<Class<?>> sig : allSignatures(boolean.class)) {
Method checkArgumentMethod =
@@ -418,6 +425,7 @@ public class PreconditionsTest extends TestCase {
}
@GwtIncompatible("Reflection")
+ @J2ktIncompatible
public void testAllOverloads_checkNotNull() throws Exception {
for (ImmutableList<Class<?>> sig : allSignatures(Object.class)) {
Method checkArgumentMethod =
@@ -461,7 +469,9 @@ public class PreconditionsTest extends TestCase {
* @param sig The method signature
*/
@GwtIncompatible("ArbitraryInstances")
- private Object[] getParametersForSignature(Object firstParam, ImmutableList<Class<?>> sig) {
+ @J2ktIncompatible
+ private Object[] getParametersForSignature(
+ @Nullable Object firstParam, ImmutableList<Class<?>> sig) {
Object[] params = new Object[sig.size()];
params[0] = firstParam;
if (params.length > 1) {
@@ -536,6 +546,7 @@ public class PreconditionsTest extends TestCase {
Preconditions.checkState(boxedBoolean.booleanValue(), "", s);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
/*
diff --git a/guava-tests/test/com/google/common/base/PredicatesTest.java b/guava-tests/test/com/google/common/base/PredicatesTest.java
index 8f8647f4d..24b4e108b 100644
--- a/guava-tests/test/com/google/common/base/PredicatesTest.java
+++ b/guava-tests/test/com/google/common/base/PredicatesTest.java
@@ -21,6 +21,7 @@ import static com.google.common.collect.Lists.newArrayList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.EqualsTester;
@@ -36,12 +37,15 @@ import java.util.List;
import java.util.regex.Pattern;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Predicates}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
+@J2ktIncompatible // TODO(b/278877942): Enable
@GwtCompatible(emulated = true)
public class PredicatesTest extends TestCase {
private static final Predicate<Integer> TRUE = Predicates.alwaysTrue();
@@ -69,7 +73,7 @@ public class PredicatesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof IsOdd;
}
@@ -105,6 +109,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testAlwaysTrue_serialization() {
checkSerialization(Predicates.alwaysTrue());
@@ -126,6 +131,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testAlwaysFalse_serialization() {
checkSerialization(Predicates.alwaysFalse());
@@ -175,6 +181,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testNot_serialization() {
checkSerialization(Predicates.not(isOdd()));
@@ -198,6 +205,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationNoArgs() {
@@ -221,6 +229,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationOneArg() {
@@ -243,6 +252,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testAnd_serializationBinary() {
checkSerialization(Predicates.and(TRUE, isOdd()));
@@ -268,6 +278,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationTernary() {
@@ -295,6 +306,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testAnd_serializationIterable() {
@@ -351,6 +363,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationNoArgs() {
@@ -374,6 +387,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationOneArg() {
@@ -400,6 +414,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testOr_serializationBinary() {
checkSerialization(Predicates.or(isOdd(), TRUE));
@@ -424,6 +439,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationTernary() {
@@ -457,6 +473,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked") // varargs
public void testOr_serializationIterable() {
@@ -517,6 +534,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIsEqualTo_serialization() {
checkSerialization(Predicates.equalTo(1));
@@ -536,6 +554,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIsEqualToNull_serialization() {
checkSerialization(Predicates.equalTo(null));
@@ -546,6 +565,7 @@ public class PredicatesTest extends TestCase {
* stripper to remove comments properly. Currently, all tests before the comments are removed as
* well.
*/
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_apply() {
Predicate<Object> isInteger = Predicates.instanceOf(Integer.class);
@@ -556,6 +576,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isInteger.apply(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_subclass() {
Predicate<Object> isNumber = Predicates.instanceOf(Number.class);
@@ -566,6 +587,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isNumber.apply(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_interface() {
Predicate<Object> isComparable = Predicates.instanceOf(Comparable.class);
@@ -576,6 +598,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isComparable.apply(null));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf
public void testIsInstanceOf_equality() {
new EqualsTester()
@@ -586,11 +609,13 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.instanceOf, SerializableTester
public void testIsInstanceOf_serialization() {
checkSerialization(Predicates.instanceOf(Integer.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_apply() {
Predicate<Class<?>> isInteger = Predicates.subtypeOf(Integer.class);
@@ -605,6 +630,7 @@ public class PredicatesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_subclass() {
Predicate<Class<?>> isNumber = Predicates.subtypeOf(Number.class);
@@ -613,6 +639,7 @@ public class PredicatesTest extends TestCase {
assertTrue(isNumber.apply(Float.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_interface() {
Predicate<Class<?>> isComparable = Predicates.subtypeOf(Comparable.class);
@@ -621,6 +648,7 @@ public class PredicatesTest extends TestCase {
assertTrue(isComparable.apply(Float.class));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf
public void testSubtypeOf_equality() {
new EqualsTester()
@@ -630,6 +658,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.subtypeOf, SerializableTester
public void testSubtypeOf_serialization() {
Predicate<Class<?>> predicate = Predicates.subtypeOf(Integer.class);
@@ -657,6 +686,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIsNull_serialization() {
Predicate<String> pre = Predicates.isNull();
@@ -678,6 +708,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testNotNull_serialization() {
checkSerialization(Predicates.notNull());
@@ -709,6 +740,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testIn_serialization() {
checkSerialization(Predicates.in(Arrays.asList(1, 2, 3, null)));
@@ -757,6 +789,7 @@ public class PredicatesTest extends TestCase {
// Predicate<Integer> p4 = Predicates.<Integer>in(nums);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
@@ -764,7 +797,8 @@ public class PredicatesTest extends TestCase {
}
@SuppressWarnings("unchecked") // varargs
- @GwtIncompatible // SerializbleTester
+ @J2ktIncompatible
+ @GwtIncompatible // SerializableTester
public void testCascadingSerialization() throws Exception {
// Eclipse says Predicate<Integer>; javac says Predicate<Object>.
Predicate<? super Integer> nasty =
@@ -815,6 +849,7 @@ public class PredicatesTest extends TestCase {
.testEquals();
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testComposeSerialization() {
Function<String, String> trim = TrimStringFunction.INSTANCE;
@@ -828,6 +863,7 @@ public class PredicatesTest extends TestCase {
* works, so there are only trivial tests of that aspect. TODO: Fix comment style once annotation
* stripper is fixed.
*/
+ @J2ktIncompatible
@GwtIncompatible // Predicates.containsPattern
public void testContainsPattern_apply() {
Predicate<CharSequence> isFoobar = Predicates.containsPattern("^Fo.*o.*bar$");
@@ -835,6 +871,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isFoobar.apply("Foobarx"));
}
+ @J2ktIncompatible
@GwtIncompatible // Predicates.containsPattern
public void testContains_apply() {
Predicate<CharSequence> isFoobar = Predicates.contains(Pattern.compile("^Fo.*o.*bar$"));
@@ -843,6 +880,7 @@ public class PredicatesTest extends TestCase {
assertFalse(isFoobar.apply("Foobarx"));
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testContainsPattern_nulls() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -851,6 +889,7 @@ public class PredicatesTest extends TestCase {
tester.testAllPublicInstanceMethods(isWooString);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testContains_nulls() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -859,6 +898,7 @@ public class PredicatesTest extends TestCase {
tester.testAllPublicInstanceMethods(isWooPattern);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testContainsPattern_serialization() {
Predicate<CharSequence> pre = Predicates.containsPattern("foo");
@@ -866,6 +906,7 @@ public class PredicatesTest extends TestCase {
assertEquals(pre.apply("foo"), post.apply("foo"));
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testContains_equals() {
new EqualsTester()
@@ -897,11 +938,13 @@ public class PredicatesTest extends TestCase {
assertTrue(Predicates.and(p1, p2).hashCode() != Predicates.or(p1, p2).hashCode());
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testNulls() throws Exception {
new ClassSanityTester().forAllPublicStaticMethods(Predicates.class).testNulls();
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException: com.google.common.base.Function
public void testEqualsAndSerializable() throws Exception {
@@ -956,6 +999,7 @@ public class PredicatesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
private static void checkSerialization(Predicate<? super Integer> predicate) {
Predicate<? super Integer> reserialized = SerializableTester.reserializeAndAssert(predicate);
diff --git a/guava-tests/test/com/google/common/base/SplitterTest.java b/guava-tests/test/com/google/common/base/SplitterTest.java
index 0c697b845..ed14a8f6f 100644
--- a/guava-tests/test/com/google/common/base/SplitterTest.java
+++ b/guava-tests/test/com/google/common/base/SplitterTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Splitter.MapSplitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.testing.NullPointerTester;
@@ -30,7 +31,10 @@ import java.util.Map;
import java.util.regex.Pattern;
import junit.framework.TestCase;
-/** @author Julien Silland */
+/**
+ * @author Julien Silland
+ */
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class SplitterTest extends TestCase {
@@ -294,6 +298,7 @@ public class SplitterTest extends TestCase {
.inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSimpleSplit() {
String simple = "a,b,c";
@@ -301,6 +306,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSimpleSplitWithNoDelimiter() {
String simple = "a,b,c";
@@ -308,6 +314,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a,b,c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithDoubleDelimiter() {
String doubled = "a,,b,c";
@@ -315,6 +322,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithDoubleDelimiterAndSpace() {
String doubled = "a,, b,c";
@@ -322,6 +330,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "", " b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithTrailingDelimiter() {
String trailing = "a,b,c,";
@@ -329,6 +338,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c", "").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithLeadingDelimiter() {
String leading = ",a,b,c";
@@ -338,6 +348,7 @@ public class SplitterTest extends TestCase {
// TODO(kevinb): the name of this method suggests it might not actually be testing what it
// intends to be testing?
+ @J2ktIncompatible
@GwtIncompatible // Splitter.onPattern
public void testPatternSplitWithMultipleLetters() {
Iterable<String> testPatterningMotto =
@@ -347,11 +358,13 @@ public class SplitterTest extends TestCase {
.inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
private static Pattern literalDotPattern() {
return Pattern.compile("\\.");
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithDoubleDelimiterOmitEmptyStrings() {
String doubled = "a..b.c";
@@ -359,6 +372,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
@AndroidIncompatible // Bug in older versions of Android we test against, since fixed.
public void testPatternSplitLookBehind() {
@@ -372,6 +386,7 @@ public class SplitterTest extends TestCase {
// splits into chunks ending in :
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
@AndroidIncompatible // Bug in older versions of Android we test against, since fixed.
public void testPatternSplitWordBoundary() {
@@ -380,6 +395,7 @@ public class SplitterTest extends TestCase {
assertThat(words).containsExactly("foo", "<", "bar", ">", "bletch").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWordBoundary_singleCharInput() {
String string = "f";
@@ -388,6 +404,7 @@ public class SplitterTest extends TestCase {
}
@AndroidIncompatible // Apparently Gingerbread's regex API is buggy.
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWordBoundary_singleWordInput() {
String string = "foo";
@@ -395,6 +412,7 @@ public class SplitterTest extends TestCase {
assertThat(words).containsExactly("foo").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitEmptyToken() {
String emptyToken = "a. .c";
@@ -402,6 +420,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitEmptyTokenOmitEmptyStrings() {
String emptyToken = "a. .c";
@@ -410,6 +429,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitOnOnlyDelimiter() {
Iterable<String> blankblank = Splitter.on(literalDotPattern()).split(".");
@@ -417,12 +437,14 @@ public class SplitterTest extends TestCase {
assertThat(blankblank).containsExactly("", "").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitOnOnlyDelimitersOmitEmptyStrings() {
Iterable<String> empty = Splitter.on(literalDotPattern()).omitEmptyStrings().split("...");
assertThat(empty).isEmpty();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitMatchingIsGreedy() {
String longDelimiter = "a, b, c";
@@ -430,6 +452,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithLongLeadingDelimiter() {
String longDelimiter = ", a, b, c";
@@ -437,6 +460,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("", "a", "b", "c").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithLongTrailingDelimiter() {
String longDelimiter = "a, b, c/ ";
@@ -444,6 +468,7 @@ public class SplitterTest extends TestCase {
assertThat(letters).containsExactly("a", "b", "c", "").inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitInvalidPattern() {
try {
@@ -453,6 +478,7 @@ public class SplitterTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testPatternSplitWithTrim() {
String jacksons =
@@ -474,6 +500,7 @@ public class SplitterTest extends TestCase {
assertIteratorIsUnmodifiable(Splitter.on(",").split("a,b").iterator());
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
public void testSplitterIterableIsUnmodifiable_pattern() {
assertIteratorIsUnmodifiable(Splitter.on(Pattern.compile(",")).split("a,b").iterator());
@@ -496,6 +523,7 @@ public class SplitterTest extends TestCase {
assertSplitterIterableIsLazy(Splitter.on(","));
}
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex.Pattern
@AndroidIncompatible // not clear that j.u.r.Matcher promises to handle mutations during use
public void testSplitterIterableIsLazy_pattern() {
@@ -670,6 +698,7 @@ public class SplitterTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/base/StopwatchJavaTimeTest.java b/guava-tests/test/com/google/common/base/StopwatchJavaTimeTest.java
index 35fd5b108..2b082119d 100644
--- a/guava-tests/test/com/google/common/base/StopwatchJavaTimeTest.java
+++ b/guava-tests/test/com/google/common/base/StopwatchJavaTimeTest.java
@@ -17,11 +17,13 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.FakeTicker;
import java.time.Duration;
import junit.framework.TestCase;
/** Unit test for the {@code java.time} support in {@link Stopwatch}. */
+@J2ktIncompatible
@GwtIncompatible
public class StopwatchJavaTimeTest extends TestCase {
private final FakeTicker ticker = new FakeTicker();
diff --git a/guava-tests/test/com/google/common/base/StopwatchTest.java b/guava-tests/test/com/google/common/base/StopwatchTest.java
index b85ebb7b0..21d36d65c 100644
--- a/guava-tests/test/com/google/common/base/StopwatchTest.java
+++ b/guava-tests/test/com/google/common/base/StopwatchTest.java
@@ -21,6 +21,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.FakeTicker;
import junit.framework.TestCase;
@@ -166,6 +167,7 @@ public class StopwatchTest extends TestCase {
assertEquals(1, stopwatch.elapsed(MILLISECONDS));
}
+ @J2ktIncompatible // TODO(b/259213718): Enable
public void testToString() {
stopwatch.start();
assertEquals("0.000 ns", stopwatch.toString());
diff --git a/guava-tests/test/com/google/common/base/StringsTest.java b/guava-tests/test/com/google/common/base/StringsTest.java
index ac3ad20a5..c495ff5bf 100644
--- a/guava-tests/test/com/google/common/base/StringsTest.java
+++ b/guava-tests/test/com/google/common/base/StringsTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import junit.framework.TestCase;
@@ -28,6 +29,7 @@ import junit.framework.TestCase;
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class StringsTest extends TestCase {
public void testNullToEmpty() {
@@ -213,6 +215,7 @@ public class StringsTest extends TestCase {
assertFalse(Strings.validSurrogatePairAt("\uD8ABx", 0));
}
+ @SuppressWarnings("LenientFormatStringValidation") // Intentional for testing.
public void testLenientFormat() {
assertEquals("%s", Strings.lenientFormat("%s"));
assertEquals("5", Strings.lenientFormat("%s", 5));
@@ -232,6 +235,7 @@ public class StringsTest extends TestCase {
assertEquals("(Object[])null", Strings.lenientFormat("%s", (Object[]) null));
}
+ @J2ktIncompatible
@GwtIncompatible // GWT reflection includes less data
public void testLenientFormat_badArgumentToString() {
assertThat(Strings.lenientFormat("boiler %s plate", new ThrowsOnToString()))
@@ -252,6 +256,7 @@ public class StringsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/base/SuppliersTest.java b/guava-tests/test/com/google/common/base/SuppliersTest.java
index a97fe656c..9befacc6f 100644
--- a/guava-tests/test/com/google/common/base/SuppliersTest.java
+++ b/guava-tests/test/com/google/common/base/SuppliersTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Lists;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.EqualsTester;
@@ -39,6 +40,7 @@ import junit.framework.TestCase;
* @author Laurence Gonsalves
* @author Harry Heymann
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class SuppliersTest extends TestCase {
@@ -126,6 +128,7 @@ public class SuppliersTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testMemoizeNonSerializable() throws Exception {
CountingSupplier countingSupplier = new CountingSupplier();
@@ -133,7 +136,7 @@ public class SuppliersTest extends TestCase {
assertThat(memoizedSupplier.toString()).isEqualTo("Suppliers.memoize(CountingSupplier)");
checkMemoize(countingSupplier, memoizedSupplier);
// Calls to the original memoized supplier shouldn't affect its copy.
- memoizedSupplier.get();
+ Object unused = memoizedSupplier.get();
assertThat(memoizedSupplier.toString())
.isEqualTo("Suppliers.memoize(<supplier that returned 10>)");
@@ -146,6 +149,7 @@ public class SuppliersTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testMemoizeSerializable() throws Exception {
SerializableCountingSupplier countingSupplier = new SerializableCountingSupplier();
@@ -153,12 +157,12 @@ public class SuppliersTest extends TestCase {
assertThat(memoizedSupplier.toString()).isEqualTo("Suppliers.memoize(CountingSupplier)");
checkMemoize(countingSupplier, memoizedSupplier);
// Calls to the original memoized supplier shouldn't affect its copy.
- memoizedSupplier.get();
+ Object unused = memoizedSupplier.get();
assertThat(memoizedSupplier.toString())
.isEqualTo("Suppliers.memoize(<supplier that returned 10>)");
Supplier<Integer> copy = reserialize(memoizedSupplier);
- memoizedSupplier.get();
+ Object unused2 = memoizedSupplier.get();
CountingSupplier countingCopy =
(CountingSupplier) ((Suppliers.MemoizingSupplier<Integer>) copy).delegate;
@@ -213,6 +217,7 @@ public class SuppliersTest extends TestCase {
assertEquals(Integer.valueOf(1), result.get(1));
}
+ @J2ktIncompatible
@GwtIncompatible // Thread.sleep
public void testMemoizeWithExpiration() throws InterruptedException {
CountingSupplier countingSupplier = new CountingSupplier();
@@ -223,6 +228,7 @@ public class SuppliersTest extends TestCase {
checkExpiration(countingSupplier, memoizedSupplier);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread.sleep, SerializationTester
public void testMemoizeWithExpirationSerialized() throws InterruptedException {
SerializableCountingSupplier countingSupplier = new SerializableCountingSupplier();
@@ -230,16 +236,17 @@ public class SuppliersTest extends TestCase {
Supplier<Integer> memoizedSupplier =
Suppliers.memoizeWithExpiration(countingSupplier, 75, TimeUnit.MILLISECONDS);
// Calls to the original memoized supplier shouldn't affect its copy.
- memoizedSupplier.get();
+ Object unused = memoizedSupplier.get();
Supplier<Integer> copy = reserialize(memoizedSupplier);
- memoizedSupplier.get();
+ Object unused2 = memoizedSupplier.get();
CountingSupplier countingCopy =
(CountingSupplier) ((Suppliers.ExpiringMemoizingSupplier<Integer>) copy).delegate;
checkExpiration(countingCopy, copy);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread.sleep
private void checkExpiration(
CountingSupplier countingSupplier, Supplier<Integer> memoizedSupplier)
@@ -278,8 +285,8 @@ public class SuppliersTest extends TestCase {
assertNull(nullSupplier.get());
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
-
public void testExpiringMemoizedSupplierThreadSafe() throws Throwable {
Function<Supplier<Boolean>, Supplier<Boolean>> memoizer =
new Function<Supplier<Boolean>, Supplier<Boolean>>() {
@@ -291,8 +298,8 @@ public class SuppliersTest extends TestCase {
testSupplierThreadSafe(memoizer);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
-
public void testMemoizedSupplierThreadSafe() throws Throwable {
Function<Supplier<Boolean>, Supplier<Boolean>> memoizer =
new Function<Supplier<Boolean>, Supplier<Boolean>>() {
@@ -304,8 +311,9 @@ public class SuppliersTest extends TestCase {
testSupplierThreadSafe(memoizer);
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
- public void testSupplierThreadSafe(Function<Supplier<Boolean>, Supplier<Boolean>> memoizer)
+ private void testSupplierThreadSafe(Function<Supplier<Boolean>, Supplier<Boolean>> memoizer)
throws Throwable {
final AtomicInteger count = new AtomicInteger(0);
final AtomicReference<Throwable> thrown = new AtomicReference<>(null);
@@ -380,8 +388,8 @@ public class SuppliersTest extends TestCase {
assertEquals(1, count.get());
}
+ @J2ktIncompatible
@GwtIncompatible // Thread
-
public void testSynchronizedSupplierThreadSafe() throws InterruptedException {
final Supplier<Integer> nonThreadSafe =
new Supplier<Integer>() {
@@ -405,7 +413,7 @@ public class SuppliersTest extends TestCase {
@Override
public void run() {
for (int j = 0; j < iterations; j++) {
- Suppliers.synchronizedSupplier(nonThreadSafe).get();
+ Object unused = Suppliers.synchronizedSupplier(nonThreadSafe).get();
}
}
};
@@ -427,6 +435,7 @@ public class SuppliersTest extends TestCase {
assertEquals(14, (int) supplierFunction.apply(supplier));
}
+ @J2ktIncompatible
@GwtIncompatible // SerializationTester
public void testSerialization() {
assertEquals(Integer.valueOf(5), reserialize(Suppliers.ofInstance(5)).get());
@@ -443,11 +452,13 @@ public class SuppliersTest extends TestCase {
reserialize(Suppliers.synchronizedSupplier(Suppliers.ofInstance(5))).get());
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
public void testSuppliersNullChecks() throws Exception {
new ClassSanityTester().forAllPublicStaticMethods(Suppliers.class).testNulls();
}
+ @J2ktIncompatible
@GwtIncompatible // reflection
@AndroidIncompatible // TODO(cpovirk): ClassNotFoundException: com.google.common.base.Function
public void testSuppliersSerializable() throws Exception {
diff --git a/guava-tests/test/com/google/common/base/ThrowablesTest.java b/guava-tests/test/com/google/common/base/ThrowablesTest.java
index e4c64aa8d..975765340 100644
--- a/guava-tests/test/com/google/common/base/ThrowablesTest.java
+++ b/guava-tests/test/com/google/common/base/ThrowablesTest.java
@@ -28,6 +28,7 @@ import static java.util.regex.Pattern.quote;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import com.google.common.testing.NullPointerTester;
@@ -62,6 +63,7 @@ public class ThrowablesTest extends TestCase {
throwIfUnchecked(new SomeCheckedException());
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_NoneThrown() {
Sample sample =
@@ -81,6 +83,7 @@ public class ThrowablesTest extends TestCase {
sample.noneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_UncheckedThrown() {
Sample sample =
@@ -104,6 +107,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_UndeclaredThrown() {
Sample sample =
@@ -127,6 +131,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_NoneThrown() throws SomeCheckedException {
Sample sample =
@@ -148,6 +153,7 @@ public class ThrowablesTest extends TestCase {
sample.oneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_UncheckedThrown() throws SomeCheckedException {
Sample sample =
@@ -171,6 +177,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_CheckedThrown() {
Sample sample =
@@ -194,6 +201,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_UndeclaredThrown() throws SomeCheckedException {
Sample sample =
@@ -217,6 +225,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_NoneThrown()
throws SomeCheckedException, SomeOtherCheckedException {
@@ -238,6 +247,7 @@ public class ThrowablesTest extends TestCase {
sample.twoDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_UncheckedThrown()
throws SomeCheckedException, SomeOtherCheckedException {
@@ -263,6 +273,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_CheckedThrown() throws SomeOtherCheckedException {
Sample sample =
@@ -287,6 +298,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_OtherCheckedThrown() throws SomeCheckedException {
Sample sample =
@@ -319,21 +331,25 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible
public void testPropageIfPossible_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null);
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropageIfPossible_OneDeclared_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null, SomeCheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropageIfPossible_TwoDeclared_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null, SomeCheckedException.class, SomeUncheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_NoneThrown() {
Sample sample =
@@ -352,6 +368,7 @@ public class ThrowablesTest extends TestCase {
sample.noneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_UncheckedThrown() {
Sample sample =
@@ -374,6 +391,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_ErrorThrown() {
Sample sample =
@@ -396,6 +414,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_CheckedThrown() {
Sample sample =
@@ -419,16 +438,19 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_Unchecked() throws SomeCheckedException {
throwIfInstanceOf(new SomeUncheckedException(), SomeCheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedDifferent() throws SomeCheckedException {
throwIfInstanceOf(new SomeOtherCheckedException(), SomeCheckedException.class);
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedSame() {
try {
@@ -438,6 +460,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedSubclass() {
try {
@@ -447,6 +470,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_NoneThrown() throws SomeCheckedException {
Sample sample =
@@ -466,6 +490,7 @@ public class ThrowablesTest extends TestCase {
sample.oneDeclared();
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_DeclaredThrown() {
Sample sample =
@@ -489,6 +514,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_UncheckedThrown() throws SomeCheckedException {
Sample sample =
@@ -512,6 +538,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_UndeclaredThrown() throws SomeCheckedException {
Sample sample =
@@ -536,6 +563,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_null() throws SomeCheckedException {
try {
@@ -545,6 +573,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public void testPropageIfInstanceOf_null() throws SomeCheckedException {
Throwables.propagateIfInstanceOf(null, SomeCheckedException.class);
@@ -625,6 +654,7 @@ public class ThrowablesTest extends TestCase {
throw new SomeUndeclaredCheckedException();
}
+ @J2ktIncompatible
@GwtIncompatible // getStackTraceAsString(Throwable)
public void testGetStackTraceAsString() {
class StackTraceException extends Exception {
@@ -637,8 +667,9 @@ public class ThrowablesTest extends TestCase {
String firstLine = quote(e.getClass().getName() + ": " + e.getMessage());
String secondLine = "\\s*at " + ThrowablesTest.class.getName() + "\\..*";
- String moreLines = "(?:.*\n?)*";
- String expected = firstLine + "\n" + secondLine + "\n" + moreLines;
+ String moreLines = "(?:.*" + System.lineSeparator() + "?)*";
+ String expected =
+ firstLine + System.lineSeparator() + secondLine + System.lineSeparator() + moreLines;
assertThat(getStackTraceAsString(e)).matches(expected);
}
@@ -679,6 +710,7 @@ public class ThrowablesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Throwables.getCauseAs(Throwable, Class)
public void testGetCauseAs() {
SomeCheckedException cause = new SomeCheckedException();
@@ -697,6 +729,7 @@ public class ThrowablesTest extends TestCase {
}
@AndroidIncompatible // No getJavaLangAccess in Android (at least not in the version we use).
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTraceIsLazy()
public void testLazyStackTraceWorksInProd() {
// TODO(b/64442212): Remove this guard once lazyStackTrace() works in Java 9+.
@@ -708,6 +741,7 @@ public class ThrowablesTest extends TestCase {
assertTrue(lazyStackTraceIsLazy());
}
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTrace(Throwable)
public void testLazyStackTrace() {
Exception e = new Exception();
@@ -731,6 +765,7 @@ public class ThrowablesTest extends TestCase {
assertThat(lazyStackTrace(e)).containsExactly((Object[]) originalStackTrace).inOrder();
}
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTrace
private void doTestLazyStackTraceFallback() {
assertFalse(lazyStackTraceIsLazy());
@@ -749,6 +784,7 @@ public class ThrowablesTest extends TestCase {
assertThat(lazyStackTrace(e)).isEmpty();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
new NullPointerTester().testAllPublicStaticMethods(Throwables.class);
diff --git a/guava-tests/test/com/google/common/base/ToStringHelperTest.java b/guava-tests/test/com/google/common/base/ToStringHelperTest.java
index db15f2ef8..62ee89191 100644
--- a/guava-tests/test/com/google/common/base/ToStringHelperTest.java
+++ b/guava-tests/test/com/google/common/base/ToStringHelperTest.java
@@ -18,6 +18,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.Map;
@@ -31,6 +32,7 @@ import junit.framework.TestCase;
@GwtCompatible
public class ToStringHelperTest extends TestCase {
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_instance() {
String toTest = MoreObjects.toStringHelper(this).toString();
@@ -42,6 +44,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_innerClass() {
String toTest = MoreObjects.toStringHelper(new TestClass()).toString();
@@ -53,6 +56,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_anonymousClass() {
String toTest = MoreObjects.toStringHelper(new Object() {}).toString();
@@ -64,6 +68,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testConstructor_classObject() {
String toTest = MoreObjects.toStringHelper(TestClass.class).toString();
@@ -80,6 +85,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("FooBar{}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringHelper_localInnerClass() {
// Local inner classes have names ending like "Outer.$1Inner"
@@ -94,6 +100,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringHelper_localInnerNestedClass() {
class LocalInnerClass {
@@ -113,6 +120,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringHelper_moreThanNineAnonymousClasses() {
// The nth anonymous class has a name ending like "Outer.$n"
@@ -147,12 +155,14 @@ public class ToStringHelperTest extends TestCase {
}
// all remaining test are on an inner class with various fields
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_oneField() {
String toTest = MoreObjects.toStringHelper(new TestClass()).add("field1", "Hello").toString();
assertEquals("TestClass{field1=Hello}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_oneIntegerField() {
String toTest =
@@ -160,6 +170,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field1=42}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_nullInteger() {
String toTest =
@@ -184,6 +195,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(".*\\{field1\\=null\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_complexFields() {
@@ -230,6 +242,7 @@ public class ToStringHelperTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_addWithNullValue() {
final String result = MoreObjects.toStringHelper(new TestClass()).add("Hello", null).toString();
@@ -242,6 +255,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(result, result.matches(".*\\{Hello\\=null\\}"));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_ToStringTwice() {
MoreObjects.ToStringHelper helper =
@@ -261,6 +275,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals(expected2, helper.toString());
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_addValue() {
String toTest =
@@ -288,6 +303,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(toTest, toTest.matches(expected));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToString_addValueWithNullValue() {
final String result =
@@ -313,6 +329,7 @@ public class ToStringHelperTest extends TestCase {
assertTrue(result, result.matches(expected));
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_oneField() {
String toTest =
@@ -320,6 +337,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyFieldsFirstNull() {
String toTest =
@@ -332,6 +350,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field2=Googley, field3=World}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyFieldsOmitAfterNull() {
String toTest =
@@ -344,6 +363,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field2=Googley, field3=World}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyFieldsLastNull() {
String toTest =
@@ -356,6 +376,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{field1=Hello, field2=Googley}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitEmptyValues_oneValue() {
String toTest =
@@ -363,6 +384,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyValuesFirstNull() {
String toTest =
@@ -375,6 +397,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{Googley, World}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_manyValuesLastNull() {
String toTest =
@@ -387,6 +410,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals("TestClass{Hello, Googley}", toTest);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_differentOrder() {
String expected = "TestClass{field1=Hello, field2=Googley, field3=World}";
@@ -408,6 +432,7 @@ public class ToStringHelperTest extends TestCase {
assertEquals(expected, toTest2);
}
+ @J2ktIncompatible
@GwtIncompatible // Class names are obfuscated in GWT
public void testToStringOmitNullValues_canBeCalledManyTimes() {
String toTest =
diff --git a/guava-tests/test/com/google/common/base/Utf8Test.java b/guava-tests/test/com/google/common/base/Utf8Test.java
index 049e8d2ab..57464a9ee 100644
--- a/guava-tests/test/com/google/common/base/Utf8Test.java
+++ b/guava-tests/test/com/google/common/base/Utf8Test.java
@@ -26,6 +26,7 @@ import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.HashMap;
@@ -187,18 +188,21 @@ public class Utf8Test extends TestCase {
FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
/** Tests that round tripping of all two byte permutations work. */
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
public void testIsWellFormed_1Byte() {
testBytes(1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
}
/** Tests that round tripping of all two byte permutations work. */
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
public void testIsWellFormed_2Bytes() {
testBytes(2, EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
}
/** Tests that round tripping of all three byte permutations work. */
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
public void testIsWellFormed_3Bytes() {
@@ -302,6 +306,7 @@ public class Utf8Test extends TestCase {
* @param numBytes the number of bytes in the byte array
* @param expectedCount the expected number of roundtrippable permutations
*/
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
private static void testBytes(int numBytes, long expectedCount) {
testBytes(numBytes, expectedCount, 0, -1);
@@ -317,6 +322,7 @@ public class Utf8Test extends TestCase {
* @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max
* limit for numBytes
*/
+ @J2ktIncompatible
@GwtIncompatible // java.nio.charset.Charset
private static void testBytes(int numBytes, long expectedCount, long start, long lim) {
byte[] bytes = new byte[numBytes];
diff --git a/guava-tests/test/com/google/common/base/VerifyTest.java b/guava-tests/test/com/google/common/base/VerifyTest.java
index 37c6efc1a..36465ea30 100644
--- a/guava-tests/test/com/google/common/base/VerifyTest.java
+++ b/guava-tests/test/com/google/common/base/VerifyTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
@@ -93,6 +94,7 @@ public class VerifyTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
// Don't bother testing: Verify is like Preconditions. See the discussion on that class.
diff --git a/guava-tests/test/com/google/common/cache/AbstractCacheTest.java b/guava-tests/test/com/google/common/cache/AbstractCacheTest.java
index 13ef33db2..8602e5873 100644
--- a/guava-tests/test/com/google/common/cache/AbstractCacheTest.java
+++ b/guava-tests/test/com/google/common/cache/AbstractCacheTest.java
@@ -24,6 +24,7 @@ import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractCache}.
@@ -37,7 +38,7 @@ public class AbstractCacheTest extends TestCase {
Cache<Object, Object> cache =
new AbstractCache<Object, Object>() {
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -53,7 +54,7 @@ public class AbstractCacheTest extends TestCase {
Cache<Object, Object> cache =
new AbstractCache<Object, Object>() {
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return null;
}
};
@@ -67,7 +68,7 @@ public class AbstractCacheTest extends TestCase {
Cache<Object, Object> cache =
new AbstractCache<Object, Object>() {
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return cachedKey.equals(key) ? cachedValue : null;
}
};
diff --git a/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java b/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java
index c2ddef7b1..84e004a8b 100644
--- a/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java
+++ b/guava-tests/test/com/google/common/cache/AbstractLoadingCacheTest.java
@@ -23,6 +23,7 @@ import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractLoadingCache}.
@@ -46,7 +47,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -78,7 +79,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -110,7 +111,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
@@ -142,7 +143,7 @@ public class AbstractLoadingCacheTest extends TestCase {
}
@Override
- public Object getIfPresent(Object key) {
+ public @Nullable Object getIfPresent(Object key) {
return valueRef.get();
}
};
diff --git a/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java b/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java
index 5426ced0e..77a4734fb 100644
--- a/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java
+++ b/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java
@@ -125,10 +125,10 @@ class CacheBuilderFactory {
}
};
- private static final Function<Optional<?>, Object> OPTIONAL_TO_NULLABLE =
- new Function<Optional<?>, Object>() {
+ private static final Function<Optional<?>, @Nullable Object> OPTIONAL_TO_NULLABLE =
+ new Function<Optional<?>, @Nullable Object>() {
@Override
- public Object apply(Optional<?> optional) {
+ public @Nullable Object apply(Optional<?> optional) {
return optional.orNull();
}
};
@@ -158,14 +158,14 @@ class CacheBuilderFactory {
}
private CacheBuilder<Object, Object> createCacheBuilder(
- Integer concurrencyLevel,
- Integer initialCapacity,
- Integer maximumSize,
- DurationSpec expireAfterWrite,
- DurationSpec expireAfterAccess,
- DurationSpec refresh,
- Strength keyStrength,
- Strength valueStrength) {
+ @Nullable Integer concurrencyLevel,
+ @Nullable Integer initialCapacity,
+ @Nullable Integer maximumSize,
+ @Nullable DurationSpec expireAfterWrite,
+ @Nullable DurationSpec expireAfterAccess,
+ @Nullable DurationSpec refresh,
+ @Nullable Strength keyStrength,
+ @Nullable Strength valueStrength) {
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (concurrencyLevel != null) {
@@ -214,7 +214,7 @@ class CacheBuilderFactory {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o instanceof DurationSpec) {
DurationSpec that = (DurationSpec) o;
return unit.toNanos(duration) == that.unit.toNanos(that.duration);
diff --git a/guava-tests/test/com/google/common/cache/CacheBuilderGwtTest.java b/guava-tests/test/com/google/common/cache/CacheBuilderGwtTest.java
index 2ae81443b..5e05f4fde 100644
--- a/guava-tests/test/com/google/common/cache/CacheBuilderGwtTest.java
+++ b/guava-tests/test/com/google/common/cache/CacheBuilderGwtTest.java
@@ -298,8 +298,8 @@ public class CacheBuilderGwtTest extends TestCase {
// Expire the two present elements.
fakeTicker.advance(1001, TimeUnit.MILLISECONDS);
- cache.getIfPresent(23);
- cache.getIfPresent(56);
+ Integer unused1 = cache.getIfPresent(23);
+ Integer unused2 = cache.getIfPresent(56);
// Add two elements and invalidate them.
cache.put(1, 4);
diff --git a/guava-tests/test/com/google/common/cache/CacheBuilderTest.java b/guava-tests/test/com/google/common/cache/CacheBuilderTest.java
index 16488f3bb..dad5ff4fb 100644
--- a/guava-tests/test/com/google/common/cache/CacheBuilderTest.java
+++ b/guava-tests/test/com/google/common/cache/CacheBuilderTest.java
@@ -475,7 +475,6 @@ public class CacheBuilderTest extends TestCase {
}
@GwtIncompatible // QueuingRemovalListener
-
public void testRemovalNotification_clear() throws InterruptedException {
// If a clear() happens while a computation is pending, we should not get a removal
// notification.
diff --git a/guava-tests/test/com/google/common/cache/CacheExpirationTest.java b/guava-tests/test/com/google/common/cache/CacheExpirationTest.java
index c1416bd7d..ef9b690b1 100644
--- a/guava-tests/test/com/google/common/cache/CacheExpirationTest.java
+++ b/guava-tests/test/com/google/common/cache/CacheExpirationTest.java
@@ -339,7 +339,7 @@ public class CacheExpirationTest extends TestCase {
assertThat(keySet).containsExactly(2, 3, 4, 5, 6, 7, 8, 9, 0);
// get(K, Callable) doesn't stop 2 from expiring
- cache.get(2, Callables.returning(-2));
+ Integer unused = cache.get(2, Callables.returning(-2));
CacheTesting.drainRecencyQueues(cache);
ticker.advance(1, MILLISECONDS);
assertThat(keySet).containsExactly(3, 4, 5, 6, 7, 8, 9, 0);
@@ -403,7 +403,7 @@ public class CacheExpirationTest extends TestCase {
// get(K, Callable) fails to save 8, replace saves 6
cache.asMap().replace(6, -6);
- cache.get(8, Callables.returning(-8));
+ Integer unused = cache.get(8, Callables.returning(-8));
CacheTesting.drainRecencyQueues(cache);
ticker.advance(1, MILLISECONDS);
assertThat(keySet).containsExactly(3, 6);
diff --git a/guava-tests/test/com/google/common/cache/CacheLoaderTest.java b/guava-tests/test/com/google/common/cache/CacheLoaderTest.java
index e078dddd7..6312e0c79 100644
--- a/guava-tests/test/com/google/common/cache/CacheLoaderTest.java
+++ b/guava-tests/test/com/google/common/cache/CacheLoaderTest.java
@@ -78,10 +78,10 @@ public class CacheLoaderTest extends TestCase {
assertEquals(0, reloadCount.get());
assertEquals(0, loadAllCount.get());
- baseLoader.load(new Object());
+ Object unused1 = baseLoader.load(new Object());
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError = baseLoader.reload(new Object(), new Object());
- baseLoader.loadAll(ImmutableList.of(new Object()));
+ Map<Object, Object> unused2 = baseLoader.loadAll(ImmutableList.of(new Object()));
assertEquals(1, loadCount.get());
assertEquals(1, reloadCount.get());
assertEquals(1, loadAllCount.get());
@@ -89,10 +89,10 @@ public class CacheLoaderTest extends TestCase {
QueuingExecutor executor = new QueuingExecutor();
CacheLoader<Object, Object> asyncReloader = CacheLoader.asyncReloading(baseLoader, executor);
- asyncReloader.load(new Object());
+ Object unused3 = asyncReloader.load(new Object());
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError1 = asyncReloader.reload(new Object(), new Object());
- asyncReloader.loadAll(ImmutableList.of(new Object()));
+ Map<Object, Object> unused4 = asyncReloader.loadAll(ImmutableList.of(new Object()));
assertEquals(2, loadCount.get());
assertEquals(1, reloadCount.get());
assertEquals(2, loadAllCount.get());
diff --git a/guava-tests/test/com/google/common/cache/CacheLoadingTest.java b/guava-tests/test/com/google/common/cache/CacheLoadingTest.java
index f5ea54603..9b193ed7f 100644
--- a/guava-tests/test/com/google/common/cache/CacheLoadingTest.java
+++ b/guava-tests/test/com/google/common/cache/CacheLoadingTest.java
@@ -1767,6 +1767,7 @@ public class CacheLoadingTest extends TestCase {
}
+ @AndroidIncompatible // Depends on GC behavior
public void testReloadAfterValueReclamation() throws InterruptedException, ExecutionException {
CountingLoader countingLoader = new CountingLoader();
LoadingCache<Object, Object> cache =
@@ -1941,7 +1942,7 @@ public class CacheLoadingTest extends TestCase {
}
}
-
+ @AndroidIncompatible // Bug? expected:<1> but was:<2>
public void testConcurrentLoading() throws InterruptedException {
testConcurrentLoading(CacheBuilder.newBuilder());
}
@@ -1954,7 +1955,7 @@ public class CacheLoadingTest extends TestCase {
testConcurrentLoadingCheckedException(builder);
}
-
+ @AndroidIncompatible // Bug? expected:<1> but was:<2>
public void testConcurrentExpirationLoading() throws InterruptedException {
testConcurrentLoading(CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS));
}
@@ -2184,7 +2185,6 @@ public class CacheLoadingTest extends TestCase {
return resultList;
}
-
public void testAsMapDuringLoading() throws InterruptedException, ExecutionException {
final CountDownLatch getStartedSignal = new CountDownLatch(2);
final CountDownLatch letGetFinishSignal = new CountDownLatch(1);
@@ -2243,7 +2243,6 @@ public class CacheLoadingTest extends TestCase {
assertEquals(refreshKey + suffix, map.get(refreshKey));
}
-
public void testInvalidateDuringLoading() throws InterruptedException, ExecutionException {
// computation starts; invalidate() is called on the key being computed, computation finishes
final CountDownLatch computationStarted = new CountDownLatch(2);
@@ -2300,7 +2299,6 @@ public class CacheLoadingTest extends TestCase {
assertEquals(2, cache.size());
}
-
public void testInvalidateAndReloadDuringLoading()
throws InterruptedException, ExecutionException {
// computation starts; clear() is called, computation finishes
@@ -2373,7 +2371,6 @@ public class CacheLoadingTest extends TestCase {
assertEquals(refreshKey + suffix, map.get(refreshKey));
}
-
public void testExpandDuringLoading() throws InterruptedException {
final int count = 3;
final AtomicInteger callCount = new AtomicInteger();
@@ -2463,7 +2460,6 @@ public class CacheLoadingTest extends TestCase {
}
// Test ignored because it is extremely flaky in CI builds
-
public void
ignoreTestExpandDuringRefresh()
throws InterruptedException, ExecutionException {
diff --git a/guava-tests/test/com/google/common/cache/CacheTesting.java b/guava-tests/test/com/google/common/cache/CacheTesting.java
index 42b50b9f4..47a75c0ab 100644
--- a/guava-tests/test/com/google/common/cache/CacheTesting.java
+++ b/guava-tests/test/com/google/common/cache/CacheTesting.java
@@ -98,7 +98,7 @@ class CacheTesting {
}
/**
- * Forces the segment containing the given {@code key} to expand (see {@link Segment#expand()}.
+ * Forces the segment containing the given {@code key} to expand (see {@link Segment#expand()}).
*/
static <K, V> void forceExpandSegment(Cache<K, V> cache, K key) {
checkNotNull(cache);
diff --git a/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java b/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java
index 412ff7802..639a208bd 100644
--- a/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java
+++ b/guava-tests/test/com/google/common/cache/ForwardingCacheTest.java
@@ -104,7 +104,7 @@ public class ForwardingCacheTest extends TestCase {
private static class OnlyGet<K, V> extends ForwardingCache<K, V> {
@Override
protected Cache<K, V> delegate() {
- return null;
+ throw new AssertionError();
}
}
}
diff --git a/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java b/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java
index d78db2d37..fe4161213 100644
--- a/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java
+++ b/guava-tests/test/com/google/common/cache/ForwardingLoadingCacheTest.java
@@ -112,7 +112,7 @@ public class ForwardingLoadingCacheTest extends TestCase {
private static class OnlyGet<K, V> extends ForwardingLoadingCache<K, V> {
@Override
protected LoadingCache<K, V> delegate() {
- return null;
+ throw new AssertionError();
}
}
}
diff --git a/guava-tests/test/com/google/common/cache/LocalCacheMapComputeTest.java b/guava-tests/test/com/google/common/cache/LocalCacheMapComputeTest.java
index 3684a7006..61f5fed2d 100644
--- a/guava-tests/test/com/google/common/cache/LocalCacheMapComputeTest.java
+++ b/guava-tests/test/com/google/common/cache/LocalCacheMapComputeTest.java
@@ -165,7 +165,7 @@ public class LocalCacheMapComputeTest extends TestCase {
count,
n -> {
try {
- cache.get(key, () -> key);
+ String unused = cache.get(key, () -> key);
cache.asMap().compute(key, (k, v) -> null);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e);
diff --git a/guava-tests/test/com/google/common/cache/LocalCacheTest.java b/guava-tests/test/com/google/common/cache/LocalCacheTest.java
index db3b80015..7cc67e840 100644
--- a/guava-tests/test/com/google/common/cache/LocalCacheTest.java
+++ b/guava-tests/test/com/google/common/cache/LocalCacheTest.java
@@ -77,6 +77,7 @@ import java.util.logging.LogRecord;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** @author Charles Fry */
@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress.
@@ -98,7 +99,6 @@ public class LocalCacheTest extends TestCase {
}
}
-
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(LocalCacheTest.class);
@@ -327,7 +327,7 @@ public class LocalCacheTest extends TestCase {
}
public void testSetConcurrencyLevel() {
- // round up to nearest power of two
+ // round up to the nearest power of two
checkConcurrencyLevel(1, 1);
checkConcurrencyLevel(2, 2);
@@ -346,7 +346,7 @@ public class LocalCacheTest extends TestCase {
}
public void testSetInitialCapacity() {
- // share capacity over each segment, then round up to nearest power of two
+ // share capacity over each segment, then round up to the nearest power of two
checkInitialCapacity(1, 0, 1);
checkInitialCapacity(1, 1, 1);
@@ -714,7 +714,6 @@ public class LocalCacheTest extends TestCase {
assertTrue(notifications.toString(), notifications.isEmpty());
}
-
public void testCopyEntry_computing() {
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch computingSignal = new CountDownLatch(1);
@@ -816,7 +815,6 @@ public class LocalCacheTest extends TestCase {
checkLogged(e);
}
-
public void testRemovalListener_replaced_computing() {
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch computingSignal = new CountDownLatch(1);
@@ -2747,7 +2745,7 @@ public class LocalCacheTest extends TestCase {
// entries and values
private static <K, V> DummyEntry<K, V> createDummyEntry(
- K key, int hash, V value, ReferenceEntry<K, V> next) {
+ K key, int hash, V value, @Nullable ReferenceEntry<K, V> next) {
DummyEntry<K, V> entry = DummyEntry.create(key, hash, next);
DummyValueReference<K, V> valueRef = DummyValueReference.create(value);
entry.setValueReference(valueRef);
@@ -2755,7 +2753,7 @@ public class LocalCacheTest extends TestCase {
}
static class DummyEntry<K, V> implements ReferenceEntry<K, V> {
- private K key;
+ private @Nullable K key;
private final int hash;
private final ReferenceEntry<K, V> next;
@@ -2765,7 +2763,8 @@ public class LocalCacheTest extends TestCase {
this.next = next;
}
- public static <K, V> DummyEntry<K, V> create(K key, int hash, ReferenceEntry<K, V> next) {
+ public static <K, V> DummyEntry<K, V> create(
+ K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new DummyEntry<>(key, hash, next);
}
@@ -2874,7 +2873,7 @@ public class LocalCacheTest extends TestCase {
}
static class DummyValueReference<K, V> implements ValueReference<K, V> {
- private V value;
+ private @Nullable V value;
boolean loading = false;
public DummyValueReference() {
@@ -2904,7 +2903,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public ReferenceEntry<K, V> getEntry() {
+ public @Nullable ReferenceEntry<K, V> getEntry() {
return null;
}
@@ -2954,7 +2953,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableCacheLoader);
}
}
@@ -2970,7 +2969,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableRemovalListener);
}
}
@@ -2987,7 +2986,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableTicker);
}
}
@@ -3004,7 +3003,7 @@ public class LocalCacheTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof SerializableWeigher);
}
}
diff --git a/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java b/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java
index 8ba9dbc97..3a7f416ea 100644
--- a/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java
+++ b/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java
@@ -157,7 +157,7 @@ public class LocalLoadingCacheTest extends TestCase {
assertThat(map).containsEntry(three, one);
assertThat(map).containsEntry(one, two);
- // TODO(user): Confirm with fry@ that this is a reasonable substitute.
+ // TODO(cgruber): Confirm with fry@ that this is a reasonable substitute.
// Set<Entry<Object, Object>> entries = map.entrySet();
// assertThat(entries).containsExactly(
// Maps.immutableEntry(three, one), Maps.immutableEntry(one, two));
@@ -293,7 +293,6 @@ public class LocalLoadingCacheTest extends TestCase {
assertFalse(segment.recencyQueue.isEmpty());
}
-
public void testRecursiveComputation() throws InterruptedException {
final AtomicReference<LoadingCache<Integer, String>> cacheRef = new AtomicReference<>();
CacheLoader<Integer, String> recursiveLoader =
@@ -324,7 +323,7 @@ public class LocalLoadingCacheTest extends TestCase {
recursiveCache = CacheBuilder.newBuilder().weakKeys().weakValues().build(recursiveLoader);
cacheRef.set(recursiveCache);
- // tells the test when the compution has completed
+ // tells the test when the computation has completed
final CountDownLatch doneSignal = new CountDownLatch(1);
Thread thread =
diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java
new file mode 100644
index 000000000..e5cea6b55
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/AbstractImmutableBiMapMapInterfaceTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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 com.google.common.base.Joiner;
+import com.google.common.collect.testing.MapInterfaceTest;
+import java.util.Map;
+import java.util.Map.Entry;
+
+@GwtCompatible
+abstract class AbstractImmutableBiMapMapInterfaceTest<K, V> extends MapInterfaceTest<K, V> {
+ AbstractImmutableBiMapMapInterfaceTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ protected Map<K, V> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ private static final Joiner JOINER = Joiner.on(", ");
+
+ @Override
+ protected final void assertMoreInvariants(Map<K, V> map) {
+ BiMap<K, V> bimap = (BiMap<K, V>) map;
+
+ for (Entry<K, V> entry : map.entrySet()) {
+ assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
+ assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue()));
+ }
+
+ assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
+ assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
+ assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
+ assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
+
+ assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
+ assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..62359f0a4
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/AbstractImmutableMapMapInterfaceTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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 com.google.common.base.Joiner;
+import com.google.common.collect.testing.MapInterfaceTest;
+import com.google.common.collect.testing.MinimalSet;
+import java.util.Map;
+import java.util.Map.Entry;
+
+@GwtCompatible
+abstract class AbstractImmutableMapMapInterfaceTest<K, V> extends MapInterfaceTest<K, V> {
+ AbstractImmutableMapMapInterfaceTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ protected Map<K, V> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ private static final Joiner JOINER = Joiner.on(", ");
+
+ @Override
+ protected final void assertMoreInvariants(Map<K, V> map) {
+ // TODO: can these be moved to MapInterfaceTest?
+ for (Entry<K, V> entry : map.entrySet()) {
+ assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
+ }
+
+ assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
+ assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
+ assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
+ assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
+
+ assertEquals(MinimalSet.from(map.entrySet()), map.entrySet());
+ assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java
index d7a8d16ca..705b15a48 100644
--- a/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java
+++ b/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java
@@ -33,6 +33,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base class for {@link ImmutableSet} and {@link ImmutableSortedSet} tests.
@@ -59,7 +60,7 @@ public abstract class AbstractImmutableSetTest extends TestCase {
protected abstract <E extends Comparable<? super E>> Set<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... rest);
- protected abstract <E extends Comparable<? super E>> Set<E> copyOf(E[] elements);
+ protected abstract <E extends Comparable<? super E>> Set<E> copyOf(E @Nullable [] elements);
protected abstract <E extends Comparable<? super E>> Set<E> copyOf(
Collection<? extends E> elements);
diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..bee92bd30
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/AbstractImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2009 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 com.google.common.base.Joiner;
+import com.google.common.collect.testing.SortedMapInterfaceTest;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.SortedMap;
+
+@GwtCompatible
+public abstract class AbstractImmutableSortedMapMapInterfaceTest<K, V>
+ extends SortedMapInterfaceTest<K, V> {
+ public AbstractImmutableSortedMapMapInterfaceTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ protected SortedMap<K, V> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ private static final Joiner joiner = Joiner.on(", ");
+
+ @Override
+ protected void assertMoreInvariants(Map<K, V> map) {
+ // TODO: can these be moved to MapInterfaceTest?
+ for (Entry<K, V> entry : map.entrySet()) {
+ assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
+ }
+
+ assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
+ assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
+ assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
+ assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());
+
+ assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
+ assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java b/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java
index a76907cda..9ca7420f6 100644
--- a/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java
+++ b/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java
@@ -51,8 +51,7 @@ public class AbstractIteratorTest extends TestCase {
case 2:
return endOfData();
default:
- fail("Should not have been invoked again");
- return null;
+ throw new AssertionError("Should not have been invoked again");
}
}
};
@@ -97,8 +96,7 @@ public class AbstractIteratorTest extends TestCase {
case 2:
return endOfData();
default:
- fail("Should not have been invoked again");
- return null;
+ throw new AssertionError("Should not have been invoked again");
}
}
};
@@ -139,6 +137,7 @@ public class AbstractIteratorTest extends TestCase {
@GwtIncompatible // weak references
+ @AndroidIncompatible // depends on details of GC
public void testFreesNextReference() {
Iterator<Object> itr =
new AbstractIterator<Object>() {
@@ -188,12 +187,12 @@ public class AbstractIteratorTest extends TestCase {
@Override
public Integer computeNext() {
if (haveBeenCalled) {
- fail("Should not have been called again");
+ throw new AssertionError("Should not have been called again");
} else {
haveBeenCalled = true;
sneakyThrow(new SomeCheckedException());
+ throw new AssertionError(); // unreachable
}
- return null; // never reached
}
};
@@ -281,7 +280,7 @@ public class AbstractIteratorTest extends TestCase {
@Override
protected Integer computeNext() {
boolean unused = hasNext();
- return null;
+ throw new AssertionError();
}
};
try {
@@ -295,7 +294,7 @@ public class AbstractIteratorTest extends TestCase {
// hasNext/next/peek), but we'll cop out for now, knowing that peek() and
// next() both start by invoking hasNext() anyway.
- /** Throws a undeclared checked exception. */
+ /** Throws an undeclared checked exception. */
private static void sneakyThrow(Throwable t) {
class SneakyThrower<T extends Throwable> {
@SuppressWarnings("unchecked") // not really safe, but that's the point
diff --git a/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java b/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java
index 63c17deda..6e6b25497 100644
--- a/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java
+++ b/guava-tests/test/com/google/common/collect/AbstractMapEntryTest.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import java.util.Collections;
import java.util.Map.Entry;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code AbstractMapEntry}.
@@ -28,8 +29,8 @@ import junit.framework.TestCase;
*/
@GwtCompatible
public class AbstractMapEntryTest extends TestCase {
- private static final String NK = null;
- private static final Integer NV = null;
+ private static final @Nullable String NK = null;
+ private static final @Nullable Integer NV = null;
private static <K, V> Entry<K, V> entry(final K key, final V value) {
return new AbstractMapEntry<K, V>() {
diff --git a/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java b/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
index f63f01ae3..16a9ba781 100644
--- a/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
+++ b/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
@@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Tests for {@link AbstractSequentialIterator}. */
@GwtCompatible(emulated = true)
@@ -60,7 +61,7 @@ public class AbstractSequentialIteratorTest extends TestCase {
Iterator<Integer> powersOfTwo =
new AbstractSequentialIterator<Integer>(1) {
@Override
- protected Integer computeNext(Integer previous) {
+ protected @Nullable Integer computeNext(Integer previous) {
return (previous == 1 << 30) ? null : previous * 2;
}
};
@@ -137,7 +138,7 @@ public class AbstractSequentialIteratorTest extends TestCase {
private static Iterator<Integer> newDoubler(int first, final int last) {
return new AbstractSequentialIterator<Integer>(first) {
@Override
- protected Integer computeNext(Integer previous) {
+ protected @Nullable Integer computeNext(Integer previous) {
return (previous == last) ? null : previous * 2;
}
};
diff --git a/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java b/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java
new file mode 100644
index 000000000..15e7a4bf6
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ArrayTableColumnMapTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableColumnMapTest extends ColumnMapTests {
+ public ArrayTableColumnMapTest() {
+ super(true, false, false, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ return ArrayTable.create(Arrays.asList(1, 2, 3), Arrays.asList("foo", "bar", "dog"));
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java b/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java
new file mode 100644
index 000000000..81acac43f
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ArrayTableColumnTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableColumnTest extends ColumnTests {
+ public ArrayTableColumnTest() {
+ super(true, true, false, false, false);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ return ArrayTable.create(
+ Arrays.asList("one", "two", "three", "four"), Arrays.asList('a', 'b', 'c'));
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java b/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java
new file mode 100644
index 000000000..b1f76cf28
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ArrayTableRowMapTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableRowMapTest extends RowMapTests {
+ public ArrayTableRowMapTest() {
+ super(true, false, false, false);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ return ArrayTable.create(Arrays.asList("foo", "bar", "dog"), Arrays.asList(1, 2, 3));
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java b/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java
new file mode 100644
index 000000000..cad5783a9
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ArrayTableRowTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Arrays;
+import java.util.Map;
+
+@GwtIncompatible // TODO(hhchan): ArrayTable
+public class ArrayTableRowTest extends RowTests {
+ public ArrayTableRowTest() {
+ super(true, true, false, false, false);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Table<Character, String, Integer> makeTable() {
+ return ArrayTable.create(
+ Arrays.asList('a', 'b', 'c'), Arrays.asList("one", "two", "three", "four"));
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java b/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
index 65d2ef6f4..0a524fca4 100644
--- a/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
+++ b/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
@@ -386,7 +386,7 @@ final class BenchmarkHelpers {
public <E> Interner<E> create(Collection<E> contents) {
Interner<E> interner = Interners.newWeakInterner();
for (E e : contents) {
- interner.intern(e);
+ E unused = interner.intern(e);
}
return interner;
}
@@ -396,7 +396,7 @@ final class BenchmarkHelpers {
public <E> Interner<E> create(Collection<E> contents) {
Interner<E> interner = Interners.newStrongInterner();
for (E e : contents) {
- interner.intern(e);
+ E unused = interner.intern(e);
}
return interner;
}
diff --git a/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java b/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
index cdc7a91cc..0504e6a74 100644
--- a/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
+++ b/guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
@@ -22,6 +22,7 @@ import com.google.common.primitives.Ints;
import java.util.Collections;
import java.util.List;
import java.util.Set;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Package up sample data for common collections benchmarking.
@@ -111,7 +112,7 @@ class CollectionBenchmarkSampleData {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return this == obj || (obj instanceof Element && ((Element) obj).hash == hash);
}
@@ -137,7 +138,7 @@ class CollectionBenchmarkSampleData {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return slowItDown() != 1 && super.equals(obj);
}
diff --git a/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java b/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java
new file mode 100644
index 000000000..8a783ec6e
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/Collections2FilterArrayListTest.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredCollectionTest;
+import java.util.Collection;
+
+public final class Collections2FilterArrayListTest
+ extends AbstractFilteredCollectionTest<Collection<Integer>> {
+ @Override
+ Collection<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Lists.newArrayList(contents);
+ }
+
+ @Override
+ Collection<Integer> filter(Collection<Integer> elements, Predicate<? super Integer> predicate) {
+ return Collections2.filter(elements, predicate);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/Collections2Test.java b/guava-tests/test/com/google/common/collect/Collections2Test.java
index 4b8761893..2cf05f632 100644
--- a/guava-tests/test/com/google/common/collect/Collections2Test.java
+++ b/guava-tests/test/com/google/common/collect/Collections2Test.java
@@ -16,16 +16,15 @@
package com.google.common.collect;
+import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newLinkedList;
import static com.google.common.truth.Truth.assertThat;
-import static java.util.Arrays.asList;
import static java.util.Collections.nCopies;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.TestStringCollectionGenerator;
@@ -40,6 +39,7 @@ import java.util.NoSuchElementException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Collections2}.
@@ -62,29 +62,10 @@ public class Collections2Test extends TestCase {
return suite;
}
- static final Predicate<String> NOT_YYY_ZZZ =
- new Predicate<String>() {
- @Override
- public boolean apply(String input) {
- return !"yyy".equals(input) && !"zzz".equals(input);
- }
- };
-
- static final Predicate<String> LENGTH_1 =
- new Predicate<String>() {
- @Override
- public boolean apply(String input) {
- return input.length() == 1;
- }
- };
-
- static final Predicate<String> STARTS_WITH_VOWEL =
- new Predicate<String>() {
- @Override
- public boolean apply(String input) {
- return asList('a', 'e', 'i', 'o', 'u').contains(input.charAt(0));
- }
- };
+ static final Predicate<@Nullable String> NOT_YYY_ZZZ =
+ input -> !"yyy".equals(input) && !"zzz".equals(input);
+
+ static final Predicate<String> LENGTH_1 = input -> input.length() == 1;
@GwtIncompatible // suite
private static Test testsForFilter() {
@@ -200,25 +181,18 @@ public class Collections2Test extends TestCase {
.createTestSuite();
}
- private static final Function<String, String> REMOVE_FIRST_CHAR =
- new Function<String, String>() {
- @Override
- public String apply(String from) {
- return ((from == null) || "".equals(from)) ? null : from.substring(1);
- }
- };
-
@GwtIncompatible // suite
private static Test testsForTransform() {
return CollectionTestSuiteBuilder.using(
new TestStringCollectionGenerator() {
@Override
- public Collection<String> create(String[] elements) {
- List<String> list = newArrayList();
+ public Collection<@Nullable String> create(@Nullable String[] elements) {
+ List<@Nullable String> list = newArrayList();
for (String element : elements) {
list.add((element == null) ? null : "q" + element);
}
- return Collections2.transform(list, REMOVE_FIRST_CHAR);
+ return Collections2.transform(
+ list, from -> isNullOrEmpty(from) ? null : from.substring(1));
}
})
.named("Collections2.transform")
diff --git a/guava-tests/test/com/google/common/collect/ComparatorsTest.java b/guava-tests/test/com/google/common/collect/ComparatorsTest.java
index 3f568c115..473f1d753 100644
--- a/guava-tests/test/com/google/common/collect/ComparatorsTest.java
+++ b/guava-tests/test/com/google/common/collect/ComparatorsTest.java
@@ -30,6 +30,7 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.Optional;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Comparators}.
@@ -161,7 +162,7 @@ public class ComparatorsTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof Foo) && ((Foo) o).value.equals(value);
}
diff --git a/guava-tests/test/com/google/common/collect/ComparisonChainTest.java b/guava-tests/test/com/google/common/collect/ComparisonChainTest.java
index 9a9f98a8c..d697ebb79 100644
--- a/guava-tests/test/com/google/common/collect/ComparisonChainTest.java
+++ b/guava-tests/test/com/google/common/collect/ComparisonChainTest.java
@@ -16,9 +16,20 @@
package com.google.common.collect;
+import static com.google.common.base.MoreObjects.toStringHelper;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+import static java.lang.Integer.signum;
+import static java.util.Comparator.comparing;
+import static java.util.Comparator.naturalOrder;
+import static java.util.Comparator.nullsLast;
+
import com.google.common.annotations.GwtCompatible;
+import com.google.common.primitives.Booleans;
+import java.util.Comparator;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ComparisonChain}.
@@ -36,77 +47,175 @@ public class ComparisonChainTest extends TestCase {
}
}
+ @SuppressWarnings("deprecation")
public void testCompareBooleans() {
- assertEquals(
- 0,
- ComparisonChain.start()
- .compare(true, true)
- .compare(true, Boolean.TRUE)
- .compare(Boolean.TRUE, true)
- .compare(Boolean.TRUE, Boolean.TRUE)
- .result());
+ assertThat(
+ ComparisonChain.start()
+ .compare(true, true)
+ .compare(true, Boolean.TRUE)
+ .compare(Boolean.TRUE, true)
+ .compare(Boolean.TRUE, Boolean.TRUE)
+ .result())
+ .isEqualTo(0);
}
public void testDegenerate() {
// kinda bogus, but who cares?
- assertEquals(0, ComparisonChain.start().result());
+ assertThat(ComparisonChain.start().result()).isEqualTo(0);
}
public void testOneEqual() {
- assertEquals(0, ComparisonChain.start().compare("a", "a").result());
+ assertThat(ComparisonChain.start().compare("a", "a").result()).isEqualTo(0);
}
public void testOneEqualUsingComparator() {
- assertEquals(
- 0, ComparisonChain.start().compare("a", "A", String.CASE_INSENSITIVE_ORDER).result());
+ assertThat(ComparisonChain.start().compare("a", "A", String.CASE_INSENSITIVE_ORDER).result())
+ .isEqualTo(0);
}
public void testManyEqual() {
- assertEquals(
- 0,
- ComparisonChain.start()
- .compare(1, 1)
- .compare(1L, 1L)
- .compareFalseFirst(true, true)
- .compare(1.0, 1.0)
- .compare(1.0f, 1.0f)
- .compare("a", "a", Ordering.usingToString())
- .result());
+ assertThat(
+ ComparisonChain.start()
+ .compare(1, 1)
+ .compare(1L, 1L)
+ .compareFalseFirst(true, true)
+ .compare(1.0, 1.0)
+ .compare(1.0f, 1.0f)
+ .compare("a", "a", Ordering.usingToString())
+ .result())
+ .isEqualTo(0);
}
public void testShortCircuitLess() {
- assertTrue(
- ComparisonChain.start().compare("a", "b").compare(DONT_COMPARE_ME, DONT_COMPARE_ME).result()
- < 0);
+ assertThat(
+ ComparisonChain.start()
+ .compare("a", "b")
+ .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
+ .result())
+ .isLessThan(0);
}
public void testShortCircuitGreater() {
- assertTrue(
- ComparisonChain.start().compare("b", "a").compare(DONT_COMPARE_ME, DONT_COMPARE_ME).result()
- > 0);
+ assertThat(
+ ComparisonChain.start()
+ .compare("b", "a")
+ .compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
+ .result())
+ .isGreaterThan(0);
}
public void testShortCircuitSecondStep() {
- assertTrue(
- ComparisonChain.start()
+ assertThat(
+ ComparisonChain.start()
.compare("a", "a")
.compare("a", "b")
.compare(DONT_COMPARE_ME, DONT_COMPARE_ME)
- .result()
- < 0);
+ .result())
+ .isLessThan(0);
}
public void testCompareFalseFirst() {
- assertTrue(ComparisonChain.start().compareFalseFirst(true, true).result() == 0);
- assertTrue(ComparisonChain.start().compareFalseFirst(true, false).result() > 0);
- assertTrue(ComparisonChain.start().compareFalseFirst(false, true).result() < 0);
- assertTrue(ComparisonChain.start().compareFalseFirst(false, false).result() == 0);
+ assertThat(ComparisonChain.start().compareFalseFirst(true, true).result()).isEqualTo(0);
+ assertThat(ComparisonChain.start().compareFalseFirst(true, false).result()).isGreaterThan(0);
+ assertThat(ComparisonChain.start().compareFalseFirst(false, true).result()).isLessThan(0);
+ assertThat(ComparisonChain.start().compareFalseFirst(false, false).result()).isEqualTo(0);
}
public void testCompareTrueFirst() {
- assertTrue(ComparisonChain.start().compareTrueFirst(true, true).result() == 0);
- assertTrue(ComparisonChain.start().compareTrueFirst(true, false).result() < 0);
- assertTrue(ComparisonChain.start().compareTrueFirst(false, true).result() > 0);
- assertTrue(ComparisonChain.start().compareTrueFirst(false, false).result() == 0);
+ assertThat(ComparisonChain.start().compareTrueFirst(true, true).result()).isEqualTo(0);
+ assertThat(ComparisonChain.start().compareTrueFirst(true, false).result()).isLessThan(0);
+ assertThat(ComparisonChain.start().compareTrueFirst(false, true).result()).isGreaterThan(0);
+ assertThat(ComparisonChain.start().compareTrueFirst(false, false).result()).isEqualTo(0);
+ }
+
+ enum TriState {
+ FALSE,
+ MAYBE,
+ TRUE,
+ }
+
+ static class Foo {
+ private final String aString;
+ private final int anInt;
+ private final @Nullable TriState anEnum;
+
+ Foo(String aString, int anInt, @Nullable TriState anEnum) {
+ this.aString = aString;
+ this.anInt = anInt;
+ this.anEnum = anEnum;
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(this)
+ .add("aString", aString)
+ .add("anInt", anInt)
+ .add("anEnum", anEnum)
+ .toString();
+ }
+ }
+
+ /** Validates that the Comparator equivalent we document is correct. */
+ public void testComparatorEquivalent() {
+ Comparator<Foo> comparatorUsingComparisonChain =
+ (a, b) ->
+ ComparisonChain.start()
+ .compare(a.aString, b.aString)
+ .compare(a.anInt, b.anInt)
+ .compare(a.anEnum, b.anEnum, Ordering.natural().nullsLast())
+ .result();
+ Comparator<Foo> comparatorUsingComparatorMethods =
+ comparing((Foo foo) -> foo.aString)
+ .thenComparing(foo -> foo.anInt)
+ .thenComparing(foo -> foo.anEnum, nullsLast(naturalOrder()));
+ ImmutableList<Foo> instances =
+ ImmutableList.of(
+ new Foo("a", 1, TriState.TRUE),
+ new Foo("a", 2, TriState.TRUE),
+ new Foo("b", 1, TriState.FALSE),
+ new Foo("b", 1, TriState.TRUE),
+ new Foo("b", 1, null));
+ for (Foo a : instances) {
+ for (Foo b : instances) {
+ int comparedUsingComparisonChain = signum(comparatorUsingComparisonChain.compare(a, b));
+ int comparedUsingComparatorMethods = signum(comparatorUsingComparatorMethods.compare(a, b));
+ assertWithMessage("%s vs %s", a, b)
+ .that(comparedUsingComparatorMethods)
+ .isEqualTo(comparedUsingComparisonChain);
+ }
+ }
+ }
+
+ static class Bar {
+ private final boolean isBaz;
+
+ Bar(boolean isBaz) {
+ this.isBaz = isBaz;
+ }
+
+ boolean isBaz() {
+ return isBaz;
+ }
+ }
+
+ /**
+ * Validates that {@link Booleans#trueFirst()} and {@link Booleans#falseFirst()} can be used with
+ * {@link Comparator} when replacing {@link ComparisonChain#compareTrueFirst} and {@link
+ * ComparisonChain#compareFalseFirst}, as we document.
+ */
+ public void testTrueFirstFalseFirst() {
+ Bar trueBar = new Bar(true);
+ Bar falseBar = new Bar(false);
+
+ assertThat(ComparisonChain.start().compareTrueFirst(trueBar.isBaz(), falseBar.isBaz()).result())
+ .isLessThan(0);
+ Comparator<Bar> trueFirstComparator = comparing(Bar::isBaz, Booleans.trueFirst());
+ assertThat(trueFirstComparator.compare(trueBar, falseBar)).isLessThan(0);
+
+ assertThat(
+ ComparisonChain.start().compareFalseFirst(falseBar.isBaz(), trueBar.isBaz()).result())
+ .isLessThan(0);
+ Comparator<Bar> falseFirstComparator = comparing(Bar::isBaz, Booleans.falseFirst());
+ assertThat(falseFirstComparator.compare(falseBar, trueBar)).isLessThan(0);
}
}
diff --git a/guava-tests/test/com/google/common/collect/EnumBiMapTest.java b/guava-tests/test/com/google/common/collect/EnumBiMapTest.java
index 25b057a72..fa927e2d8 100644
--- a/guava-tests/test/com/google/common/collect/EnumBiMapTest.java
+++ b/guava-tests/test/com/google/common/collect/EnumBiMapTest.java
@@ -183,11 +183,13 @@ public class EnumBiMapTest extends TestCase {
assertEquals(bimap3, emptyBimap);
}
+ @GwtIncompatible // keyType
public void testKeyType() {
EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class);
assertEquals(Currency.class, bimap.keyType());
}
+ @GwtIncompatible // valueType
public void testValueType() {
EnumBiMap<Currency, Country> bimap = EnumBiMap.create(Currency.class, Country.class);
assertEquals(Country.class, bimap.valueType());
diff --git a/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java b/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java
index 2a78f5547..24f395328 100644
--- a/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java
+++ b/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java
@@ -197,6 +197,7 @@ public class EnumHashBiMapTest extends TestCase {
assertEquals(bimap3, emptyBimap);
}
+ @GwtIncompatible // keyType
public void testKeyType() {
EnumHashBiMap<Currency, String> bimap = EnumHashBiMap.create(Currency.class);
assertEquals(Currency.class, bimap.keyType());
diff --git a/guava-tests/test/com/google/common/collect/FauxveridesTest.java b/guava-tests/test/com/google/common/collect/FauxveridesTest.java
index ff0b86bf9..f7eda67d5 100644
--- a/guava-tests/test/com/google/common/collect/FauxveridesTest.java
+++ b/guava-tests/test/com/google/common/collect/FauxveridesTest.java
@@ -34,6 +34,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests that all {@code public static} methods "inherited" from superclasses are "overridden" in
@@ -176,7 +177,7 @@ public class FauxveridesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof MethodSignature) {
MethodSignature other = (MethodSignature) obj;
return name.equals(other.name)
@@ -219,7 +220,7 @@ public class FauxveridesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof TypeSignature) {
TypeSignature other = (TypeSignature) obj;
return parameterSignatures.equals(other.parameterSignatures);
@@ -251,7 +252,7 @@ public class FauxveridesTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof TypeParameterSignature) {
TypeParameterSignature other = (TypeParameterSignature) obj;
/*
diff --git a/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java b/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java
new file mode 100644
index 000000000..f575a73c4
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/FilteredBiMapTest.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2007 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;
+
+@GwtCompatible
+public class FilteredBiMapTest extends FilteredMapTest {
+ @Override
+ BiMap<String, Integer> createUnfiltered() {
+ return HashBiMap.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java b/guava-tests/test/com/google/common/collect/FilteredCollectionsTestUtil.java
index 85b4e214d..95bfac5bc 100644
--- a/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java
+++ b/guava-tests/test/com/google/common/collect/FilteredCollectionsTestUtil.java
@@ -29,15 +29,19 @@ import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
-import java.util.TreeSet;
import junit.framework.TestCase;
/**
- * Tests for filtered collection views.
+ * Class that contains nested abstract tests for filtered collection views, along with their
+ * implementation helpers.
*
* @author Louis Wasserman
*/
-public class FilteredCollectionsTest extends TestCase {
+/*
+ * TODO(cpovirk): Should all the tests for filtered collections run under GWT, too? Currently, they
+ * don't.
+ */
+public final class FilteredCollectionsTestUtil {
private static final Predicate<Integer> EVEN =
new Predicate<Integer>() {
@Override
@@ -389,79 +393,5 @@ public class FilteredCollectionsTest extends TestCase {
}
}
- // implementation tests
-
- public static final class IterablesFilterArrayListTest
- extends AbstractFilteredIterableTest<Iterable<Integer>> {
- @Override
- Iterable<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Lists.newArrayList(contents);
- }
-
- @Override
- Iterable<Integer> filter(Iterable<Integer> elements, Predicate<? super Integer> predicate) {
- return Iterables.filter(elements, predicate);
- }
- }
-
- public static final class Collections2FilterArrayListTest
- extends AbstractFilteredCollectionTest<Collection<Integer>> {
- @Override
- Collection<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Lists.newArrayList(contents);
- }
-
- @Override
- Collection<Integer> filter(Collection<Integer> elements, Predicate<? super Integer> predicate) {
- return Collections2.filter(elements, predicate);
- }
- }
-
- public static final class SetsFilterHashSetTest extends AbstractFilteredSetTest<Set<Integer>> {
- @Override
- Set<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Sets.newHashSet(contents);
- }
-
- @Override
- Set<Integer> filter(Set<Integer> elements, Predicate<? super Integer> predicate) {
- return Sets.filter(elements, predicate);
- }
- }
-
- public static final class SetsFilterSortedSetTest
- extends AbstractFilteredSortedSetTest<SortedSet<Integer>> {
- @Override
- SortedSet<Integer> createUnfiltered(Iterable<Integer> contents) {
- final TreeSet<Integer> result = Sets.newTreeSet(contents);
- // we have to make the result not Navigable
- return new ForwardingSortedSet<Integer>() {
- @Override
- protected SortedSet<Integer> delegate() {
- return result;
- }
- };
- }
-
- @Override
- SortedSet<Integer> filter(SortedSet<Integer> elements, Predicate<? super Integer> predicate) {
- return Sets.filter(elements, predicate);
- }
- }
-
- public static final class SetsFilterNavigableSetTest extends AbstractFilteredNavigableSetTest {
- @Override
- NavigableSet<Integer> createUnfiltered(Iterable<Integer> contents) {
- return Sets.newTreeSet(contents);
- }
-
- @Override
- NavigableSet<Integer> filter(
- NavigableSet<Integer> elements, Predicate<? super Integer> predicate) {
- return Sets.filter(elements, predicate);
- }
- }
-
- /** No-op test so that the class has at least one method, making Maven's test runner happy. */
- public void testNoop() {}
+ private FilteredCollectionsTestUtil() {}
}
diff --git a/guava-tests/test/com/google/common/collect/FilteredMapTest.java b/guava-tests/test/com/google/common/collect/FilteredMapTest.java
new file mode 100644
index 000000000..159fec9a9
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/FilteredMapTest.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.collect.MapsTest.CORRECT_LENGTH;
+import static com.google.common.collect.MapsTest.EVEN;
+import static com.google.common.collect.MapsTest.NOT_LENGTH_3;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import java.util.Map;
+import java.util.Map.Entry;
+import junit.framework.TestCase;
+
+@GwtCompatible
+public class FilteredMapTest extends TestCase {
+ Map<String, Integer> createUnfiltered() {
+ return Maps.newHashMap();
+ }
+
+ public void testFilteredKeysIllegalPut() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
+ filtered.put("a", 1);
+ filtered.put("b", 2);
+ assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
+
+ try {
+ filtered.put("yyy", 3);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testFilteredKeysIllegalPutAll() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
+ filtered.put("a", 1);
+ filtered.put("b", 2);
+ assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
+
+ try {
+ filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
+ }
+
+ public void testFilteredKeysFilteredReflectsBackingChanges() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
+ unfiltered.put("two", 2);
+ unfiltered.put("three", 3);
+ unfiltered.put("four", 4);
+ assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered);
+ assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered);
+
+ unfiltered.remove("three");
+ assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered);
+ assertEquals(ImmutableMap.of("four", 4), filtered);
+
+ unfiltered.clear();
+ assertEquals(ImmutableMap.of(), unfiltered);
+ assertEquals(ImmutableMap.of(), filtered);
+ }
+
+ public void testFilteredValuesIllegalPut() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ filtered.put("a", 2);
+ unfiltered.put("b", 4);
+ unfiltered.put("c", 5);
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+
+ try {
+ filtered.put("yyy", 3);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+ }
+
+ public void testFilteredValuesIllegalPutAll() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ filtered.put("a", 2);
+ unfiltered.put("b", 4);
+ unfiltered.put("c", 5);
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+
+ try {
+ filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+ }
+
+ public void testFilteredValuesIllegalSetValue() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ filtered.put("a", 2);
+ filtered.put("b", 4);
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+
+ Entry<String, Integer> entry = filtered.entrySet().iterator().next();
+ try {
+ entry.setValue(5);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
+ }
+
+ public void testFilteredValuesClear() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("one", 1);
+ unfiltered.put("two", 2);
+ unfiltered.put("three", 3);
+ unfiltered.put("four", 4);
+ Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
+ assertEquals(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), unfiltered);
+ assertEquals(ImmutableMap.of("two", 2, "four", 4), filtered);
+
+ filtered.clear();
+ assertEquals(ImmutableMap.of("one", 1, "three", 3), unfiltered);
+ assertTrue(filtered.isEmpty());
+ }
+
+ public void testFilteredEntriesIllegalPut() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
+
+ filtered.put("chicken", 7);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+
+ try {
+ filtered.put("cow", 7);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+ }
+
+ public void testFilteredEntriesIllegalPutAll() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
+
+ filtered.put("chicken", 7);
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+
+ try {
+ filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
+ }
+
+ public void testFilteredEntriesObjectPredicate() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Predicate<Object> predicate = Predicates.alwaysFalse();
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
+ assertTrue(filtered.isEmpty());
+ }
+
+ public void testFilteredEntriesWildCardEntryPredicate() {
+ Map<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 2);
+ unfiltered.put("horse", 5);
+ Predicate<Entry<?, ?>> predicate =
+ new Predicate<Entry<?, ?>>() {
+ @Override
+ public boolean apply(Entry<?, ?> input) {
+ return "cat".equals(input.getKey()) || Integer.valueOf(2) == input.getValue();
+ }
+ };
+ Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
+ assertEquals(ImmutableMap.of("cat", 3, "dog", 2), filtered);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java b/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java
new file mode 100644
index 000000000..23b3f2a99
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/FilteredSortedMapTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.collect.MapsTest.CORRECT_LENGTH;
+
+import com.google.common.annotations.GwtCompatible;
+import java.util.SortedMap;
+
+@GwtCompatible
+public class FilteredSortedMapTest extends FilteredMapTest {
+ @Override
+ SortedMap<String, Integer> createUnfiltered() {
+ return Maps.newTreeMap();
+ }
+
+ public void testFirstAndLastKeyFilteredMap() {
+ SortedMap<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("apple", 2);
+ unfiltered.put("banana", 6);
+ unfiltered.put("cat", 3);
+ unfiltered.put("dog", 5);
+
+ SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+ assertEquals("banana", filtered.firstKey());
+ assertEquals("cat", filtered.lastKey());
+ }
+
+ public void testHeadSubTailMap_FilteredMap() {
+ SortedMap<String, Integer> unfiltered = createUnfiltered();
+ unfiltered.put("apple", 2);
+ unfiltered.put("banana", 6);
+ unfiltered.put("cat", 4);
+ unfiltered.put("dog", 3);
+ SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
+
+ assertEquals(ImmutableMap.of("banana", 6), filtered.headMap("dog"));
+ assertEquals(ImmutableMap.of(), filtered.headMap("banana"));
+ assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.headMap("emu"));
+
+ assertEquals(ImmutableMap.of("banana", 6), filtered.subMap("banana", "dog"));
+ assertEquals(ImmutableMap.of("dog", 3), filtered.subMap("cat", "emu"));
+
+ assertEquals(ImmutableMap.of("dog", 3), filtered.tailMap("cat"));
+ assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.tailMap("banana"));
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/FluentIterableTest.java b/guava-tests/test/com/google/common/collect/FluentIterableTest.java
index 6a9c2d73f..5a3236cf9 100644
--- a/guava-tests/test/com/google/common/collect/FluentIterableTest.java
+++ b/guava-tests/test/com/google/common/collect/FluentIterableTest.java
@@ -61,7 +61,7 @@ public class FluentIterableTest extends TestCase {
}
public void testFromArrayAndAppend() {
- FluentIterable<TimeUnit> units =
+ FluentIterable<TimeUnit> unused =
FluentIterable.from(TimeUnit.values()).append(TimeUnit.SECONDS);
}
@@ -105,7 +105,6 @@ public class FluentIterableTest extends TestCase {
List<Integer> list1 = newArrayList(1);
List<Integer> list2 = newArrayList(4);
- @SuppressWarnings("unchecked")
List<List<Integer>> input = newArrayList(list1, list2);
FluentIterable<Integer> result = FluentIterable.concat(input);
@@ -127,7 +126,6 @@ public class FluentIterableTest extends TestCase {
List<Integer> list3 = newArrayList(7, 8);
List<Integer> list4 = newArrayList(9);
List<Integer> list5 = newArrayList(10);
- @SuppressWarnings("unchecked")
FluentIterable<Integer> result = FluentIterable.concat(list1, list2, list3, list4, list5);
assertEquals(asList(1, 4, 7, 8, 9, 10), newArrayList(result));
assertEquals("[1, 4, 7, 8, 9, 10]", result.toString());
diff --git a/guava-tests/test/com/google/common/collect/ForwardingListTest.java b/guava-tests/test/com/google/common/collect/ForwardingListTest.java
index 7d3466eed..881228260 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingListTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingListTest.java
@@ -31,6 +31,7 @@ import java.util.ListIterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingList}.
@@ -112,7 +113,7 @@ public class ForwardingListTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingMapTest.java b/guava-tests/test/com/google/common/collect/ForwardingMapTest.java
index cf2ed0d3b..6654f5496 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingMapTest.java
@@ -47,6 +47,7 @@ import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ForwardingMap}.
@@ -83,12 +84,12 @@ public class ForwardingMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
return standardRemove(object);
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -335,7 +336,7 @@ public class ForwardingMapTest extends TestCase {
"java.util.function.Consumer", "accept",
"java.util.function.IntFunction", "apply");
- private static Object getDefaultValue(final TypeToken<?> type) {
+ private static @Nullable Object getDefaultValue(final TypeToken<?> type) {
Class<?> rawType = type.getRawType();
Object defaultValue = ArbitraryInstances.get(rawType);
if (defaultValue != null) {
diff --git a/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java b/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java
index 327885d53..c2d783005 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingMultisetTest.java
@@ -33,6 +33,7 @@ import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ForwardingMultiset}.
@@ -115,7 +116,7 @@ public class ForwardingMultisetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -277,7 +278,7 @@ public class ForwardingMultisetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
throw new UnsupportedOperationException();
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java b/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java
index b70cd0718..41e29ec88 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java
@@ -39,6 +39,7 @@ import java.util.SortedMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingNavigableMap}.
@@ -75,12 +76,12 @@ public class ForwardingNavigableMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
return standardRemove(object);
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -134,47 +135,47 @@ public class ForwardingNavigableMapTest extends TestCase {
}
@Override
- public Entry<K, V> lowerEntry(K key) {
+ public @Nullable Entry<K, V> lowerEntry(K key) {
return standardLowerEntry(key);
}
@Override
- public K lowerKey(K key) {
+ public @Nullable K lowerKey(K key) {
return standardLowerKey(key);
}
@Override
- public Entry<K, V> floorEntry(K key) {
+ public @Nullable Entry<K, V> floorEntry(K key) {
return standardFloorEntry(key);
}
@Override
- public K floorKey(K key) {
+ public @Nullable K floorKey(K key) {
return standardFloorKey(key);
}
@Override
- public Entry<K, V> ceilingEntry(K key) {
+ public @Nullable Entry<K, V> ceilingEntry(K key) {
return standardCeilingEntry(key);
}
@Override
- public K ceilingKey(K key) {
+ public @Nullable K ceilingKey(K key) {
return standardCeilingKey(key);
}
@Override
- public Entry<K, V> higherEntry(K key) {
+ public @Nullable Entry<K, V> higherEntry(K key) {
return standardHigherEntry(key);
}
@Override
- public K higherKey(K key) {
+ public @Nullable K higherKey(K key) {
return standardHigherKey(key);
}
@Override
- public Entry<K, V> firstEntry() {
+ public @Nullable Entry<K, V> firstEntry() {
return standardFirstEntry();
}
@@ -184,12 +185,12 @@ public class ForwardingNavigableMapTest extends TestCase {
*/
@Override
- public Entry<K, V> pollFirstEntry() {
+ public @Nullable Entry<K, V> pollFirstEntry() {
return standardPollFirstEntry();
}
@Override
- public Entry<K, V> pollLastEntry() {
+ public @Nullable Entry<K, V> pollLastEntry() {
return standardPollLastEntry();
}
@@ -242,7 +243,7 @@ public class ForwardingNavigableMapTest extends TestCase {
}
@Override
- public Entry<K, V> lastEntry() {
+ public @Nullable Entry<K, V> lastEntry() {
return standardLastEntry();
}
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java b/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java
index fd47bf8fd..2fbc42ae7 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java
@@ -34,6 +34,7 @@ import java.util.SortedSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingNavigableSet}.
@@ -54,7 +55,7 @@ public class ForwardingNavigableSetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
@@ -119,32 +120,32 @@ public class ForwardingNavigableSetTest extends TestCase {
}
@Override
- public T lower(T e) {
+ public @Nullable T lower(T e) {
return standardLower(e);
}
@Override
- public T floor(T e) {
+ public @Nullable T floor(T e) {
return standardFloor(e);
}
@Override
- public T ceiling(T e) {
+ public @Nullable T ceiling(T e) {
return standardCeiling(e);
}
@Override
- public T higher(T e) {
+ public @Nullable T higher(T e) {
return standardHigher(e);
}
@Override
- public T pollFirst() {
+ public @Nullable T pollFirst() {
return standardPollFirst();
}
@Override
- public T pollLast() {
+ public @Nullable T pollLast() {
return standardPollLast();
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java b/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java
index 248f13277..033a96d9e 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java
@@ -29,6 +29,7 @@ import java.util.Queue;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingQueue}.
@@ -106,12 +107,12 @@ public class ForwardingQueueTest extends TestCase {
}
@Override
- public T peek() {
+ public @Nullable T peek() {
return standardPeek();
}
@Override
- public T poll() {
+ public @Nullable T poll() {
return standardPoll();
}
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingSetTest.java b/guava-tests/test/com/google/common/collect/ForwardingSetTest.java
index 89bf7b31d..53d12c36a 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingSetTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingSetTest.java
@@ -31,6 +31,7 @@ import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingSet}.
@@ -52,7 +53,7 @@ public class ForwardingSetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java b/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java
index 59e7ece53..a4d829085 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java
@@ -36,6 +36,7 @@ import java.util.SortedMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingSortedMap}.
@@ -71,12 +72,12 @@ public class ForwardingSortedMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
return standardRemove(object);
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java b/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java
index b83ee6b97..417370488 100644
--- a/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java
+++ b/guava-tests/test/com/google/common/collect/ForwardingSortedSetTest.java
@@ -31,6 +31,7 @@ import java.util.SortedSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code ForwardingSortedSet}.
@@ -51,7 +52,7 @@ public class ForwardingSortedSetTest extends TestCase {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
return standardEquals(object);
}
diff --git a/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java b/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java
new file mode 100644
index 000000000..5b12653b5
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/HashBasedTableColumnMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+
+@GwtCompatible
+public class HashBasedTableColumnMapTest extends ColumnMapTests {
+ public HashBasedTableColumnMapTest() {
+ super(false, true, true, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java b/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java
new file mode 100644
index 000000000..3a68bc642
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/HashBasedTableColumnTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+
+@GwtCompatible
+public class HashBasedTableColumnTest extends ColumnTests {
+ public HashBasedTableColumnTest() {
+ super(false, true, true, true, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java b/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java
new file mode 100644
index 000000000..e5203b134
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/HashBasedTableRowMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+
+@GwtCompatible
+public class HashBasedTableRowMapTest extends RowMapTests {
+ public HashBasedTableRowMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java b/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java
new file mode 100644
index 000000000..eb4afeb78
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/HashBasedTableRowTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+
+@GwtCompatible
+public class HashBasedTableRowTest extends RowTests {
+ public HashBasedTableRowTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ return HashBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableBiMapFloodingTest.java b/guava-tests/test/com/google/common/collect/ImmutableBiMapFloodingTest.java
new file mode 100644
index 000000000..722e3189a
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableBiMapFloodingTest.java
@@ -0,0 +1,114 @@
+/*
+ * 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 com.google.errorprone.annotations.CanIgnoreReturnValue;
+import java.util.EnumSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Stream;
+
+@GwtCompatible
+public class ImmutableBiMapFloodingTest extends AbstractHashFloodingTest<BiMap<Object, Object>> {
+ public ImmutableBiMapFloodingTest() {
+ super(
+ EnumSet.allOf(ConstructionPathway.class).stream()
+ .flatMap(
+ path ->
+ Stream.<Construction<BiMap<Object, Object>>>of(
+ keys ->
+ path.create(
+ Lists.transform(
+ keys, key -> Maps.immutableEntry(key, new Object()))),
+ keys ->
+ path.create(
+ Lists.transform(
+ keys, key -> Maps.immutableEntry(new Object(), key))),
+ keys ->
+ path.create(
+ Lists.transform(keys, key -> Maps.immutableEntry(key, key)))))
+ .collect(ImmutableList.toImmutableList()),
+ n -> n * Math.log(n),
+ ImmutableList.of(
+ QueryOp.create("BiMap.get", BiMap::get, Math::log),
+ QueryOp.create("BiMap.inverse.get", (bm, o) -> bm.inverse().get(o), Math::log)));
+ }
+
+ /** All the ways to create an ImmutableBiMap. */
+ enum ConstructionPathway {
+ COPY_OF_MAP {
+ @Override
+ public ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries) {
+ Map<Object, Object> sourceMap = new LinkedHashMap<>();
+ for (Entry<?, ?> entry : entries) {
+ if (sourceMap.put(entry.getKey(), entry.getValue()) != null) {
+ throw new UnsupportedOperationException("duplicate key");
+ }
+ }
+ return ImmutableBiMap.copyOf(sourceMap);
+ }
+ },
+ COPY_OF_ENTRIES {
+ @Override
+ public ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries) {
+ return ImmutableBiMap.copyOf(entries);
+ }
+ },
+ BUILDER_PUT_ONE_BY_ONE {
+ @Override
+ public ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries) {
+ ImmutableBiMap.Builder<Object, Object> builder = ImmutableBiMap.builder();
+ for (Entry<?, ?> entry : entries) {
+ builder.put(entry.getKey(), entry.getValue());
+ }
+ return builder.buildOrThrow();
+ }
+ },
+ BUILDER_PUT_ALL_MAP {
+ @Override
+ public ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries) {
+ Map<Object, Object> sourceMap = new LinkedHashMap<>();
+ for (Entry<?, ?> entry : entries) {
+ if (sourceMap.put(entry.getKey(), entry.getValue()) != null) {
+ throw new UnsupportedOperationException("duplicate key");
+ }
+ }
+ ImmutableBiMap.Builder<Object, Object> builder = ImmutableBiMap.builder();
+ builder.putAll(sourceMap);
+ return builder.buildOrThrow();
+ }
+ },
+ BUILDER_PUT_ALL_ENTRIES {
+ @Override
+ public ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries) {
+ return ImmutableBiMap.builder().putAll(entries).buildOrThrow();
+ }
+ },
+ FORCE_JDK {
+ @Override
+ public ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries) {
+ return ImmutableBiMap.builder().putAll(entries).buildJdkBacked();
+ }
+ };
+
+ @CanIgnoreReturnValue
+ public abstract ImmutableBiMap<Object, Object> create(List<Entry<?, ?>> entries);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java
new file mode 100644
index 000000000..1484171ed
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableBiMapInverseMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class ImmutableBiMapInverseMapInterfaceTest
+ extends AbstractImmutableBiMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ return ImmutableBiMap.of();
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse();
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java
new file mode 100644
index 000000000..6a7846e3d
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableBiMapMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class ImmutableBiMapMapInterfaceTest
+ extends AbstractImmutableBiMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ return ImmutableBiMap.of();
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableBiMap.of("one", 1, "two", 2, "three", 3);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
index 780dc37c0..24eddecd4 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
@@ -22,9 +22,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
-import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableBiMap.Builder;
-import com.google.common.collect.testing.MapInterfaceTest;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -36,13 +34,10 @@ import com.google.common.collect.testing.google.BiMapTestSuiteBuilder;
import com.google.common.collect.testing.google.TestStringBiMapGenerator;
import com.google.common.testing.CollectorTester;
import com.google.common.testing.SerializableTester;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collections;
-import java.util.EnumSet;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@@ -66,12 +61,6 @@ public class ImmutableBiMapTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite();
- suite.addTestSuite(MapTests.class);
- suite.addTestSuite(InverseMapTests.class);
- suite.addTestSuite(CreationTests.class);
- suite.addTestSuite(BiMapSpecificTests.class);
- suite.addTestSuite(FloodingTest.class);
-
suite.addTest(
BiMapTestSuiteBuilder.using(new ImmutableBiMapGenerator())
.named("ImmutableBiMap")
@@ -128,659 +117,581 @@ public class ImmutableBiMapTest extends TestCase {
return suite;
}
- public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> {
- public AbstractMapTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- protected Map<K, V> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- private static final Joiner joiner = Joiner.on(", ");
-
- @Override
- protected void assertMoreInvariants(Map<K, V> map) {
+ // Creation tests
- BiMap<K, V> bimap = (BiMap<K, V>) map;
-
- for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
- assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue()));
- }
-
- assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
- assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
- assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
- assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());
-
- assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
- assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
- }
+ public void testEmptyBuilder() {
+ ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
+ assertEquals(Collections.<Integer, String>emptyMap(), map.inverse());
+ assertSame(ImmutableBiMap.of(), map);
}
- public static class MapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- return ImmutableBiMap.of();
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableBiMap.of("one", 1, "two", 2, "three", 3);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testSingletonBuilder() {
+ ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).build();
+ assertMapEquals(map, "one", 1);
+ assertMapEquals(map.inverse(), 1, "one");
}
- public static class InverseMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- return ImmutableBiMap.of();
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse();
- }
+ public void testBuilder_withImmutableEntry() {
+ ImmutableBiMap<String, Integer> map =
+ new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).build();
+ assertMapEquals(map, "one", 1);
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
+ public void testBuilder() {
+ ImmutableBiMap<String, Integer> map =
+ ImmutableBiMap.<String, Integer>builder()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ @GwtIncompatible
+ public void testBuilderExactlySizedReusesArray() {
+ ImmutableBiMap.Builder<Integer, Integer> builder = ImmutableBiMap.builderWithExpectedSize(10);
+ Entry<Integer, Integer>[] builderArray = builder.entries;
+ for (int i = 0; i < 10; i++) {
+ builder.put(i, i);
+ }
+ Entry<Integer, Integer>[] builderArrayAfterPuts = builder.entries;
+ RegularImmutableBiMap<Integer, Integer> map =
+ (RegularImmutableBiMap<Integer, Integer>) builder.build();
+ Entry<Integer, Integer>[] mapInternalArray = map.entries;
+ assertSame(builderArray, builderArrayAfterPuts);
+ assertSame(builderArray, mapInternalArray);
}
- public static class CreationTests extends TestCase {
- public void testEmptyBuilder() {
- ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
- assertEquals(Collections.<Integer, String>emptyMap(), map.inverse());
- assertSame(ImmutableBiMap.of(), map);
- }
+ public void testBuilder_orderEntriesByValue() {
+ ImmutableBiMap<String, Integer> map =
+ ImmutableBiMap.<String, Integer>builder()
+ .orderEntriesByValue(Ordering.natural())
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 4)
+ .put("two", 2)
+ .build();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- public void testSingletonBuilder() {
- ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).build();
- assertMapEquals(map, "one", 1);
- assertMapEquals(map.inverse(), 1, "one");
- }
+ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
+ ImmutableBiMap.Builder<String, Integer> builder =
+ new ImmutableBiMap.Builder<String, Integer>(2).put("four", 4).put("one", 1);
+ ImmutableMap<String, Integer> keyOrdered = builder.build();
+ ImmutableMap<String, Integer> valueOrdered =
+ builder.orderEntriesByValue(Ordering.natural()).build();
+ assertMapEquals(keyOrdered, "four", 4, "one", 1);
+ assertMapEquals(valueOrdered, "one", 1, "four", 4);
+ }
- public void testBuilder_withImmutableEntry() {
- ImmutableBiMap<String, Integer> map =
- new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).build();
- assertMapEquals(map, "one", 1);
+ public void testBuilder_orderEntriesByValue_usedTwiceFails() {
+ ImmutableBiMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
+ try {
+ builder.orderEntriesByValue(Ordering.natural());
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException expected) {
}
+ }
- public void testBuilder() {
- ImmutableBiMap<String, Integer> map =
- ImmutableBiMap.<String, Integer>builder()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
- }
+ public void testBuilderPutAllWithEmptyMap() {
+ ImmutableBiMap<String, Integer> map =
+ new Builder<String, Integer>().putAll(Collections.<String, Integer>emptyMap()).build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
+ }
- @GwtIncompatible
- public void testBuilderExactlySizedReusesArray() {
- ImmutableBiMap.Builder<Integer, Integer> builder = ImmutableBiMap.builderWithExpectedSize(10);
- Entry<Integer, Integer>[] builderArray = builder.entries;
- for (int i = 0; i < 10; i++) {
- builder.put(i, i);
- }
- Entry<Integer, Integer>[] builderArrayAfterPuts = builder.entries;
- RegularImmutableBiMap<Integer, Integer> map =
- (RegularImmutableBiMap<Integer, Integer>) builder.build();
- Entry<Integer, Integer>[] mapInternalArray = map.entries;
- assertSame(builderArray, builderArrayAfterPuts);
- assertSame(builderArray, mapInternalArray);
- }
+ public void testBuilderPutAll() {
+ Map<String, Integer> toPut = new LinkedHashMap<>();
+ toPut.put("one", 1);
+ toPut.put("two", 2);
+ toPut.put("three", 3);
+ Map<String, Integer> moreToPut = new LinkedHashMap<>();
+ moreToPut.put("four", 4);
+ moreToPut.put("five", 5);
+
+ ImmutableBiMap<String, Integer> map =
+ new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).build();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- public void testBuilder_orderEntriesByValue() {
- ImmutableBiMap<String, Integer> map =
- ImmutableBiMap.<String, Integer>builder()
- .orderEntriesByValue(Ordering.natural())
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 4)
- .put("two", 2)
- .build();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
- }
+ public void testBuilderReuse() {
+ Builder<String, Integer> builder = new Builder<>();
+ ImmutableBiMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
+ ImmutableBiMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
- public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
- ImmutableBiMap.Builder<String, Integer> builder =
- new ImmutableBiMap.Builder<String, Integer>(2).put("four", 4).put("one", 1);
- ImmutableMap<String, Integer> keyOrdered = builder.build();
- ImmutableMap<String, Integer> valueOrdered =
- builder.orderEntriesByValue(Ordering.natural()).build();
- assertMapEquals(keyOrdered, "four", 4, "one", 1);
- assertMapEquals(valueOrdered, "one", 1, "four", 4);
- }
+ assertMapEquals(mapOne, "one", 1, "two", 2);
+ assertMapEquals(mapOne.inverse(), 1, "one", 2, "two");
+ assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
+ assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four");
+ }
- public void testBuilder_orderEntriesByValue_usedTwiceFails() {
- ImmutableBiMap.Builder<String, Integer> builder =
- new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
- try {
- builder.orderEntriesByValue(Ordering.natural());
- fail("Expected IllegalStateException");
- } catch (IllegalStateException expected) {
- }
+ public void testBuilderPutNullKey() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAllWithEmptyMap() {
- ImmutableBiMap<String, Integer> map =
- new Builder<String, Integer>().putAll(Collections.<String, Integer>emptyMap()).build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
+ public void testBuilderPutNullValue() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAll() {
- Map<String, Integer> toPut = new LinkedHashMap<>();
- toPut.put("one", 1);
- toPut.put("two", 2);
- toPut.put("three", 3);
- Map<String, Integer> moreToPut = new LinkedHashMap<>();
- moreToPut.put("four", 4);
- moreToPut.put("five", 5);
-
- ImmutableBiMap<String, Integer> map =
- new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).build();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ public void testBuilderPutNullKeyViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderReuse() {
- Builder<String, Integer> builder = new Builder<>();
- ImmutableBiMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
- ImmutableBiMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
-
- assertMapEquals(mapOne, "one", 1, "two", 2);
- assertMapEquals(mapOne.inverse(), 1, "one", 2, "two");
- assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
- assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four");
+ public void testBuilderPutNullValueViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap("one", null));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutNullKey() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ @SuppressWarnings("AlwaysThrows")
+ public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
+ Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .put("one", 1)
+ .put("one", 1); // throwing on this line would be even better
- public void testBuilderPutNullValue() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ builder.build();
+ fail();
+ } catch (IllegalArgumentException expected) {
+ assertThat(expected.getMessage()).contains("one");
}
+ }
- public void testBuilderPutNullKeyViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testOf() {
+ assertMapEquals(ImmutableBiMap.of("one", 1), "one", 1);
+ assertMapEquals(ImmutableBiMap.of("one", 1).inverse(), 1, "one");
+ assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2);
+ assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two");
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(),
+ 1,
+ "one",
+ 2,
+ "two",
+ 3,
+ "three");
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4);
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4).inverse(),
+ 1,
+ "one",
+ 2,
+ "two",
+ 3,
+ "three",
+ 4,
+ "four");
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5);
+ assertMapEquals(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(),
+ 1,
+ "one",
+ 2,
+ "two",
+ 3,
+ "three",
+ 4,
+ "four",
+ 5,
+ "five");
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9);
+ assertMapEquals(
+ ImmutableBiMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9,
+ "ten", 10),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9,
+ "ten",
+ 10);
+ }
- public void testBuilderPutNullValueViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap("one", null));
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullKey() {
+ try {
+ ImmutableBiMap.of(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
- @SuppressWarnings("AlwaysThrows")
- public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
- Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .put("one", 1)
- .put("one", 1); // throwing on this line would be even better
-
- try {
- builder.build();
- fail();
- } catch (IllegalArgumentException expected) {
- assertThat(expected.getMessage()).contains("one");
- }
+ try {
+ ImmutableBiMap.of("one", 1, null, 2);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOf() {
- assertMapEquals(ImmutableBiMap.of("one", 1), "one", 1);
- assertMapEquals(ImmutableBiMap.of("one", 1).inverse(), 1, "one");
- assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2);
- assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two");
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(),
- 1,
- "one",
- 2,
- "two",
- 3,
- "three");
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4);
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4).inverse(),
- 1,
- "one",
- 2,
- "two",
- 3,
- "three",
- 4,
- "four");
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5);
- assertMapEquals(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(),
- 1,
- "one",
- 2,
- "two",
- 3,
- "three",
- 4,
- "four",
- 5,
- "five");
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9);
- assertMapEquals(
- ImmutableBiMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9,
- "ten", 10),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9,
- "ten",
- 10);
+ public void testOfNullValue() {
+ try {
+ ImmutableBiMap.of("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testOfNullKey() {
- try {
- ImmutableBiMap.of(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableBiMap.of("one", 1, null, 2);
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ ImmutableBiMap.of("one", 1, "two", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOfNullValue() {
- try {
- ImmutableBiMap.of("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableBiMap.of("one", 1, "two", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ @SuppressWarnings("AlwaysThrows")
+ public void testOfWithDuplicateKey() {
+ try {
+ ImmutableBiMap.of("one", 1, "one", 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ assertThat(expected.getMessage()).contains("one");
}
+ }
- @SuppressWarnings("AlwaysThrows")
- public void testOfWithDuplicateKey() {
- try {
- ImmutableBiMap.of("one", 1, "one", 1);
- fail();
- } catch (IllegalArgumentException expected) {
- assertThat(expected.getMessage()).contains("one");
- }
- }
+ public void testOfEntries() {
+ assertMapEquals(ImmutableBiMap.ofEntries(entry("one", 1), entry("two", 2)), "one", 1, "two", 2);
+ }
- public void testOfEntries() {
- assertMapEquals(
- ImmutableBiMap.ofEntries(entry("one", 1), entry("two", 2)), "one", 1, "two", 2);
+ public void testOfEntriesNull() {
+ Entry<Integer, Integer> nullKey = entry(null, 23);
+ try {
+ ImmutableBiMap.ofEntries(nullKey);
+ fail();
+ } catch (NullPointerException expected) {
}
-
- public void testOfEntriesNull() {
- Entry<Integer, Integer> nullKey = entry(null, 23);
- try {
- ImmutableBiMap.ofEntries(nullKey);
- fail();
- } catch (NullPointerException expected) {
- }
- Entry<Integer, Integer> nullValue = entry(23, null);
- try {
- ImmutableBiMap.ofEntries(nullValue);
- fail();
- } catch (NullPointerException expected) {
- }
+ Entry<Integer, Integer> nullValue = entry(23, null);
+ try {
+ ImmutableBiMap.ofEntries(nullValue);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- private static <T> Entry<T, T> entry(T key, T value) {
- return new AbstractMap.SimpleImmutableEntry<>(key, value);
- }
+ private static <T> Entry<T, T> entry(T key, T value) {
+ return new AbstractMap.SimpleImmutableEntry<>(key, value);
+ }
- public void testCopyOfEmptyMap() {
- ImmutableBiMap<String, Integer> copy =
- ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
- assertEquals(Collections.<String, Integer>emptyMap(), copy);
- assertSame(copy, ImmutableBiMap.copyOf(copy));
- assertSame(ImmutableBiMap.of(), copy);
- }
+ public void testCopyOfEmptyMap() {
+ ImmutableBiMap<String, Integer> copy =
+ ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
+ assertEquals(Collections.<String, Integer>emptyMap(), copy);
+ assertSame(copy, ImmutableBiMap.copyOf(copy));
+ assertSame(ImmutableBiMap.of(), copy);
+ }
- public void testCopyOfSingletonMap() {
- ImmutableBiMap<String, Integer> copy =
- ImmutableBiMap.copyOf(Collections.singletonMap("one", 1));
- assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableBiMap.copyOf(copy));
- }
+ public void testCopyOfSingletonMap() {
+ ImmutableBiMap<String, Integer> copy =
+ ImmutableBiMap.copyOf(Collections.singletonMap("one", 1));
+ assertMapEquals(copy, "one", 1);
+ assertSame(copy, ImmutableBiMap.copyOf(copy));
+ }
- public void testCopyOf() {
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
+ public void testCopyOf() {
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
- assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
- assertSame(copy, ImmutableBiMap.copyOf(copy));
- }
+ ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
+ assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
+ assertSame(copy, ImmutableBiMap.copyOf(copy));
+ }
- public void testEmpty() {
- ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
- assertEquals(Collections.<String, Integer>emptyMap(), bimap);
- assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse());
- }
+ public void testEmpty() {
+ ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
+ assertEquals(Collections.<String, Integer>emptyMap(), bimap);
+ assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse());
+ }
- public void testFromHashMap() {
- Map<String, Integer> hashMap = Maps.newLinkedHashMap();
- hashMap.put("one", 1);
- hashMap.put("two", 2);
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- assertMapEquals(bimap, "one", 1, "two", 2);
- assertMapEquals(bimap.inverse(), 1, "one", 2, "two");
- }
+ public void testFromHashMap() {
+ Map<String, Integer> hashMap = Maps.newLinkedHashMap();
+ hashMap.put("one", 1);
+ hashMap.put("two", 2);
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ assertMapEquals(bimap, "one", 1, "two", 2);
+ assertMapEquals(bimap.inverse(), 1, "one", 2, "two");
+ }
- public void testFromImmutableMap() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(
- new ImmutableMap.Builder<String, Integer>()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .buildOrThrow());
- assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
- }
+ public void testFromImmutableMap() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(
+ new ImmutableMap.Builder<String, Integer>()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .buildOrThrow());
+ assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
+ }
- public void testDuplicateValues() {
- ImmutableMap<String, Integer> map =
- new ImmutableMap.Builder<String, Integer>()
- .put("one", 1)
- .put("two", 2)
- .put("uno", 1)
- .put("dos", 2)
- .buildOrThrow();
-
- try {
- ImmutableBiMap.copyOf(map);
- fail();
- } catch (IllegalArgumentException expected) {
- assertThat(expected.getMessage()).containsMatch("1|2");
- // We don't specify which of the two dups should be reported.
- }
+ public void testDuplicateValues() {
+ ImmutableMap<String, Integer> map =
+ new ImmutableMap.Builder<String, Integer>()
+ .put("one", 1)
+ .put("two", 2)
+ .put("uno", 1)
+ .put("dos", 2)
+ .buildOrThrow();
+
+ try {
+ ImmutableBiMap.copyOf(map);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ assertThat(expected.getMessage()).containsMatch("1|2");
+ // We don't specify which of the two dups should be reported.
}
+ }
- public void testToImmutableBiMap() {
- Collector<Entry<String, Integer>, ?, ImmutableBiMap<String, Integer>> collector =
- ImmutableBiMap.toImmutableBiMap(Entry::getKey, Entry::getValue);
- Equivalence<ImmutableBiMap<String, Integer>> equivalence =
- Equivalence.equals()
- .<Entry<String, Integer>>pairwise()
- .onResultOf(ImmutableBiMap::entrySet);
- CollectorTester.of(collector, equivalence)
- .expectCollects(
- ImmutableBiMap.of("one", 1, "two", 2, "three", 3),
- mapEntry("one", 1),
- mapEntry("two", 2),
- mapEntry("three", 3));
- }
+ public void testToImmutableBiMap() {
+ Collector<Entry<String, Integer>, ?, ImmutableBiMap<String, Integer>> collector =
+ ImmutableBiMap.toImmutableBiMap(Entry::getKey, Entry::getValue);
+ Equivalence<ImmutableBiMap<String, Integer>> equivalence =
+ Equivalence.equals()
+ .<Entry<String, Integer>>pairwise()
+ .onResultOf(ImmutableBiMap::entrySet);
+ CollectorTester.of(collector, equivalence)
+ .expectCollects(
+ ImmutableBiMap.of("one", 1, "two", 2, "three", 3),
+ mapEntry("one", 1),
+ mapEntry("two", 2),
+ mapEntry("three", 3));
+ }
- public void testToImmutableBiMap_exceptionOnDuplicateKey() {
- Collector<Entry<String, Integer>, ?, ImmutableBiMap<String, Integer>> collector =
- ImmutableBiMap.toImmutableBiMap(Entry::getKey, Entry::getValue);
- try {
- Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
+ public void testToImmutableBiMap_exceptionOnDuplicateKey() {
+ Collector<Entry<String, Integer>, ?, ImmutableBiMap<String, Integer>> collector =
+ ImmutableBiMap.toImmutableBiMap(Entry::getKey, Entry::getValue);
+ try {
+ Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
}
}
- public static class BiMapSpecificTests extends TestCase {
+ // BiMap-specific tests
- @SuppressWarnings("DoNotCall")
- public void testForcePut() {
- BiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- try {
- bimap.forcePut("three", 3);
- fail();
- } catch (UnsupportedOperationException expected) {
- }
+ @SuppressWarnings("DoNotCall")
+ public void testForcePut() {
+ BiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ try {
+ bimap.forcePut("three", 3);
+ fail();
+ } catch (UnsupportedOperationException expected) {
}
+ }
- public void testKeySet() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
- Set<String> keys = bimap.keySet();
- assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys);
- assertThat(keys).containsExactly("one", "two", "three", "four").inOrder();
- }
+ public void testKeySet() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
+ Set<String> keys = bimap.keySet();
+ assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys);
+ assertThat(keys).containsExactly("one", "two", "three", "four").inOrder();
+ }
- public void testValues() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
- Set<Integer> values = bimap.values();
- assertEquals(Sets.newHashSet(1, 2, 3, 4), values);
- assertThat(values).containsExactly(1, 2, 3, 4).inOrder();
- }
+ public void testValues() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
+ Set<Integer> values = bimap.values();
+ assertEquals(Sets.newHashSet(1, 2, 3, 4), values);
+ assertThat(values).containsExactly(1, 2, 3, 4).inOrder();
+ }
- public void testDoubleInverse() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- assertSame(bimap, bimap.inverse().inverse());
- }
+ public void testDoubleInverse() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ assertSame(bimap, bimap.inverse().inverse());
+ }
- @GwtIncompatible // SerializableTester
- public void testEmptySerialization() {
- ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
- assertSame(bimap, SerializableTester.reserializeAndAssert(bimap));
- }
+ @GwtIncompatible // SerializableTester
+ public void testEmptySerialization() {
+ ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
+ assertSame(bimap, SerializableTester.reserializeAndAssert(bimap));
+ }
- @GwtIncompatible // SerializableTester
- public void testSerialization() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
- ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
- assertEquals(Integer.valueOf(1), copy.get("one"));
- assertEquals("one", copy.inverse().get(1));
- assertSame(copy, copy.inverse().inverse());
- }
+ @GwtIncompatible // SerializableTester
+ public void testSerialization() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
+ ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
+ assertEquals(Integer.valueOf(1), copy.get("one"));
+ assertEquals("one", copy.inverse().get(1));
+ assertSame(copy, copy.inverse().inverse());
+ }
- @GwtIncompatible // SerializableTester
- public void testInverseSerialization() {
- ImmutableBiMap<String, Integer> bimap =
- ImmutableBiMap.copyOf(ImmutableMap.of(1, "one", 2, "two")).inverse();
- ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
- assertEquals(Integer.valueOf(1), copy.get("one"));
- assertEquals("one", copy.inverse().get(1));
- assertSame(copy, copy.inverse().inverse());
- }
+ @GwtIncompatible // SerializableTester
+ public void testInverseSerialization() {
+ ImmutableBiMap<String, Integer> bimap =
+ ImmutableBiMap.copyOf(ImmutableMap.of(1, "one", 2, "two")).inverse();
+ ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
+ assertEquals(Integer.valueOf(1), copy.get("one"));
+ assertEquals("one", copy.inverse().get(1));
+ assertSame(copy, copy.inverse().inverse());
}
private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) {
@@ -791,93 +702,6 @@ public class ImmutableBiMapTest extends TestCase {
assertThat(map).containsExactlyEntriesIn(expected).inOrder();
}
- public static class FloodingTest extends AbstractHashFloodingTest<BiMap<Object, Object>> {
- public FloodingTest() {
- super(
- EnumSet.allOf(ConstructionPathway.class).stream()
- .flatMap(
- path ->
- Stream.<Construction<BiMap<Object, Object>>>of(
- keys ->
- path.create(
- Lists.transform(
- keys, key -> Maps.immutableEntry(key, new Object()))),
- keys ->
- path.create(
- Lists.transform(
- keys, key -> Maps.immutableEntry(new Object(), key))),
- keys ->
- path.create(
- Lists.transform(keys, key -> Maps.immutableEntry(key, key)))))
- .collect(ImmutableList.toImmutableList()),
- n -> n * Math.log(n),
- ImmutableList.of(
- QueryOp.create("BiMap.get", BiMap::get, Math::log),
- QueryOp.create("BiMap.inverse.get", (bm, o) -> bm.inverse().get(o), Math::log)));
- }
-
- /** All the ways to create an ImmutableBiMap. */
- enum ConstructionPathway {
- COPY_OF_MAP {
- @Override
- public ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries) {
- Map<Object, Object> sourceMap = new LinkedHashMap<>();
- for (Map.Entry<?, ?> entry : entries) {
- if (sourceMap.put(entry.getKey(), entry.getValue()) != null) {
- throw new UnsupportedOperationException("duplicate key");
- }
- }
- return ImmutableBiMap.copyOf(sourceMap);
- }
- },
- COPY_OF_ENTRIES {
- @Override
- public ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries) {
- return ImmutableBiMap.copyOf(entries);
- }
- },
- BUILDER_PUT_ONE_BY_ONE {
- @Override
- public ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries) {
- ImmutableBiMap.Builder<Object, Object> builder = ImmutableBiMap.builder();
- for (Map.Entry<?, ?> entry : entries) {
- builder.put(entry.getKey(), entry.getValue());
- }
- return builder.build();
- }
- },
- BUILDER_PUT_ALL_MAP {
- @Override
- public ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries) {
- Map<Object, Object> sourceMap = new LinkedHashMap<>();
- for (Map.Entry<?, ?> entry : entries) {
- if (sourceMap.put(entry.getKey(), entry.getValue()) != null) {
- throw new UnsupportedOperationException("duplicate key");
- }
- }
- ImmutableBiMap.Builder<Object, Object> builder = ImmutableBiMap.builder();
- builder.putAll(sourceMap);
- return builder.build();
- }
- },
- BUILDER_PUT_ALL_ENTRIES {
- @Override
- public ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries) {
- return ImmutableBiMap.builder().putAll(entries).build();
- }
- },
- FORCE_JDK {
- @Override
- public ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries) {
- return ImmutableBiMap.builder().putAll(entries).buildJdkBacked();
- }
- };
-
- @CanIgnoreReturnValue
- public abstract ImmutableBiMap<Object, Object> create(List<Map.Entry<?, ?>> entries);
- }
- }
-
/** No-op test so that the class has at least one method, making Maven's test runner happy. */
public void testNoop() {}
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
index bce73b8f7..b9696301f 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableClassToInstanceMapTest.java
@@ -33,6 +33,7 @@ import java.util.Map.Entry;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ImmutableClassToInstanceMap}.
@@ -213,7 +214,7 @@ public class ImmutableClassToInstanceMapTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof Impl && value == ((Impl) obj).value;
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java b/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java
new file mode 100644
index 000000000..113251981
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableListCopyOfConcurrentlyModifiedInputTest.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2007 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 static com.google.common.collect.Iterables.getOnlyElement;
+import static com.google.common.collect.Iterables.unmodifiableIterable;
+import static com.google.common.collect.Sets.newHashSet;
+import static java.lang.reflect.Proxy.newProxyInstance;
+import static java.util.Arrays.asList;
+
+import com.google.common.annotations.GwtIncompatible;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import junit.framework.TestCase;
+
+@GwtIncompatible // reflection
+public class ImmutableListCopyOfConcurrentlyModifiedInputTest extends TestCase {
+ enum WrapWithIterable {
+ WRAP,
+ NO_WRAP
+ }
+
+ private static void runConcurrentlyMutatedTest(
+ Collection<Integer> initialContents,
+ Iterable<ListFrobber> actionsToPerformConcurrently,
+ WrapWithIterable wrap) {
+ ConcurrentlyMutatedList<Integer> concurrentlyMutatedList =
+ newConcurrentlyMutatedList(initialContents, actionsToPerformConcurrently);
+
+ Iterable<Integer> iterableToCopy =
+ wrap == WrapWithIterable.WRAP
+ ? unmodifiableIterable(concurrentlyMutatedList)
+ : concurrentlyMutatedList;
+
+ ImmutableList<Integer> copyOfIterable = ImmutableList.copyOf(iterableToCopy);
+
+ assertTrue(concurrentlyMutatedList.getAllStates().contains(copyOfIterable));
+ }
+
+ private static void runConcurrentlyMutatedTest(WrapWithIterable wrap) {
+ /*
+ * TODO: Iterate over many array sizes and all possible operation lists,
+ * performing adds and removes in different ways.
+ */
+ runConcurrentlyMutatedTest(elements(), ops(add(1), add(2)), wrap);
+
+ runConcurrentlyMutatedTest(elements(), ops(add(1), nop()), wrap);
+
+ runConcurrentlyMutatedTest(elements(), ops(add(1), remove()), wrap);
+
+ runConcurrentlyMutatedTest(elements(), ops(nop(), add(1)), wrap);
+
+ runConcurrentlyMutatedTest(elements(1), ops(remove(), nop()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1), ops(remove(), add(2)), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), remove()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), nop()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), add(3)), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2), ops(nop(), remove()), wrap);
+
+ runConcurrentlyMutatedTest(elements(1, 2, 3), ops(remove(), remove()), wrap);
+ }
+
+ private static ImmutableList<Integer> elements(Integer... elements) {
+ return ImmutableList.copyOf(elements);
+ }
+
+ private static ImmutableList<ListFrobber> ops(ListFrobber... elements) {
+ return ImmutableList.copyOf(elements);
+ }
+
+ public void testCopyOf_concurrentlyMutatedList() {
+ runConcurrentlyMutatedTest(WrapWithIterable.NO_WRAP);
+ }
+
+ public void testCopyOf_concurrentlyMutatedIterable() {
+ runConcurrentlyMutatedTest(WrapWithIterable.WRAP);
+ }
+
+ /** An operation to perform on a list. */
+ interface ListFrobber {
+ void perform(List<Integer> list);
+ }
+
+ static ListFrobber add(final int element) {
+ return new ListFrobber() {
+ @Override
+ public void perform(List<Integer> list) {
+ list.add(0, element);
+ }
+ };
+ }
+
+ static ListFrobber remove() {
+ return new ListFrobber() {
+ @Override
+ public void perform(List<Integer> list) {
+ list.remove(0);
+ }
+ };
+ }
+
+ static ListFrobber nop() {
+ return new ListFrobber() {
+ @Override
+ public void perform(List<Integer> list) {}
+ };
+ }
+
+ /** A list that mutates itself after every call to each of its {@link List} methods. */
+ interface ConcurrentlyMutatedList<E> extends List<E> {
+ /**
+ * The elements of a {@link ConcurrentlyMutatedList} are added and removed over time. This
+ * method returns every state that the list has passed through at some point.
+ */
+ Set<List<E>> getAllStates();
+ }
+
+ /**
+ * Returns a {@link ConcurrentlyMutatedList} that performs the given operations as its concurrent
+ * modifications. The mutations occur in the same thread as the triggering method call.
+ */
+ private static ConcurrentlyMutatedList<Integer> newConcurrentlyMutatedList(
+ final Collection<Integer> initialContents,
+ final Iterable<ListFrobber> actionsToPerformConcurrently) {
+ InvocationHandler invocationHandler =
+ new InvocationHandler() {
+ final CopyOnWriteArrayList<Integer> delegate =
+ new CopyOnWriteArrayList<>(initialContents);
+
+ final Method getAllStatesMethod =
+ getOnlyElement(asList(ConcurrentlyMutatedList.class.getDeclaredMethods()));
+
+ final Iterator<ListFrobber> remainingActions = actionsToPerformConcurrently.iterator();
+
+ final Set<List<Integer>> allStates = newHashSet();
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ return method.equals(getAllStatesMethod)
+ ? getAllStates()
+ : invokeListMethod(method, args);
+ }
+
+ private Set<List<Integer>> getAllStates() {
+ return allStates;
+ }
+
+ private Object invokeListMethod(Method method, Object[] args) throws Throwable {
+ try {
+ Object returnValue = method.invoke(delegate, args);
+ mutateDelegate();
+ return returnValue;
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ } catch (IllegalAccessException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private void mutateDelegate() {
+ allStates.add(ImmutableList.copyOf(delegate));
+ remainingActions.next().perform(delegate);
+ allStates.add(ImmutableList.copyOf(delegate));
+ }
+ };
+
+ @SuppressWarnings("unchecked")
+ ConcurrentlyMutatedList<Integer> list =
+ (ConcurrentlyMutatedList<Integer>)
+ newProxyInstance(
+ ImmutableListCopyOfConcurrentlyModifiedInputTest.class.getClassLoader(),
+ new Class[] {ConcurrentlyMutatedList.class},
+ invocationHandler);
+ return list;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableListTest.java b/guava-tests/test/com/google/common/collect/ImmutableListTest.java
index 8f8f11791..99b31d694 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableListTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableListTest.java
@@ -16,12 +16,8 @@
package com.google.common.collect;
-import static com.google.common.collect.Iterables.getOnlyElement;
-import static com.google.common.collect.Iterables.unmodifiableIterable;
-import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
-import static java.lang.reflect.Proxy.newProxyInstance;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
@@ -42,16 +38,11 @@ import com.google.common.collect.testing.testers.ListHashCodeTester;
import com.google.common.testing.CollectorTester;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
@@ -113,712 +104,542 @@ public class ImmutableListTest extends TestCase {
return suite;
}
- public static class CreationTests extends TestCase {
- public void testCreation_noArgs() {
- List<String> list = ImmutableList.of();
- assertEquals(Collections.emptyList(), list);
- }
+ // Creation tests
- public void testCreation_oneElement() {
- List<String> list = ImmutableList.of("a");
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCreation_noArgs() {
+ List<String> list = ImmutableList.of();
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCreation_twoElements() {
- List<String> list = ImmutableList.of("a", "b");
- assertEquals(Lists.newArrayList("a", "b"), list);
- }
+ public void testCreation_oneElement() {
+ List<String> list = ImmutableList.of("a");
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCreation_threeElements() {
- List<String> list = ImmutableList.of("a", "b", "c");
- assertEquals(Lists.newArrayList("a", "b", "c"), list);
- }
+ public void testCreation_twoElements() {
+ List<String> list = ImmutableList.of("a", "b");
+ assertEquals(Lists.newArrayList("a", "b"), list);
+ }
- public void testCreation_fourElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d");
- assertEquals(Lists.newArrayList("a", "b", "c", "d"), list);
- }
+ public void testCreation_threeElements() {
+ List<String> list = ImmutableList.of("a", "b", "c");
+ assertEquals(Lists.newArrayList("a", "b", "c"), list);
+ }
- public void testCreation_fiveElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e"), list);
- }
+ public void testCreation_fourElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d"), list);
+ }
- public void testCreation_sixElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), list);
- }
+ public void testCreation_fiveElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e"), list);
+ }
- public void testCreation_sevenElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g"), list);
- }
+ public void testCreation_sixElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), list);
+ }
- public void testCreation_eightElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h"), list);
- }
+ public void testCreation_sevenElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g"), list);
+ }
- public void testCreation_nineElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i"), list);
- }
+ public void testCreation_eightElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h"), list);
+ }
- public void testCreation_tenElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), list);
- }
+ public void testCreation_nineElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i"), list);
+ }
- public void testCreation_elevenElements() {
- List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
- assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), list);
- }
+ public void testCreation_tenElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), list);
+ }
- // Varargs versions
+ public void testCreation_elevenElements() {
+ List<String> list = ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), list);
+ }
- public void testCreation_twelveElements() {
- List<String> list =
- ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l");
- assertEquals(
- Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), list);
- }
+ // Varargs versions
- public void testCreation_thirteenElements() {
- List<String> list =
- ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");
- assertEquals(
- Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"),
- list);
- }
+ public void testCreation_twelveElements() {
+ List<String> list =
+ ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l");
+ assertEquals(
+ Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"), list);
+ }
- public void testCreation_fourteenElements() {
- List<String> list =
- ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n");
- assertEquals(
- Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"),
- list);
- }
+ public void testCreation_thirteenElements() {
+ List<String> list =
+ ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");
+ assertEquals(
+ Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"), list);
+ }
- public void testCreation_singletonNull() {
- try {
- ImmutableList.of((String) null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCreation_fourteenElements() {
+ List<String> list =
+ ImmutableList.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n");
+ assertEquals(
+ Lists.newArrayList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"),
+ list);
+ }
- public void testCreation_withNull() {
- try {
- ImmutableList.of("a", null, "b");
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCreation_singletonNull() {
+ try {
+ ImmutableList.of((String) null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCreation_generic() {
- List<String> a = ImmutableList.of("a");
- // only verify that there is no compile warning
- ImmutableList<List<String>> unused = ImmutableList.of(a, a);
+ public void testCreation_withNull() {
+ try {
+ ImmutableList.of("a", null, "b");
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCreation_arrayOfArray() {
- String[] array = new String[] {"a"};
- List<String[]> list = ImmutableList.<String[]>of(array);
- assertEquals(Collections.singletonList(array), list);
- }
+ public void testCreation_generic() {
+ List<String> a = ImmutableList.of("a");
+ // only verify that there is no compile warning
+ ImmutableList<List<String>> unused = ImmutableList.of(a, a);
+ }
- public void testCopyOf_emptyArray() {
- String[] array = new String[0];
- List<String> list = ImmutableList.copyOf(array);
- assertEquals(Collections.emptyList(), list);
- }
+ public void testCreation_arrayOfArray() {
+ String[] array = new String[] {"a"};
+ List<String[]> list = ImmutableList.<String[]>of(array);
+ assertEquals(Collections.singletonList(array), list);
+ }
- public void testCopyOf_arrayOfOneElement() {
- String[] array = new String[] {"a"};
- List<String> list = ImmutableList.copyOf(array);
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCopyOf_emptyArray() {
+ String[] array = new String[0];
+ List<String> list = ImmutableList.copyOf(array);
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCopyOf_nullArray() {
- try {
- ImmutableList.copyOf((String[]) null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOf_arrayOfOneElement() {
+ String[] array = new String[] {"a"};
+ List<String> list = ImmutableList.copyOf(array);
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCopyOf_arrayContainingOnlyNull() {
- String[] array = new String[] {null};
- try {
- ImmutableList.copyOf(array);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOf_nullArray() {
+ try {
+ ImmutableList.copyOf((String[]) null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_collection_empty() {
- // "<String>" is required to work around a javac 1.5 bug.
- Collection<String> c = MinimalCollection.<String>of();
- List<String> list = ImmutableList.copyOf(c);
- assertEquals(Collections.emptyList(), list);
+ public void testCopyOf_arrayContainingOnlyNull() {
+ String[] array = new String[] {null};
+ try {
+ ImmutableList.copyOf(array);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_collection_oneElement() {
- Collection<String> c = MinimalCollection.of("a");
- List<String> list = ImmutableList.copyOf(c);
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCopyOf_collection_empty() {
+ // "<String>" is required to work around a javac 1.5 bug.
+ Collection<String> c = MinimalCollection.<String>of();
+ List<String> list = ImmutableList.copyOf(c);
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCopyOf_collection_general() {
- Collection<String> c = MinimalCollection.of("a", "b", "a");
- List<String> list = ImmutableList.copyOf(c);
- assertEquals(asList("a", "b", "a"), list);
- List<String> mutableList = asList("a", "b");
- list = ImmutableList.copyOf(mutableList);
- mutableList.set(0, "c");
- assertEquals(asList("a", "b"), list);
- }
+ public void testCopyOf_collection_oneElement() {
+ Collection<String> c = MinimalCollection.of("a");
+ List<String> list = ImmutableList.copyOf(c);
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCopyOf_collectionContainingNull() {
- Collection<String> c = MinimalCollection.of("a", null, "b");
- try {
- ImmutableList.copyOf(c);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOf_collection_general() {
+ Collection<String> c = MinimalCollection.of("a", "b", "a");
+ List<String> list = ImmutableList.copyOf(c);
+ assertEquals(asList("a", "b", "a"), list);
+ List<String> mutableList = asList("a", "b");
+ list = ImmutableList.copyOf(mutableList);
+ mutableList.set(0, "c");
+ assertEquals(asList("a", "b"), list);
+ }
- public void testCopyOf_iterator_empty() {
- Iterator<String> iterator = Iterators.emptyIterator();
- List<String> list = ImmutableList.copyOf(iterator);
- assertEquals(Collections.emptyList(), list);
+ public void testCopyOf_collectionContainingNull() {
+ Collection<String> c = MinimalCollection.of("a", null, "b");
+ try {
+ ImmutableList.copyOf(c);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_iterator_oneElement() {
- Iterator<String> iterator = Iterators.singletonIterator("a");
- List<String> list = ImmutableList.copyOf(iterator);
- assertEquals(Collections.singletonList("a"), list);
- }
+ public void testCopyOf_iterator_empty() {
+ Iterator<String> iterator = Iterators.emptyIterator();
+ List<String> list = ImmutableList.copyOf(iterator);
+ assertEquals(Collections.emptyList(), list);
+ }
- public void testCopyOf_iterator_general() {
- Iterator<String> iterator = asList("a", "b", "a").iterator();
- List<String> list = ImmutableList.copyOf(iterator);
- assertEquals(asList("a", "b", "a"), list);
- }
+ public void testCopyOf_iterator_oneElement() {
+ Iterator<String> iterator = Iterators.singletonIterator("a");
+ List<String> list = ImmutableList.copyOf(iterator);
+ assertEquals(Collections.singletonList("a"), list);
+ }
- public void testCopyOf_iteratorContainingNull() {
- Iterator<String> iterator = asList("a", null, "b").iterator();
- try {
- ImmutableList.copyOf(iterator);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOf_iterator_general() {
+ Iterator<String> iterator = asList("a", "b", "a").iterator();
+ List<String> list = ImmutableList.copyOf(iterator);
+ assertEquals(asList("a", "b", "a"), list);
+ }
- public void testCopyOf_iteratorNull() {
- try {
- ImmutableList.copyOf((Iterator<String>) null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOf_iteratorContainingNull() {
+ Iterator<String> iterator = asList("a", null, "b").iterator();
+ try {
+ ImmutableList.copyOf(iterator);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testCopyOf_concurrentlyMutating() {
- List<String> sample = Lists.newArrayList("a", "b", "c");
- for (int delta : new int[] {-1, 0, 1}) {
- for (int i = 0; i < sample.size(); i++) {
- Collection<String> misleading = Helpers.misleadingSizeCollection(delta);
- List<String> expected = sample.subList(0, i);
- misleading.addAll(expected);
- assertEquals(expected, ImmutableList.copyOf(misleading));
- assertEquals(expected, ImmutableList.copyOf((Iterable<String>) misleading));
- }
- }
+ public void testCopyOf_iteratorNull() {
+ try {
+ ImmutableList.copyOf((Iterator<String>) null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- private static class CountingIterable implements Iterable<String> {
- int count = 0;
-
- @Override
- public Iterator<String> iterator() {
- count++;
- return asList("a", "b", "a").iterator();
+ public void testCopyOf_concurrentlyMutating() {
+ List<String> sample = Lists.newArrayList("a", "b", "c");
+ for (int delta : new int[] {-1, 0, 1}) {
+ for (int i = 0; i < sample.size(); i++) {
+ Collection<String> misleading = Helpers.misleadingSizeCollection(delta);
+ List<String> expected = sample.subList(0, i);
+ misleading.addAll(expected);
+ assertEquals(expected, ImmutableList.copyOf(misleading));
+ assertEquals(expected, ImmutableList.copyOf((Iterable<String>) misleading));
}
}
+ }
- public void testCopyOf_plainIterable() {
- CountingIterable iterable = new CountingIterable();
- List<String> list = ImmutableList.copyOf(iterable);
- assertEquals(asList("a", "b", "a"), list);
- }
-
- public void testCopyOf_plainIterable_iteratesOnce() {
- CountingIterable iterable = new CountingIterable();
- ImmutableList<String> unused = ImmutableList.copyOf(iterable);
- assertEquals(1, iterable.count);
- }
-
- public void testCopyOf_shortcut_empty() {
- Collection<String> c = ImmutableList.of();
- assertSame(c, ImmutableList.copyOf(c));
- }
-
- public void testCopyOf_shortcut_singleton() {
- Collection<String> c = ImmutableList.of("a");
- assertSame(c, ImmutableList.copyOf(c));
- }
+ private static class CountingIterable implements Iterable<String> {
+ int count = 0;
- public void testCopyOf_shortcut_immutableList() {
- Collection<String> c = ImmutableList.of("a", "b", "c");
- assertSame(c, ImmutableList.copyOf(c));
+ @Override
+ public Iterator<String> iterator() {
+ count++;
+ return asList("a", "b", "a").iterator();
}
+ }
- public void testBuilderAddArrayHandlesNulls() {
- String[] elements = {"a", null, "b"};
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.add(elements);
- fail("Expected NullPointerException");
- } catch (NullPointerException expected) {
- }
- ImmutableList<String> result = builder.build();
-
- /*
- * Maybe it rejects all elements, or maybe it adds "a" before failing.
- * Either way is fine with us.
- */
- if (result.isEmpty()) {
- return;
- }
- assertTrue(ImmutableList.of("a").equals(result));
- assertEquals(1, result.size());
- }
+ public void testCopyOf_plainIterable() {
+ CountingIterable iterable = new CountingIterable();
+ List<String> list = ImmutableList.copyOf(iterable);
+ assertEquals(asList("a", "b", "a"), list);
+ }
- public void testBuilderAddCollectionHandlesNulls() {
- List<String> elements = Arrays.asList("a", null, "b");
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.addAll(elements);
- fail("Expected NullPointerException");
- } catch (NullPointerException expected) {
- }
- ImmutableList<String> result = builder.build();
- assertEquals(ImmutableList.of("a"), result);
- assertEquals(1, result.size());
- }
+ public void testCopyOf_plainIterable_iteratesOnce() {
+ CountingIterable iterable = new CountingIterable();
+ ImmutableList<String> unused = ImmutableList.copyOf(iterable);
+ assertEquals(1, iterable.count);
+ }
- public void testSortedCopyOf_natural() {
- Collection<Integer> c = MinimalCollection.of(4, 16, 10, -1, 5);
- ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
- assertEquals(asList(-1, 4, 5, 10, 16), list);
- }
+ public void testCopyOf_shortcut_empty() {
+ Collection<String> c = ImmutableList.of();
+ assertSame(c, ImmutableList.copyOf(c));
+ }
- public void testSortedCopyOf_natural_empty() {
- Collection<Integer> c = MinimalCollection.of();
- ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
- assertEquals(asList(), list);
- }
+ public void testCopyOf_shortcut_singleton() {
+ Collection<String> c = ImmutableList.of("a");
+ assertSame(c, ImmutableList.copyOf(c));
+ }
- public void testSortedCopyOf_natural_singleton() {
- Collection<Integer> c = MinimalCollection.of(100);
- ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
- assertEquals(asList(100), list);
- }
+ public void testCopyOf_shortcut_immutableList() {
+ Collection<String> c = ImmutableList.of("a", "b", "c");
+ assertSame(c, ImmutableList.copyOf(c));
+ }
- public void testSortedCopyOf_natural_containsNull() {
- Collection<Integer> c = MinimalCollection.of(1, 3, null, 2);
- try {
- ImmutableList.sortedCopyOf(c);
- fail("Expected NPE");
- } catch (NullPointerException expected) {
- }
+ public void testBuilderAddArrayHandlesNulls() {
+ String[] elements = {"a", null, "b"};
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.add(elements);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
}
+ ImmutableList<String> result = builder.build();
- public void testSortedCopyOf() {
- Collection<String> c = MinimalCollection.of("a", "b", "A", "c");
- List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- assertEquals(asList("a", "A", "b", "c"), list);
+ /*
+ * Maybe it rejects all elements, or maybe it adds "a" before failing.
+ * Either way is fine with us.
+ */
+ if (result.isEmpty()) {
+ return;
}
+ assertTrue(ImmutableList.of("a").equals(result));
+ assertEquals(1, result.size());
+ }
- public void testSortedCopyOf_empty() {
- Collection<String> c = MinimalCollection.of();
- List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- assertEquals(asList(), list);
- }
+ public void testBuilderAddCollectionHandlesNulls() {
+ List<String> elements = Arrays.asList("a", null, "b");
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.addAll(elements);
+ fail("Expected NullPointerException");
+ } catch (NullPointerException expected) {
+ }
+ ImmutableList<String> result = builder.build();
+ assertEquals(ImmutableList.of("a"), result);
+ assertEquals(1, result.size());
+ }
- public void testSortedCopyOf_singleton() {
- Collection<String> c = MinimalCollection.of("a");
- List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- assertEquals(asList("a"), list);
- }
+ public void testSortedCopyOf_natural() {
+ Collection<Integer> c = MinimalCollection.of(4, 16, 10, -1, 5);
+ ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
+ assertEquals(asList(-1, 4, 5, 10, 16), list);
+ }
- public void testSortedCopyOf_containsNull() {
- Collection<String> c = MinimalCollection.of("a", "b", "A", null, "c");
- try {
- ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
- fail("Expected NPE");
- } catch (NullPointerException expected) {
- }
- }
+ public void testSortedCopyOf_natural_empty() {
+ Collection<Integer> c = MinimalCollection.of();
+ ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
+ assertEquals(asList(), list);
+ }
- public void testToImmutableList() {
- CollectorTester.of(ImmutableList.<String>toImmutableList())
- .expectCollects(ImmutableList.of("a", "b", "c", "d"), "a", "b", "c", "d");
- }
+ public void testSortedCopyOf_natural_singleton() {
+ Collection<Integer> c = MinimalCollection.of(100);
+ ImmutableList<Integer> list = ImmutableList.sortedCopyOf(c);
+ assertEquals(asList(100), list);
}
- @GwtIncompatible // reflection
- public static class ConcurrentTests extends TestCase {
- enum WrapWithIterable {
- WRAP,
- NO_WRAP
+ public void testSortedCopyOf_natural_containsNull() {
+ Collection<Integer> c = MinimalCollection.of(1, 3, null, 2);
+ try {
+ ImmutableList.sortedCopyOf(c);
+ fail("Expected NPE");
+ } catch (NullPointerException expected) {
}
+ }
- private static void runConcurrentlyMutatedTest(
- Collection<Integer> initialContents,
- Iterable<ListFrobber> actionsToPerformConcurrently,
- WrapWithIterable wrap) {
- ConcurrentlyMutatedList<Integer> concurrentlyMutatedList =
- newConcurrentlyMutatedList(initialContents, actionsToPerformConcurrently);
+ public void testSortedCopyOf() {
+ Collection<String> c = MinimalCollection.of("a", "b", "A", "c");
+ List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ assertEquals(asList("a", "A", "b", "c"), list);
+ }
- Iterable<Integer> iterableToCopy =
- wrap == WrapWithIterable.WRAP
- ? unmodifiableIterable(concurrentlyMutatedList)
- : concurrentlyMutatedList;
+ public void testSortedCopyOf_empty() {
+ Collection<String> c = MinimalCollection.of();
+ List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ assertEquals(asList(), list);
+ }
- ImmutableList<Integer> copyOfIterable = ImmutableList.copyOf(iterableToCopy);
+ public void testSortedCopyOf_singleton() {
+ Collection<String> c = MinimalCollection.of("a");
+ List<String> list = ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ assertEquals(asList("a"), list);
+ }
- assertTrue(concurrentlyMutatedList.getAllStates().contains(copyOfIterable));
+ public void testSortedCopyOf_containsNull() {
+ Collection<String> c = MinimalCollection.of("a", "b", "A", null, "c");
+ try {
+ ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, c);
+ fail("Expected NPE");
+ } catch (NullPointerException expected) {
}
+ }
- private static void runConcurrentlyMutatedTest(WrapWithIterable wrap) {
- /*
- * TODO: Iterate over many array sizes and all possible operation lists,
- * performing adds and removes in different ways.
- */
- runConcurrentlyMutatedTest(elements(), ops(add(1), add(2)), wrap);
-
- runConcurrentlyMutatedTest(elements(), ops(add(1), nop()), wrap);
-
- runConcurrentlyMutatedTest(elements(), ops(add(1), remove()), wrap);
-
- runConcurrentlyMutatedTest(elements(), ops(nop(), add(1)), wrap);
-
- runConcurrentlyMutatedTest(elements(1), ops(remove(), nop()), wrap);
+ public void testToImmutableList() {
+ CollectorTester.of(ImmutableList.<String>toImmutableList())
+ .expectCollects(ImmutableList.of("a", "b", "c", "d"), "a", "b", "c", "d");
+ }
- runConcurrentlyMutatedTest(elements(1), ops(remove(), add(2)), wrap);
+ // Basic tests
- runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), remove()), wrap);
+ @GwtIncompatible // NullPointerTester
+ public void testNullPointers() {
+ NullPointerTester tester = new NullPointerTester();
+ tester.testAllPublicStaticMethods(ImmutableList.class);
+ tester.testAllPublicInstanceMethods(ImmutableList.of(1, 2, 3));
+ }
- runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), nop()), wrap);
+ @GwtIncompatible // SerializableTester
+ public void testSerialization_empty() {
+ Collection<String> c = ImmutableList.of();
+ assertSame(c, SerializableTester.reserialize(c));
+ }
- runConcurrentlyMutatedTest(elements(1, 2), ops(remove(), add(3)), wrap);
+ @GwtIncompatible // SerializableTester
+ public void testSerialization_singleton() {
+ Collection<String> c = ImmutableList.of("a");
+ SerializableTester.reserializeAndAssert(c);
+ }
- runConcurrentlyMutatedTest(elements(1, 2), ops(nop(), remove()), wrap);
+ @GwtIncompatible // SerializableTester
+ public void testSerialization_multiple() {
+ Collection<String> c = ImmutableList.of("a", "b", "c");
+ SerializableTester.reserializeAndAssert(c);
+ }
- runConcurrentlyMutatedTest(elements(1, 2, 3), ops(remove(), remove()), wrap);
- }
+ public void testEquals_immutableList() {
+ Collection<String> c = ImmutableList.of("a", "b", "c");
+ assertTrue(c.equals(ImmutableList.of("a", "b", "c")));
+ assertFalse(c.equals(ImmutableList.of("a", "c", "b")));
+ assertFalse(c.equals(ImmutableList.of("a", "b")));
+ assertFalse(c.equals(ImmutableList.of("a", "b", "c", "d")));
+ }
- private static ImmutableList<Integer> elements(Integer... elements) {
- return ImmutableList.copyOf(elements);
- }
+ public void testBuilderAdd() {
+ ImmutableList<String> list =
+ new ImmutableList.Builder<String>().add("a").add("b").add("a").add("c").build();
+ assertEquals(asList("a", "b", "a", "c"), list);
+ }
- private static ImmutableList<ListFrobber> ops(ListFrobber... elements) {
- return ImmutableList.copyOf(elements);
+ @GwtIncompatible("Builder impl")
+ public void testBuilderForceCopy() {
+ ImmutableList.Builder<Integer> builder = ImmutableList.builder();
+ Object[] prevArray = null;
+ for (int i = 0; i < 10; i++) {
+ builder.add(i);
+ assertNotSame(builder.contents, prevArray);
+ prevArray = builder.contents;
+ ImmutableList<Integer> unused = builder.build();
}
+ }
- public void testCopyOf_concurrentlyMutatedList() {
- runConcurrentlyMutatedTest(WrapWithIterable.NO_WRAP);
- }
+ @GwtIncompatible
+ public void testBuilderExactlySizedReusesArray() {
+ ImmutableList.Builder<Integer> builder = ImmutableList.builderWithExpectedSize(10);
+ Object[] builderArray = builder.contents;
+ for (int i = 0; i < 10; i++) {
+ builder.add(i);
+ }
+ Object[] builderArrayAfterAdds = builder.contents;
+ RegularImmutableList<Integer> list = (RegularImmutableList<Integer>) builder.build();
+ Object[] listInternalArray = list.array;
+ assertSame(builderArray, builderArrayAfterAdds);
+ assertSame(builderArray, listInternalArray);
+ }
- public void testCopyOf_concurrentlyMutatedIterable() {
- runConcurrentlyMutatedTest(WrapWithIterable.WRAP);
- }
+ public void testBuilderAdd_varargs() {
+ ImmutableList<String> list =
+ new ImmutableList.Builder<String>().add("a", "b", "a", "c").build();
+ assertEquals(asList("a", "b", "a", "c"), list);
+ }
- /** An operation to perform on a list. */
- interface ListFrobber {
- void perform(List<Integer> list);
- }
+ public void testBuilderAddAll_iterable() {
+ List<String> a = asList("a", "b");
+ List<String> b = asList("c", "d");
+ ImmutableList<String> list = new ImmutableList.Builder<String>().addAll(a).addAll(b).build();
+ assertEquals(asList("a", "b", "c", "d"), list);
+ b.set(0, "f");
+ assertEquals(asList("a", "b", "c", "d"), list);
+ }
- static ListFrobber add(final int element) {
- return new ListFrobber() {
- @Override
- public void perform(List<Integer> list) {
- list.add(0, element);
- }
- };
- }
+ public void testBuilderAddAll_iterator() {
+ List<String> a = asList("a", "b");
+ List<String> b = asList("c", "d");
+ ImmutableList<String> list =
+ new ImmutableList.Builder<String>().addAll(a.iterator()).addAll(b.iterator()).build();
+ assertEquals(asList("a", "b", "c", "d"), list);
+ b.set(0, "f");
+ assertEquals(asList("a", "b", "c", "d"), list);
+ }
- static ListFrobber remove() {
- return new ListFrobber() {
- @Override
- public void perform(List<Integer> list) {
- list.remove(0);
+ public void testComplexBuilder() {
+ List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF);
+ ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder();
+ for (Integer red : colorElem) {
+ for (Integer green : colorElem) {
+ for (Integer blue : colorElem) {
+ webSafeColorsBuilder.add((red << 16) + (green << 8) + blue);
}
- };
- }
-
- static ListFrobber nop() {
- return new ListFrobber() {
- @Override
- public void perform(List<Integer> list) {}
- };
- }
-
- /** A list that mutates itself after every call to each of its {@link List} methods. */
- interface ConcurrentlyMutatedList<E> extends List<E> {
- /**
- * The elements of a {@link ConcurrentlyMutatedList} are added and removed over time. This
- * method returns every state that the list has passed through at some point.
- */
- Set<List<E>> getAllStates();
- }
-
- /**
- * Returns a {@link ConcurrentlyMutatedList} that performs the given operations as its
- * concurrent modifications. The mutations occur in the same thread as the triggering method
- * call.
- */
- private static ConcurrentlyMutatedList<Integer> newConcurrentlyMutatedList(
- final Collection<Integer> initialContents,
- final Iterable<ListFrobber> actionsToPerformConcurrently) {
- InvocationHandler invocationHandler =
- new InvocationHandler() {
- final CopyOnWriteArrayList<Integer> delegate =
- new CopyOnWriteArrayList<>(initialContents);
-
- final Method getAllStatesMethod =
- getOnlyElement(asList(ConcurrentlyMutatedList.class.getDeclaredMethods()));
-
- final Iterator<ListFrobber> remainingActions = actionsToPerformConcurrently.iterator();
-
- final Set<List<Integer>> allStates = newHashSet();
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- return method.equals(getAllStatesMethod)
- ? getAllStates()
- : invokeListMethod(method, args);
- }
-
- private Set<List<Integer>> getAllStates() {
- return allStates;
- }
-
- private Object invokeListMethod(Method method, Object[] args) throws Throwable {
- try {
- Object returnValue = method.invoke(delegate, args);
- mutateDelegate();
- return returnValue;
- } catch (InvocationTargetException e) {
- throw e.getCause();
- } catch (IllegalAccessException e) {
- throw new AssertionError(e);
- }
- }
-
- private void mutateDelegate() {
- allStates.add(ImmutableList.copyOf(delegate));
- remainingActions.next().perform(delegate);
- allStates.add(ImmutableList.copyOf(delegate));
- }
- };
-
- @SuppressWarnings("unchecked")
- ConcurrentlyMutatedList<Integer> list =
- (ConcurrentlyMutatedList<Integer>)
- newProxyInstance(
- ImmutableListTest.CreationTests.class.getClassLoader(),
- new Class[] {ConcurrentlyMutatedList.class},
- invocationHandler);
- return list;
+ }
}
+ ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build();
+ assertEquals(216, webSafeColors.size());
+ Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]);
+ assertEquals(0x000000, (int) webSafeColorArray[0]);
+ assertEquals(0x000033, (int) webSafeColorArray[1]);
+ assertEquals(0x000066, (int) webSafeColorArray[2]);
+ assertEquals(0x003300, (int) webSafeColorArray[6]);
+ assertEquals(0x330000, (int) webSafeColorArray[36]);
+ assertEquals(0x000066, (int) webSafeColors.get(2));
+ assertEquals(0x003300, (int) webSafeColors.get(6));
+ ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build();
+ assertEquals(
+ "Modifying the builder should not have changed any already" + " built sets",
+ 216,
+ webSafeColors.size());
+ assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size());
+ Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]);
+ assertEquals(0x00BFFF, (int) appendColorArray[216]);
}
- public static class BasicTests extends TestCase {
-
- @GwtIncompatible // NullPointerTester
- public void testNullPointers() {
- NullPointerTester tester = new NullPointerTester();
- tester.testAllPublicStaticMethods(ImmutableList.class);
- tester.testAllPublicInstanceMethods(ImmutableList.of(1, 2, 3));
- }
-
- @GwtIncompatible // SerializableTester
- public void testSerialization_empty() {
- Collection<String> c = ImmutableList.of();
- assertSame(c, SerializableTester.reserialize(c));
- }
-
- @GwtIncompatible // SerializableTester
- public void testSerialization_singleton() {
- Collection<String> c = ImmutableList.of("a");
- SerializableTester.reserializeAndAssert(c);
- }
-
- @GwtIncompatible // SerializableTester
- public void testSerialization_multiple() {
- Collection<String> c = ImmutableList.of("a", "b", "c");
- SerializableTester.reserializeAndAssert(c);
- }
-
- public void testEquals_immutableList() {
- Collection<String> c = ImmutableList.of("a", "b", "c");
- assertTrue(c.equals(ImmutableList.of("a", "b", "c")));
- assertFalse(c.equals(ImmutableList.of("a", "c", "b")));
- assertFalse(c.equals(ImmutableList.of("a", "b")));
- assertFalse(c.equals(ImmutableList.of("a", "b", "c", "d")));
- }
-
- public void testBuilderAdd() {
- ImmutableList<String> list =
- new ImmutableList.Builder<String>().add("a").add("b").add("a").add("c").build();
- assertEquals(asList("a", "b", "a", "c"), list);
- }
-
- @GwtIncompatible("Builder impl")
- public void testBuilderForceCopy() {
- ImmutableList.Builder<Integer> builder = ImmutableList.builder();
- Object[] prevArray = null;
- for (int i = 0; i < 10; i++) {
- builder.add(i);
- assertNotSame(builder.contents, prevArray);
- prevArray = builder.contents;
- ImmutableList<Integer> unused = builder.build();
- }
+ public void testBuilderAddHandlesNullsCorrectly() {
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.add((String) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- @GwtIncompatible
- public void testBuilderExactlySizedReusesArray() {
- ImmutableList.Builder<Integer> builder = ImmutableList.builderWithExpectedSize(10);
- Object[] builderArray = builder.contents;
- for (int i = 0; i < 10; i++) {
- builder.add(i);
- }
- Object[] builderArrayAfterAdds = builder.contents;
- RegularImmutableList<Integer> list = (RegularImmutableList<Integer>) builder.build();
- Object[] listInternalArray = list.array;
- assertSame(builderArray, builderArrayAfterAdds);
- assertSame(builderArray, listInternalArray);
+ try {
+ builder.add((String[]) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAdd_varargs() {
- ImmutableList<String> list =
- new ImmutableList.Builder<String>().add("a", "b", "a", "c").build();
- assertEquals(asList("a", "b", "a", "c"), list);
+ try {
+ builder.add("a", null, "b");
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderAddAll_iterable() {
- List<String> a = asList("a", "b");
- List<String> b = asList("c", "d");
- ImmutableList<String> list = new ImmutableList.Builder<String>().addAll(a).addAll(b).build();
- assertEquals(asList("a", "b", "c", "d"), list);
- b.set(0, "f");
- assertEquals(asList("a", "b", "c", "d"), list);
+ public void testBuilderAddAllHandlesNullsCorrectly() {
+ ImmutableList.Builder<String> builder = ImmutableList.builder();
+ try {
+ builder.addAll((Iterable<String>) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAddAll_iterator() {
- List<String> a = asList("a", "b");
- List<String> b = asList("c", "d");
- ImmutableList<String> list =
- new ImmutableList.Builder<String>().addAll(a.iterator()).addAll(b.iterator()).build();
- assertEquals(asList("a", "b", "c", "d"), list);
- b.set(0, "f");
- assertEquals(asList("a", "b", "c", "d"), list);
+ try {
+ builder.addAll((Iterator<String>) null);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testComplexBuilder() {
- List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF);
- ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder();
- for (Integer red : colorElem) {
- for (Integer green : colorElem) {
- for (Integer blue : colorElem) {
- webSafeColorsBuilder.add((red << 16) + (green << 8) + blue);
- }
- }
- }
- ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build();
- assertEquals(216, webSafeColors.size());
- Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]);
- assertEquals(0x000000, (int) webSafeColorArray[0]);
- assertEquals(0x000033, (int) webSafeColorArray[1]);
- assertEquals(0x000066, (int) webSafeColorArray[2]);
- assertEquals(0x003300, (int) webSafeColorArray[6]);
- assertEquals(0x330000, (int) webSafeColorArray[36]);
- assertEquals(0x000066, (int) webSafeColors.get(2));
- assertEquals(0x003300, (int) webSafeColors.get(6));
- ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build();
- assertEquals(
- "Modifying the builder should not have changed any already" + " built sets",
- 216,
- webSafeColors.size());
- assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size());
- Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]);
- assertEquals(0x00BFFF, (int) appendColorArray[216]);
+ builder = ImmutableList.builder();
+ List<String> listWithNulls = asList("a", null, "b");
+ try {
+ builder.addAll(listWithNulls);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAddHandlesNullsCorrectly() {
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.add((String) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- try {
- builder.add((String[]) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- try {
- builder.add("a", null, "b");
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
+ builder = ImmutableList.builder();
+ Iterator<String> iteratorWithNulls = asList("a", null, "b").iterator();
+ try {
+ builder.addAll(iteratorWithNulls);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
- public void testBuilderAddAllHandlesNullsCorrectly() {
- ImmutableList.Builder<String> builder = ImmutableList.builder();
- try {
- builder.addAll((Iterable<String>) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- try {
- builder.addAll((Iterator<String>) null);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- builder = ImmutableList.builder();
- List<String> listWithNulls = asList("a", null, "b");
- try {
- builder.addAll(listWithNulls);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- builder = ImmutableList.builder();
- Iterator<String> iteratorWithNulls = asList("a", null, "b").iterator();
- try {
- builder.addAll(iteratorWithNulls);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
-
- Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b");
- try {
- builder.addAll(iterableWithNulls);
- fail("expected NullPointerException");
- } catch (NullPointerException expected) {
- }
+ Iterable<String> iterableWithNulls = MinimalIterable.of("a", null, "b");
+ try {
+ builder.addAll(iterableWithNulls);
+ fail("expected NullPointerException");
+ } catch (NullPointerException expected) {
}
+ }
- public void testAsList() {
- ImmutableList<String> list = ImmutableList.of("a", "b");
- assertSame(list, list.asList());
- }
+ public void testAsList() {
+ ImmutableList<String> list = ImmutableList.of("a", "b");
+ assertSame(list, list.asList());
}
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableMapFloodingTest.java b/guava-tests/test/com/google/common/collect/ImmutableMapFloodingTest.java
new file mode 100644
index 000000000..cdf85e3af
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableMapFloodingTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@GwtCompatible
+public class ImmutableMapFloodingTest extends AbstractHashFloodingTest<Map<Object, Object>> {
+ public ImmutableMapFloodingTest() {
+ super(
+ Arrays.asList(ConstructionPathway.values()),
+ n -> n * Math.log(n),
+ ImmutableList.of(QueryOp.MAP_GET));
+ }
+
+ /** All the ways to create an ImmutableMap. */
+ enum ConstructionPathway implements Construction<Map<Object, Object>> {
+ COPY_OF_MAP {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ Map<Object, Object> sourceMap = new LinkedHashMap<>();
+ for (Object k : keys) {
+ if (sourceMap.put(k, "dummy value") != null) {
+ throw new UnsupportedOperationException("duplicate key");
+ }
+ }
+ return ImmutableMap.copyOf(sourceMap);
+ }
+ },
+ COPY_OF_ENTRIES {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ return ImmutableMap.copyOf(
+ Lists.transform(keys, k -> Maps.immutableEntry(k, "dummy value")));
+ }
+ },
+ BUILDER_PUT_ONE_BY_ONE {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
+ for (Object k : keys) {
+ builder.put(k, "dummy value");
+ }
+ return builder.buildOrThrow();
+ }
+ },
+ BUILDER_PUT_ENTRIES_ONE_BY_ONE {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
+ for (Object k : keys) {
+ builder.put(Maps.immutableEntry(k, "dummy value"));
+ }
+ return builder.buildOrThrow();
+ }
+ },
+ BUILDER_PUT_ALL_MAP {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ Map<Object, Object> sourceMap = new LinkedHashMap<>();
+ for (Object k : keys) {
+ if (sourceMap.put(k, "dummy value") != null) {
+ throw new UnsupportedOperationException("duplicate key");
+ }
+ }
+ return ImmutableMap.builder().putAll(sourceMap).buildOrThrow();
+ }
+ },
+ BUILDER_PUT_ALL_ENTRIES {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ return ImmutableMap.builder()
+ .putAll(Lists.transform(keys, k -> Maps.immutableEntry(k, "dummy value")))
+ .buildOrThrow();
+ }
+ },
+ FORCE_JDK {
+ @Override
+ public Map<Object, Object> create(List<?> keys) {
+ ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
+ for (Object k : keys) {
+ builder.put(k, "dummy value");
+ }
+ return builder.buildJdkBacked();
+ }
+ };
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
index 63ce08a9c..3e4390bd4 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
@@ -24,18 +24,12 @@ import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
-import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.testing.AnEnum;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.ListTestSuiteBuilder;
-import com.google.common.collect.testing.MapInterfaceTest;
import com.google.common.collect.testing.MapTestSuiteBuilder;
-import com.google.common.collect.testing.MinimalSet;
-import com.google.common.collect.testing.SampleElements.Colliders;
-import com.google.common.collect.testing.SampleElements.Unhashables;
import com.google.common.collect.testing.TestStringMapGenerator;
-import com.google.common.collect.testing.UnhashableObject;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -51,7 +45,6 @@ import com.google.common.collect.testing.google.MapGenerators.ImmutableMapValues
import com.google.common.testing.CollectorTester;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
-import com.google.common.testing.SerializableTester;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@@ -72,6 +65,7 @@ import java.util.stream.Stream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ImmutableMap}.
@@ -87,7 +81,6 @@ public class ImmutableMapTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(ImmutableMapTest.class);
- suite.addTestSuite(FloodingTest.class);
suite.addTest(
MapTestSuiteBuilder.using(new ImmutableMapGenerator())
@@ -201,842 +194,688 @@ public class ImmutableMapTest extends TestCase {
return suite;
}
- public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> {
- public AbstractMapTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- protected Map<K, V> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- private static final Joiner JOINER = Joiner.on(", ");
+ // Creation tests
- @Override
- protected void assertMoreInvariants(Map<K, V> map) {
- // TODO: can these be moved to MapInterfaceTest?
- for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
- }
-
- assertEquals("{" + JOINER.join(map.entrySet()) + "}", map.toString());
- assertEquals("[" + JOINER.join(map.entrySet()) + "]", map.entrySet().toString());
- assertEquals("[" + JOINER.join(map.keySet()) + "]", map.keySet().toString());
- assertEquals("[" + JOINER.join(map.values()) + "]", map.values().toString());
-
- assertEquals(MinimalSet.from(map.entrySet()), map.entrySet());
- assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
- }
+ public void testEmptyBuilder() {
+ ImmutableMap<String, Integer> map = new Builder<String, Integer>().buildOrThrow();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class MapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- return ImmutableMap.of();
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableMap.of("one", 1, "two", 2, "three", 3);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testSingletonBuilder() {
+ ImmutableMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).buildOrThrow();
+ assertMapEquals(map, "one", 1);
}
- public static class SingletonMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return ImmutableMap.of("one", 1);
- }
+ public void testBuilder() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .buildOrThrow();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
+ @GwtIncompatible
+ public void testBuilderExactlySizedReusesArray() {
+ ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(10);
+ Entry<Integer, Integer>[] builderArray = builder.entries;
+ for (int i = 0; i < 10; i++) {
+ builder.put(i, i);
+ }
+ Entry<Integer, Integer>[] builderArrayAfterPuts = builder.entries;
+ RegularImmutableMap<Integer, Integer> map =
+ (RegularImmutableMap<Integer, Integer>) builder.buildOrThrow();
+ Entry<Integer, Integer>[] mapInternalArray = map.entries;
+ assertSame(builderArray, builderArrayAfterPuts);
+ assertSame(builderArray, mapInternalArray);
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testBuilder_orderEntriesByValue() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>()
+ .orderEntriesByValue(Ordering.natural())
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 4)
+ .put("two", 2)
+ .buildOrThrow();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
}
- @GwtIncompatible // SerializableTester
- public static class ReserializedMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- return SerializableTester.reserialize(ImmutableMap.of("one", 1, "two", 2, "three", 3));
- }
+ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
+ Builder<String, Integer> builder = new Builder<String, Integer>(2).put("four", 4).put("one", 1);
+ ImmutableMap<String, Integer> keyOrdered = builder.buildOrThrow();
+ ImmutableMap<String, Integer> valueOrdered =
+ builder.orderEntriesByValue(Ordering.natural()).buildOrThrow();
+ assertMapEquals(keyOrdered, "four", 4, "one", 1);
+ assertMapEquals(valueOrdered, "one", 1, "four", 4);
+ }
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
+ public void testBuilder_orderEntriesByValue_usedTwiceFails() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
+ try {
+ builder.orderEntriesByValue(Ordering.natural());
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException expected) {
}
+ }
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
+ @GwtIncompatible // we haven't implemented this
+ public void testBuilder_orderEntriesByValue_keepingLast() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .orderEntriesByValue(Ordering.natural())
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 3)
+ .put("four", 5)
+ .put("four", 4) // this should win because it's last
+ .put("two", 2);
+ assertMapEquals(
+ builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ try {
+ builder.buildOrThrow();
+ fail("Expected exception from duplicate keys");
+ } catch (IllegalArgumentException expected) {
}
}
- public static class MapTestsWithBadHashes extends AbstractMapTests<Object, Integer> {
-
- @Override
- protected Map<Object, Integer> makeEmptyMap() {
- throw new UnsupportedOperationException();
+ @GwtIncompatible // we haven't implemented this
+ public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserved() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .orderEntriesByValue(Ordering.natural())
+ .put("one", 1)
+ .put("one", 1);
+ assertMapEquals(builder.buildKeepingLast(), "one", 1);
+ try {
+ builder.buildOrThrow();
+ fail("Expected exception from duplicate keys");
+ } catch (IllegalArgumentException expected) {
}
+ }
- @Override
- protected Map<Object, Integer> makePopulatedMap() {
- Colliders colliders = new Colliders();
- return ImmutableMap.of(
- colliders.e0(), 0,
- colliders.e1(), 1,
- colliders.e2(), 2,
- colliders.e3(), 3);
- }
+ public void testBuilder_withImmutableEntry() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).buildOrThrow();
+ assertMapEquals(map, "one", 1);
+ }
- @Override
- protected Object getKeyNotInPopulatedMap() {
- return new Colliders().e4();
+ public void testBuilder_withImmutableEntryAndNullContents() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(Maps.immutableEntry("one", (Integer) null));
+ fail();
+ } catch (NullPointerException expected) {
}
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
+ try {
+ builder.put(Maps.immutableEntry((String) null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
}
- @GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
- public static class MapTestsWithUnhashableValues
- extends AbstractMapTests<Integer, UnhashableObject> {
- @Override
- protected Map<Integer, UnhashableObject> makeEmptyMap() {
- return ImmutableMap.of();
- }
+ private static class StringHolder {
+ String string;
+ }
- @Override
- protected Map<Integer, UnhashableObject> makePopulatedMap() {
- Unhashables unhashables = new Unhashables();
- return ImmutableMap.of(0, unhashables.e0(), 1, unhashables.e1(), 2, unhashables.e2());
- }
+ public void testBuilder_withMutableEntry() {
+ ImmutableMap.Builder<String, Integer> builder = new Builder<>();
+ final StringHolder holder = new StringHolder();
+ holder.string = "one";
+ Entry<String, Integer> entry =
+ new AbstractMapEntry<String, Integer>() {
+ @Override
+ public String getKey() {
+ return holder.string;
+ }
- @Override
- protected Integer getKeyNotInPopulatedMap() {
- return 3;
- }
+ @Override
+ public Integer getValue() {
+ return 1;
+ }
+ };
- @Override
- protected UnhashableObject getValueNotInPopulatedMap() {
- return new Unhashables().e3();
- }
+ builder.put(entry);
+ holder.string = "two";
+ assertMapEquals(builder.buildOrThrow(), "one", 1);
}
- @GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
- public static class MapTestsWithSingletonUnhashableValue extends MapTestsWithUnhashableValues {
- @Override
- protected Map<Integer, UnhashableObject> makePopulatedMap() {
- Unhashables unhashables = new Unhashables();
- return ImmutableMap.of(0, unhashables.e0());
- }
+ public void testBuilderPutAllWithEmptyMap() {
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>()
+ .putAll(Collections.<String, Integer>emptyMap())
+ .buildOrThrow();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class CreationTests extends TestCase {
- public void testEmptyBuilder() {
- ImmutableMap<String, Integer> map = new Builder<String, Integer>().buildOrThrow();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
- }
-
- public void testSingletonBuilder() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>().put("one", 1).buildOrThrow();
- assertMapEquals(map, "one", 1);
- }
+ public void testBuilderPutAll() {
+ Map<String, Integer> toPut = new LinkedHashMap<>();
+ toPut.put("one", 1);
+ toPut.put("two", 2);
+ toPut.put("three", 3);
+ Map<String, Integer> moreToPut = new LinkedHashMap<>();
+ moreToPut.put("four", 4);
+ moreToPut.put("five", 5);
- public void testBuilder() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .buildOrThrow();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- }
+ ImmutableMap<String, Integer> map =
+ new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).buildOrThrow();
+ assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ }
- @GwtIncompatible
- public void testBuilderExactlySizedReusesArray() {
- ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(10);
- Entry<Integer, Integer>[] builderArray = builder.entries;
- for (int i = 0; i < 10; i++) {
- builder.put(i, i);
- }
- Entry<Integer, Integer>[] builderArrayAfterPuts = builder.entries;
- RegularImmutableMap<Integer, Integer> map =
- (RegularImmutableMap<Integer, Integer>) builder.buildOrThrow();
- Entry<Integer, Integer>[] mapInternalArray = map.entries;
- assertSame(builderArray, builderArrayAfterPuts);
- assertSame(builderArray, mapInternalArray);
- }
+ public void testBuilderReuse() {
+ Builder<String, Integer> builder = new Builder<>();
+ ImmutableMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).buildOrThrow();
+ ImmutableMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).buildOrThrow();
- public void testBuilder_orderEntriesByValue() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>()
- .orderEntriesByValue(Ordering.natural())
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 4)
- .put("two", 2)
- .buildOrThrow();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- }
+ assertMapEquals(mapOne, "one", 1, "two", 2);
+ assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
+ }
- public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
- Builder<String, Integer> builder =
- new Builder<String, Integer>(2).put("four", 4).put("one", 1);
- ImmutableMap<String, Integer> keyOrdered = builder.buildOrThrow();
- ImmutableMap<String, Integer> valueOrdered =
- builder.orderEntriesByValue(Ordering.natural()).buildOrThrow();
- assertMapEquals(keyOrdered, "four", 4, "one", 1);
- assertMapEquals(valueOrdered, "one", 1, "four", 4);
+ public void testBuilderPutNullKeyFailsAtomically() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ builder.put("foo", 2);
+ assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ }
- public void testBuilder_orderEntriesByValue_usedTwiceFails() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
- try {
- builder.orderEntriesByValue(Ordering.natural());
- fail("Expected IllegalStateException");
- } catch (IllegalStateException expected) {
- }
+ public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(Maps.immutableEntry((String) null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ builder.put("foo", 2);
+ assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ }
- @GwtIncompatible // we haven't implemented this
- public void testBuilder_orderEntriesByValue_keepingLast() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .orderEntriesByValue(Ordering.natural())
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 3)
- .put("four", 5)
- .put("four", 4) // this should win because it's last
- .put("two", 2);
- assertMapEquals(
- builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
- try {
- builder.buildOrThrow();
- fail("Expected exception from duplicate keys");
- } catch (IllegalArgumentException expected) {
- }
- }
+ // for GWT compatibility
+ static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> {
+ public K key;
+ public V value;
- @GwtIncompatible // we haven't implemented this
- public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserved() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .orderEntriesByValue(Ordering.natural())
- .put("one", 1)
- .put("one", 1);
- assertMapEquals(builder.buildKeepingLast(), "one", 1);
- try {
- builder.buildOrThrow();
- fail("Expected exception from duplicate keys");
- } catch (IllegalArgumentException expected) {
- }
+ SimpleEntry(K key, V value) {
+ this.key = key;
+ this.value = value;
}
- public void testBuilder_withImmutableEntry() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).buildOrThrow();
- assertMapEquals(map, "one", 1);
+ @Override
+ public K getKey() {
+ return key;
}
- public void testBuilder_withImmutableEntryAndNullContents() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(Maps.immutableEntry("one", (Integer) null));
- fail();
- } catch (NullPointerException expected) {
- }
- try {
- builder.put(Maps.immutableEntry((String) null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
+ @Override
+ public V getValue() {
+ return value;
}
+ }
- private static class StringHolder {
- String string;
+ public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(new SimpleEntry<String, Integer>(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ builder.put("foo", 2);
+ assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ }
- public void testBuilder_withMutableEntry() {
- ImmutableMap.Builder<String, Integer> builder = new Builder<>();
- final StringHolder holder = new StringHolder();
- holder.string = "one";
- Entry<String, Integer> entry =
- new AbstractMapEntry<String, Integer>() {
- @Override
- public String getKey() {
- return holder.string;
- }
-
- @Override
- public Integer getValue() {
- return 1;
- }
- };
-
- builder.put(entry);
- holder.string = "two";
- assertMapEquals(builder.buildOrThrow(), "one", 1);
+ public void testBuilderPutNullKey() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAllWithEmptyMap() {
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>()
- .putAll(Collections.<String, Integer>emptyMap())
- .buildOrThrow();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
+ public void testBuilderPutNullValue() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.put("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAll() {
- Map<String, Integer> toPut = new LinkedHashMap<>();
- toPut.put("one", 1);
- toPut.put("two", 2);
- toPut.put("three", 3);
- Map<String, Integer> moreToPut = new LinkedHashMap<>();
- moreToPut.put("four", 4);
- moreToPut.put("five", 5);
-
- ImmutableMap<String, Integer> map =
- new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).buildOrThrow();
- assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
+ public void testBuilderPutNullKeyViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderReuse() {
- Builder<String, Integer> builder = new Builder<>();
- ImmutableMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).buildOrThrow();
- ImmutableMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).buildOrThrow();
-
- assertMapEquals(mapOne, "one", 1, "two", 2);
- assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
+ public void testBuilderPutNullValueViaPutAll() {
+ Builder<String, Integer> builder = new Builder<>();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap("one", null));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutNullKeyFailsAtomically() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- builder.put("foo", 2);
- assertMapEquals(builder.buildOrThrow(), "foo", 2);
- }
+ public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
+ Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .put("one", 1)
+ .put("one", 1); // throwing on this line might be better but it's too late to change
- public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(Maps.immutableEntry((String) null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- builder.put("foo", 2);
- assertMapEquals(builder.buildOrThrow(), "foo", 2);
+ try {
+ builder.buildOrThrow();
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- // for GWT compatibility
- static class SimpleEntry<K, V> extends AbstractMapEntry<K, V> {
- public K key;
- public V value;
-
- SimpleEntry(K key, V value) {
- this.key = key;
- this.value = value;
- }
-
- @Override
- public K getKey() {
- return key;
- }
-
- @Override
- public V getValue() {
- return value;
- }
- }
+ public void testBuildKeepingLast_allowsOverwrite() {
+ Builder<Integer, String> builder =
+ new Builder<Integer, String>()
+ .put(1, "un")
+ .put(2, "deux")
+ .put(70, "soixante-dix")
+ .put(70, "septante")
+ .put(70, "seventy")
+ .put(1, "one")
+ .put(2, "two");
+ ImmutableMap<Integer, String> map = builder.buildKeepingLast();
+ assertMapEquals(map, 1, "one", 2, "two", 70, "seventy");
+ }
- public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(new SimpleEntry<String, Integer>(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- builder.put("foo", 2);
- assertMapEquals(builder.buildOrThrow(), "foo", 2);
- }
+ public void testBuildKeepingLast_smallTableSameHash() {
+ String key1 = "QED";
+ String key2 = "R&D";
+ assertThat(key1.hashCode()).isEqualTo(key2.hashCode());
+ ImmutableMap<String, Integer> map =
+ ImmutableMap.<String, Integer>builder()
+ .put(key1, 1)
+ .put(key2, 2)
+ .put(key1, 3)
+ .put(key2, 4)
+ .buildKeepingLast();
+ assertMapEquals(map, key1, 3, key2, 4);
+ }
- public void testBuilderPutNullKey() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ // The java7 branch has different code depending on whether the entry indexes fit in a byte,
+ // short, or int. The small table in testBuildKeepingLast_allowsOverwrite will test the byte
+ // case. This method tests the short case.
+ public void testBuildKeepingLast_shortTable() {
+ Builder<Integer, String> builder = ImmutableMap.builder();
+ Map<Integer, String> expected = new LinkedHashMap<>();
+ for (int i = 0; i < 1000; i++) {
+ // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
+ // duplicates.
+ Integer key = i & ~1;
+ String value = String.valueOf(i);
+ builder.put(key, value);
+ expected.put(key, value);
+ }
+ ImmutableMap<Integer, String> map = builder.buildKeepingLast();
+ assertThat(map).hasSize(500);
+ assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ }
- public void testBuilderPutNullValue() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.put("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ // This method tests the int case.
+ public void testBuildKeepingLast_bigTable() {
+ Builder<Integer, String> builder = ImmutableMap.builder();
+ Map<Integer, String> expected = new LinkedHashMap<>();
+ for (int i = 0; i < 200_000; i++) {
+ // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
+ // duplicates.
+ Integer key = i & ~1;
+ String value = String.valueOf(i);
+ builder.put(key, value);
+ expected.put(key, value);
+ }
+ ImmutableMap<Integer, String> map = builder.buildKeepingLast();
+ assertThat(map).hasSize(100_000);
+ assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ }
- public void testBuilderPutNullKeyViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ private static class ClassWithTerribleHashCode implements Comparable<ClassWithTerribleHashCode> {
+ private final int value;
- public void testBuilderPutNullValueViaPutAll() {
- Builder<String, Integer> builder = new Builder<>();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap("one", null));
- fail();
- } catch (NullPointerException expected) {
- }
+ ClassWithTerribleHashCode(int value) {
+ this.value = value;
}
- public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
- Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .put("one", 1)
- .put("one", 1); // throwing on this line might be better but it's too late to change
-
- try {
- builder.buildOrThrow();
- fail();
- } catch (IllegalArgumentException expected) {
- }
+ @Override
+ public int compareTo(ClassWithTerribleHashCode that) {
+ return Integer.compare(this.value, that.value);
}
- public void testBuildKeepingLast_allowsOverwrite() {
- Builder<Integer, String> builder =
- new Builder<Integer, String>()
- .put(1, "un")
- .put(2, "deux")
- .put(70, "soixante-dix")
- .put(70, "septante")
- .put(70, "seventy")
- .put(1, "one")
- .put(2, "two");
- ImmutableMap<Integer, String> map = builder.buildKeepingLast();
- assertMapEquals(map, 1, "one", 2, "two", 70, "seventy");
+ @Override
+ public boolean equals(@Nullable Object x) {
+ return x instanceof ClassWithTerribleHashCode
+ && ((ClassWithTerribleHashCode) x).value == value;
}
- public void testBuildKeepingLast_smallTableSameHash() {
- String key1 = "QED";
- String key2 = "R&D";
- assertThat(key1.hashCode()).isEqualTo(key2.hashCode());
- ImmutableMap<String, Integer> map =
- ImmutableMap.<String, Integer>builder()
- .put(key1, 1)
- .put(key2, 2)
- .put(key1, 3)
- .put(key2, 4)
- .buildKeepingLast();
- assertMapEquals(map, key1, 3, key2, 4);
+ @Override
+ public int hashCode() {
+ return 23;
}
- // The java7 branch has different code depending on whether the entry indexes fit in a byte,
- // short, or int. The small table in testBuildKeepingLast_allowsOverwrite will test the byte
- // case. This method tests the short case.
- public void testBuildKeepingLast_shortTable() {
- Builder<Integer, String> builder = ImmutableMap.builder();
- Map<Integer, String> expected = new LinkedHashMap<>();
- for (int i = 0; i < 1000; i++) {
- // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
- // duplicates.
- Integer key = i & ~1;
- String value = String.valueOf(i);
- builder.put(key, value);
- expected.put(key, value);
- }
- ImmutableMap<Integer, String> map = builder.buildKeepingLast();
- assertThat(map).hasSize(500);
- assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ @Override
+ public String toString() {
+ return "ClassWithTerribleHashCode(" + value + ")";
}
+ }
- // This method tests the int case.
- public void testBuildKeepingLast_bigTable() {
- Builder<Integer, String> builder = ImmutableMap.builder();
- Map<Integer, String> expected = new LinkedHashMap<>();
- for (int i = 0; i < 200_000; i++) {
- // Truncate to even key, so we have put(0, "0") then put(0, "1"). Half the entries are
- // duplicates.
- Integer key = i & ~1;
- String value = String.valueOf(i);
- builder.put(key, value);
- expected.put(key, value);
- }
- ImmutableMap<Integer, String> map = builder.buildKeepingLast();
- assertThat(map).hasSize(100_000);
- assertThat(map).containsExactlyEntriesIn(expected).inOrder();
- }
+ @GwtIncompatible
+ public void testBuildKeepingLast_collisions() {
+ Map<ClassWithTerribleHashCode, Integer> expected = new LinkedHashMap<>();
+ Builder<ClassWithTerribleHashCode, Integer> builder = new Builder<>();
+ int size = RegularImmutableMap.MAX_HASH_BUCKET_LENGTH + 10;
+ for (int i = 0; i < size; i++) {
+ ClassWithTerribleHashCode key = new ClassWithTerribleHashCode(i);
+ builder.put(key, i);
+ builder.put(key, -i);
+ expected.put(key, -i);
+ }
+ ImmutableMap<ClassWithTerribleHashCode, Integer> map = builder.buildKeepingLast();
+ assertThat(map).containsExactlyEntriesIn(expected).inOrder();
+ assertThat(map).isInstanceOf(JdkBackedImmutableMap.class);
+ }
- private static class ClassWithTerribleHashCode
- implements Comparable<ClassWithTerribleHashCode> {
- private final int value;
-
- ClassWithTerribleHashCode(int value) {
- this.value = value;
- }
-
- @Override
- public int compareTo(ClassWithTerribleHashCode that) {
- return Integer.compare(this.value, that.value);
- }
-
- @Override
- public boolean equals(Object x) {
- return x instanceof ClassWithTerribleHashCode
- && ((ClassWithTerribleHashCode) x).value == value;
- }
-
- @Override
- public int hashCode() {
- return 23;
- }
-
- @Override
- public String toString() {
- return "ClassWithTerribleHashCode(" + value + ")";
- }
+ @GwtIncompatible // Pattern, Matcher
+ public void testBuilder_keepingLast_thenOrThrow() {
+ ImmutableMap.Builder<String, Integer> builder =
+ new Builder<String, Integer>()
+ .put("three", 3)
+ .put("one", 1)
+ .put("five", 5)
+ .put("four", 3)
+ .put("four", 5)
+ .put("four", 4) // this should win because it's last
+ .put("two", 2);
+ assertMapEquals(
+ builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2);
+ try {
+ builder.buildOrThrow();
+ fail("Expected exception from duplicate keys");
+ } catch (IllegalArgumentException expected) {
+ // We don't really care which values the exception message contains, but they should be
+ // different from each other. If buildKeepingLast() collapsed duplicates, that might end up
+ // not being true.
+ Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)");
+ assertThat(expected).hasMessageThat().matches(pattern);
+ Matcher matcher = pattern.matcher(expected.getMessage());
+ assertThat(matcher.matches()).isTrue();
+ assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2));
}
+ }
- @GwtIncompatible
- public void testBuildKeepingLast_collisions() {
- Map<ClassWithTerribleHashCode, Integer> expected = new LinkedHashMap<>();
- Builder<ClassWithTerribleHashCode, Integer> builder = new Builder<>();
- int size = RegularImmutableMap.MAX_HASH_BUCKET_LENGTH + 10;
- for (int i = 0; i < size; i++) {
- ClassWithTerribleHashCode key = new ClassWithTerribleHashCode(i);
- builder.put(key, i);
- builder.put(key, -i);
- expected.put(key, -i);
- }
- ImmutableMap<ClassWithTerribleHashCode, Integer> map = builder.buildKeepingLast();
- assertThat(map).containsExactlyEntriesIn(expected).inOrder();
- assertThat(map).isInstanceOf(JdkBackedImmutableMap.class);
- }
+ public void testOf() {
+ assertMapEquals(ImmutableMap.of("one", 1), "one", 1);
+ assertMapEquals(ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2);
+ assertMapEquals(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
+ assertMapEquals(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4);
+ assertMapEquals(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9);
+ assertMapEquals(
+ ImmutableMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9,
+ "ten", 10),
+ "one",
+ 1,
+ "two",
+ 2,
+ "three",
+ 3,
+ "four",
+ 4,
+ "five",
+ 5,
+ "six",
+ 6,
+ "seven",
+ 7,
+ "eight",
+ 8,
+ "nine",
+ 9,
+ "ten",
+ 10);
+ }
- @GwtIncompatible // Pattern, Matcher
- public void testBuilder_keepingLast_thenOrThrow() {
- ImmutableMap.Builder<String, Integer> builder =
- new Builder<String, Integer>()
- .put("three", 3)
- .put("one", 1)
- .put("five", 5)
- .put("four", 3)
- .put("four", 5)
- .put("four", 4) // this should win because it's last
- .put("two", 2);
- assertMapEquals(
- builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2);
- try {
- builder.buildOrThrow();
- fail("Expected exception from duplicate keys");
- } catch (IllegalArgumentException expected) {
- // We don't really care which values the exception message contains, but they should be
- // different from each other. If buildKeepingLast() collapsed duplicates, that might end up
- // not being true.
- Pattern pattern =
- Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)");
- assertThat(expected).hasMessageThat().matches(pattern);
- Matcher matcher = pattern.matcher(expected.getMessage());
- assertThat(matcher.matches()).isTrue();
- assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2));
- }
+ public void testOfNullKey() {
+ try {
+ ImmutableMap.of(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testOf() {
- assertMapEquals(ImmutableMap.of("one", 1), "one", 1);
- assertMapEquals(ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2);
- assertMapEquals(
- ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
- assertMapEquals(
- ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4);
- assertMapEquals(
- ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9);
- assertMapEquals(
- ImmutableMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9,
- "ten", 10),
- "one",
- 1,
- "two",
- 2,
- "three",
- 3,
- "four",
- 4,
- "five",
- 5,
- "six",
- 6,
- "seven",
- 7,
- "eight",
- 8,
- "nine",
- 9,
- "ten",
- 10);
+ try {
+ ImmutableMap.of("one", 1, null, 2);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOfNullKey() {
- try {
- ImmutableMap.of(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableMap.of("one", 1, null, 2);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullValue() {
+ try {
+ ImmutableMap.of("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testOfNullValue() {
- try {
- ImmutableMap.of("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
-
- try {
- ImmutableMap.of("one", 1, "two", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ ImmutableMap.of("one", 1, "two", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOfWithDuplicateKey() {
- try {
- ImmutableMap.of("one", 1, "one", 1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
+ public void testOfWithDuplicateKey() {
+ try {
+ ImmutableMap.of("one", 1, "one", 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testCopyOfEmptyMap() {
- ImmutableMap<String, Integer> copy =
- ImmutableMap.copyOf(Collections.<String, Integer>emptyMap());
- assertEquals(Collections.<String, Integer>emptyMap(), copy);
- assertSame(copy, ImmutableMap.copyOf(copy));
- }
+ public void testCopyOfEmptyMap() {
+ ImmutableMap<String, Integer> copy =
+ ImmutableMap.copyOf(Collections.<String, Integer>emptyMap());
+ assertEquals(Collections.<String, Integer>emptyMap(), copy);
+ assertSame(copy, ImmutableMap.copyOf(copy));
+ }
- public void testCopyOfSingletonMap() {
- ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1));
- assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableMap.copyOf(copy));
- }
+ public void testCopyOfSingletonMap() {
+ ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.singletonMap("one", 1));
+ assertMapEquals(copy, "one", 1);
+ assertSame(copy, ImmutableMap.copyOf(copy));
+ }
- public void testCopyOf() {
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
+ public void testCopyOf() {
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original);
- assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
- assertSame(copy, ImmutableMap.copyOf(copy));
- }
+ ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original);
+ assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
+ assertSame(copy, ImmutableMap.copyOf(copy));
+ }
- public void testToImmutableMap() {
- Collector<Entry<String, Integer>, ?, ImmutableMap<String, Integer>> collector =
- ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue);
- Equivalence<ImmutableMap<String, Integer>> equivalence =
- Equivalence.equals()
- .<Entry<String, Integer>>pairwise()
- .onResultOf(ImmutableMap::entrySet);
- CollectorTester.of(collector, equivalence)
- .expectCollects(
- ImmutableMap.of("one", 1, "two", 2, "three", 3),
- mapEntry("one", 1),
- mapEntry("two", 2),
- mapEntry("three", 3));
- }
+ public void testToImmutableMap() {
+ Collector<Entry<String, Integer>, ?, ImmutableMap<String, Integer>> collector =
+ ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue);
+ Equivalence<ImmutableMap<String, Integer>> equivalence =
+ Equivalence.equals().<Entry<String, Integer>>pairwise().onResultOf(ImmutableMap::entrySet);
+ CollectorTester.of(collector, equivalence)
+ .expectCollects(
+ ImmutableMap.of("one", 1, "two", 2, "three", 3),
+ mapEntry("one", 1),
+ mapEntry("two", 2),
+ mapEntry("three", 3));
+ }
- public void testToImmutableMap_exceptionOnDuplicateKey() {
- Collector<Entry<String, Integer>, ?, ImmutableMap<String, Integer>> collector =
- ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue);
- try {
- Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
+ public void testToImmutableMap_exceptionOnDuplicateKey() {
+ Collector<Entry<String, Integer>, ?, ImmutableMap<String, Integer>> collector =
+ ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue);
+ try {
+ Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testToImmutableMapMerging() {
- Collector<Entry<String, Integer>, ?, ImmutableMap<String, Integer>> collector =
- ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue, Integer::sum);
- Equivalence<ImmutableMap<String, Integer>> equivalence =
- Equivalence.equals()
- .<Entry<String, Integer>>pairwise()
- .onResultOf(ImmutableMap::entrySet);
- CollectorTester.of(collector, equivalence)
- .expectCollects(
- ImmutableMap.of("one", 1, "two", 4, "three", 3),
- mapEntry("one", 1),
- mapEntry("two", 2),
- mapEntry("three", 3),
- mapEntry("two", 2));
- }
+ public void testToImmutableMapMerging() {
+ Collector<Entry<String, Integer>, ?, ImmutableMap<String, Integer>> collector =
+ ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue, Integer::sum);
+ Equivalence<ImmutableMap<String, Integer>> equivalence =
+ Equivalence.equals().<Entry<String, Integer>>pairwise().onResultOf(ImmutableMap::entrySet);
+ CollectorTester.of(collector, equivalence)
+ .expectCollects(
+ ImmutableMap.of("one", 1, "two", 4, "three", 3),
+ mapEntry("one", 1),
+ mapEntry("two", 2),
+ mapEntry("three", 3),
+ mapEntry("two", 2));
}
+ // Non-creation tests
+
public void testNullGet() {
ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1);
assertNull(map.get(null));
@@ -1090,7 +929,7 @@ public class ImmutableMapTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof IntHolder) && ((IntHolder) o).value == value;
}
@@ -1185,7 +1024,7 @@ public class ImmutableMapTest extends TestCase {
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked")
public void ignore_testSerializationNoDuplication_regularImmutableMap() throws Exception {
- // Tests that searializing a map, its keySet, and values only writes the underlying data once.
+ // Tests that serializing a map, its keySet, and values only writes the underlying data once.
Entry<Integer, Integer>[] entries = (Entry<Integer, Integer>[]) new Entry<?, ?>[1000];
for (int i = 0; i < 1000; i++) {
@@ -1215,7 +1054,7 @@ public class ImmutableMapTest extends TestCase {
@GwtIncompatible // SerializableTester
@SuppressWarnings("unchecked")
public void ignore_testSerializationNoDuplication_jdkBackedImmutableMap() throws Exception {
- // Tests that searializing a map, its keySet, and values only writes
+ // Tests that serializing a map, its keySet, and values only writes
// the underlying data once.
Entry<Integer, Integer>[] entries = (Entry<Integer, Integer>[]) new Entry<?, ?>[1000];
@@ -1378,86 +1217,4 @@ public class ImmutableMapTest extends TestCase {
entryList.get(0).setValue("3");
assertThat(map).containsExactly("a", "1", "b", "2").inOrder();
}
-
- public static class FloodingTest extends AbstractHashFloodingTest<Map<Object, Object>> {
- public FloodingTest() {
- super(
- Arrays.asList(ConstructionPathway.values()),
- n -> n * Math.log(n),
- ImmutableList.of(QueryOp.MAP_GET));
- }
-
- /** All the ways to create an ImmutableMap. */
- enum ConstructionPathway implements Construction<Map<Object, Object>> {
- COPY_OF_MAP {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- Map<Object, Object> sourceMap = new LinkedHashMap<>();
- for (Object k : keys) {
- if (sourceMap.put(k, "dummy value") != null) {
- throw new UnsupportedOperationException("duplicate key");
- }
- }
- return ImmutableMap.copyOf(sourceMap);
- }
- },
- COPY_OF_ENTRIES {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- return ImmutableMap.copyOf(
- Lists.transform(keys, k -> Maps.immutableEntry(k, "dummy value")));
- }
- },
- BUILDER_PUT_ONE_BY_ONE {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
- for (Object k : keys) {
- builder.put(k, "dummy value");
- }
- return builder.buildOrThrow();
- }
- },
- BUILDER_PUT_ENTRIES_ONE_BY_ONE {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
- for (Object k : keys) {
- builder.put(Maps.immutableEntry(k, "dummy value"));
- }
- return builder.buildOrThrow();
- }
- },
- BUILDER_PUT_ALL_MAP {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- Map<Object, Object> sourceMap = new LinkedHashMap<>();
- for (Object k : keys) {
- if (sourceMap.put(k, "dummy value") != null) {
- throw new UnsupportedOperationException("duplicate key");
- }
- }
- return ImmutableMap.builder().putAll(sourceMap).buildOrThrow();
- }
- },
- BUILDER_PUT_ALL_ENTRIES {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- return ImmutableMap.builder()
- .putAll(Lists.transform(keys, k -> Maps.immutableEntry(k, "dummy value")))
- .buildOrThrow();
- }
- },
- FORCE_JDK {
- @Override
- public Map<Object, Object> create(List<?> keys) {
- ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
- for (Object k : keys) {
- builder.put(k, "dummy value");
- }
- return builder.buildJdkBacked();
- }
- };
- }
- }
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java
new file mode 100644
index 000000000..76a1fac59
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableMapWithBadHashesMapInterfaceTest.java
@@ -0,0 +1,50 @@
+/*
+ * 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 com.google.common.collect.testing.SampleElements.Colliders;
+import java.util.Map;
+
+@GwtCompatible
+public class ImmutableMapWithBadHashesMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<Object, Integer> {
+ @Override
+ protected Map<Object, Integer> makeEmptyMap() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ protected Map<Object, Integer> makePopulatedMap() {
+ Colliders colliders = new Colliders();
+ return ImmutableMap.of(
+ colliders.e0(), 0,
+ colliders.e1(), 1,
+ colliders.e2(), 2,
+ colliders.e3(), 3);
+ }
+
+ @Override
+ protected Object getKeyNotInPopulatedMap() {
+ return new Colliders().e4();
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableMultisetFloodingTest.java b/guava-tests/test/com/google/common/collect/ImmutableMultisetFloodingTest.java
new file mode 100644
index 000000000..551637987
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableMultisetFloodingTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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 com.google.errorprone.annotations.CanIgnoreReturnValue;
+import java.util.Arrays;
+import java.util.List;
+
+@GwtCompatible
+public class ImmutableMultisetFloodingTest extends AbstractHashFloodingTest<Multiset<Object>> {
+ public ImmutableMultisetFloodingTest() {
+ super(
+ Arrays.asList(ConstructionPathway.values()),
+ n -> n * Math.log(n),
+ ImmutableList.of(
+ QueryOp.create(
+ "count",
+ (ms, o) -> {
+ int unused = ms.count(o);
+ },
+ Math::log)));
+ }
+
+ /** All the ways to create an ImmutableMultiset. */
+ enum ConstructionPathway implements Construction<Multiset<Object>> {
+ COPY_OF_COLLECTION {
+ @Override
+ public ImmutableMultiset<Object> create(List<?> keys) {
+ return ImmutableMultiset.copyOf(keys);
+ }
+ },
+ COPY_OF_ITERATOR {
+ @Override
+ public ImmutableMultiset<Object> create(List<?> keys) {
+ return ImmutableMultiset.copyOf(keys.iterator());
+ }
+ },
+ BUILDER_ADD_ENTRY_BY_ENTRY {
+ @Override
+ public ImmutableMultiset<Object> create(List<?> keys) {
+ ImmutableMultiset.Builder<Object> builder = ImmutableMultiset.builder();
+ for (Object o : keys) {
+ builder.add(o);
+ }
+ return builder.build();
+ }
+ },
+ BUILDER_ADD_ALL_COLLECTION {
+ @Override
+ public ImmutableMultiset<Object> create(List<?> keys) {
+ ImmutableMultiset.Builder<Object> builder = ImmutableMultiset.builder();
+ builder.addAll(keys);
+ return builder.build();
+ }
+ };
+
+ @CanIgnoreReturnValue
+ @Override
+ public abstract ImmutableMultiset<Object> create(List<?> keys);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java b/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java
index 3cb6d7526..719cfc8c1 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java
@@ -36,9 +36,7 @@ import com.google.common.testing.CollectorTester;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
@@ -49,6 +47,7 @@ import java.util.stream.Collector;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ImmutableMultiset}.
@@ -62,7 +61,6 @@ public class ImmutableMultisetTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(ImmutableMultisetTest.class);
- suite.addTestSuite(FloodingTest.class);
suite.addTest(
MultisetTestSuiteBuilder.using(
@@ -357,11 +355,11 @@ public class ImmutableMultisetTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof TypeWithDuplicates && ((TypeWithDuplicates) obj).a == a;
}
- public boolean fullEquals(TypeWithDuplicates other) {
+ public boolean fullEquals(@Nullable TypeWithDuplicates other) {
return other != null && a == other.a && b == other.b;
}
}
@@ -667,57 +665,4 @@ public class ImmutableMultisetTest extends TestCase {
assertThat(builder.build().elementSet()).containsExactly("a", "c", "b").inOrder();
assertThat(multiset.elementSet()).containsExactly("a", "c").inOrder();
}
-
- public static class FloodingTest extends AbstractHashFloodingTest<Multiset<Object>> {
- public FloodingTest() {
- super(
- Arrays.asList(ConstructionPathway.values()),
- n -> n * Math.log(n),
- ImmutableList.of(
- QueryOp.create(
- "count",
- (ms, o) -> {
- int unused = ms.count(o);
- },
- Math::log)));
- }
-
- /** All the ways to create an ImmutableMultiset. */
- enum ConstructionPathway implements Construction<Multiset<Object>> {
- COPY_OF_COLLECTION {
- @Override
- public ImmutableMultiset<Object> create(List<?> keys) {
- return ImmutableMultiset.copyOf(keys);
- }
- },
- COPY_OF_ITERATOR {
- @Override
- public ImmutableMultiset<Object> create(List<?> keys) {
- return ImmutableMultiset.copyOf(keys.iterator());
- }
- },
- BUILDER_ADD_ENTRY_BY_ENTRY {
- @Override
- public ImmutableMultiset<Object> create(List<?> keys) {
- ImmutableMultiset.Builder<Object> builder = ImmutableMultiset.builder();
- for (Object o : keys) {
- builder.add(o);
- }
- return builder.build();
- }
- },
- BUILDER_ADD_ALL_COLLECTION {
- @Override
- public ImmutableMultiset<Object> create(List<?> keys) {
- ImmutableMultiset.Builder<Object> builder = ImmutableMultiset.builder();
- builder.addAll(keys);
- return builder.build();
- }
- };
-
- @CanIgnoreReturnValue
- @Override
- public abstract ImmutableMultiset<Object> create(List<?> keys);
- }
- }
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSetFloodingTest.java b/guava-tests/test/com/google/common/collect/ImmutableSetFloodingTest.java
new file mode 100644
index 000000000..c32a160c5
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableSetFloodingTest.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2007 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.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+@GwtCompatible
+public class ImmutableSetFloodingTest extends AbstractHashFloodingTest<Set<Object>> {
+ public ImmutableSetFloodingTest() {
+ super(
+ Arrays.asList(ConstructionPathway.values()),
+ n -> n * Math.log(n),
+ ImmutableList.of(
+ QueryOp.create(
+ "contains",
+ (s, o) -> {
+ boolean unused = s.contains(o);
+ },
+ Math::log)));
+ }
+
+ /** All the ways to construct an ImmutableSet. */
+ enum ConstructionPathway implements Construction<Set<Object>> {
+ OF {
+ @Override
+ public ImmutableSet<Object> create(List<?> list) {
+ Object o1 = list.get(0);
+ Object o2 = list.get(1);
+ Object o3 = list.get(2);
+ Object o4 = list.get(3);
+ Object o5 = list.get(4);
+ Object o6 = list.get(5);
+ Object[] rest = list.subList(6, list.size()).toArray();
+ return ImmutableSet.of(o1, o2, o3, o4, o5, o6, rest);
+ }
+ },
+ COPY_OF_ARRAY {
+ @Override
+ public ImmutableSet<Object> create(List<?> list) {
+ return ImmutableSet.copyOf(list.toArray());
+ }
+ },
+ COPY_OF_LIST {
+ @Override
+ public ImmutableSet<Object> create(List<?> list) {
+ return ImmutableSet.copyOf(list);
+ }
+ },
+ BUILDER_ADD_ONE_BY_ONE {
+ @Override
+ public ImmutableSet<Object> create(List<?> list) {
+ ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
+ for (Object o : list) {
+ builder.add(o);
+ }
+ return builder.build();
+ }
+ },
+ BUILDER_ADD_ARRAY {
+ @Override
+ public ImmutableSet<Object> create(List<?> list) {
+ ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
+ builder.add(list.toArray());
+ return builder.build();
+ }
+ },
+ BUILDER_ADD_LIST {
+ @Override
+ public ImmutableSet<Object> create(List<?> list) {
+ ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
+ builder.addAll(list);
+ return builder.build();
+ }
+ };
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSetTest.java b/guava-tests/test/com/google/common/collect/ImmutableSetTest.java
index 182851766..4f76cc888 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableSetTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableSetTest.java
@@ -37,16 +37,15 @@ import com.google.common.collect.testing.google.SetGenerators.ImmutableSetUnsize
import com.google.common.collect.testing.google.SetGenerators.ImmutableSetWithBadHashesGenerator;
import com.google.common.testing.CollectorTester;
import com.google.common.testing.EqualsTester;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
-import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.Collector;
import junit.framework.Test;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link ImmutableSet}.
@@ -160,7 +159,6 @@ public class ImmutableSetTest extends AbstractImmutableSetTest {
.createTestSuite());
suite.addTestSuite(ImmutableSetTest.class);
- suite.addTestSuite(FloodingTest.class);
return suite;
}
@@ -324,11 +322,11 @@ public class ImmutableSetTest extends AbstractImmutableSetTest {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
return obj instanceof TypeWithDuplicates && ((TypeWithDuplicates) obj).a == a;
}
- public boolean fullEquals(TypeWithDuplicates other) {
+ public boolean fullEquals(@Nullable TypeWithDuplicates other) {
return other != null && a == other.a && b == other.b;
}
}
@@ -391,73 +389,4 @@ public class ImmutableSetTest extends AbstractImmutableSetTest {
ImmutableSet<Object> subject = builder.add(1).add(2).add(3).build();
assertFalse(subject.contains(4));
}
-
- public static class FloodingTest extends AbstractHashFloodingTest<Set<Object>> {
- public FloodingTest() {
- super(
- Arrays.asList(ConstructionPathway.values()),
- n -> n * Math.log(n),
- ImmutableList.of(
- QueryOp.create(
- "contains",
- (s, o) -> {
- boolean unused = s.contains(o);
- },
- Math::log)));
- }
- /** All the ways to construct an ImmutableSet. */
- enum ConstructionPathway implements Construction<Set<Object>> {
- OF {
- @Override
- public ImmutableSet<Object> create(List<?> list) {
- Object o1 = list.get(0);
- Object o2 = list.get(1);
- Object o3 = list.get(2);
- Object o4 = list.get(3);
- Object o5 = list.get(4);
- Object o6 = list.get(5);
- Object[] rest = list.subList(6, list.size()).toArray();
- return ImmutableSet.of(o1, o2, o3, o4, o5, o6, rest);
- }
- },
- COPY_OF_ARRAY {
- @Override
- public ImmutableSet<Object> create(List<?> list) {
- return ImmutableSet.copyOf(list.toArray());
- }
- },
- COPY_OF_LIST {
- @Override
- public ImmutableSet<Object> create(List<?> list) {
- return ImmutableSet.copyOf(list);
- }
- },
- BUILDER_ADD_ONE_BY_ONE {
- @Override
- public ImmutableSet<Object> create(List<?> list) {
- ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
- for (Object o : list) {
- builder.add(o);
- }
- return builder.build();
- }
- },
- BUILDER_ADD_ARRAY {
- @Override
- public ImmutableSet<Object> create(List<?> list) {
- ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
- builder.add(list.toArray());
- return builder.build();
- }
- },
- BUILDER_ADD_LIST {
- @Override
- public ImmutableSet<Object> create(List<?> list) {
- ImmutableSet.Builder<Object> builder = ImmutableSet.builder();
- builder.addAll(list);
- return builder.build();
- }
- };
- }
- }
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java
new file mode 100644
index 000000000..5823d542d
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapInclusiveMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapHeadMapInclusiveMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("c", true);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "d";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java
new file mode 100644
index 000000000..ed96bd1f5
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapHeadMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapHeadMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("d");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "d";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java
new file mode 100644
index 000000000..7d4566390
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapSubMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapSubMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).subMap("b", "d");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 4;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java
new file mode 100644
index 000000000..15ba852fa
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapExclusiveMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapTailMapExclusiveMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("a", false);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java
new file mode 100644
index 000000000..54c3aa575
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTailMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class ImmutableSortedMapTailMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("b");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return 1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java
index 1de9e6972..9eb466cd4 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java
@@ -22,12 +22,10 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
-import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSortedMap.Builder;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.NavigableMapTestSuiteBuilder;
-import com.google.common.collect.testing.SortedMapInterfaceTest;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -53,6 +51,7 @@ import java.util.stream.Stream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link ImmutableSortedMap}.
@@ -125,736 +124,561 @@ public class ImmutableSortedMapTest extends TestCase {
return suite;
}
- public abstract static class AbstractMapTests<K, V> extends SortedMapInterfaceTest<K, V> {
- public AbstractMapTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- protected SortedMap<K, V> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- private static final Joiner joiner = Joiner.on(", ");
+ // Creation tests
- @Override
- protected void assertMoreInvariants(Map<K, V> map) {
- // TODO: can these be moved to MapInterfaceTest?
- for (Entry<K, V> entry : map.entrySet()) {
- assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
- }
-
- assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
- assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
- assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
- assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());
-
- assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
- assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
- }
+ public void testEmptyBuilder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder().build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class MapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makeEmptyMap() {
- return ImmutableSortedMap.of();
- }
-
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testSingletonBuilder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).build();
+ assertMapEquals(map, "one", 1);
}
- public static class SingletonMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("one", 1);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
- }
+ public void testBuilder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
}
- @GwtIncompatible // SerializableTester
- public static class ReserializedMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return SerializableTester.reserialize(ImmutableSortedMap.of("one", 1, "two", 2, "three", 3));
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "minus one";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return -1;
+ @SuppressWarnings("DoNotCall")
+ public void testBuilder_orderEntriesByValueFails() {
+ ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.orderEntriesByValue(Ordering.natural());
+ fail("Expected UnsupportedOperationException");
+ } catch (UnsupportedOperationException expected) {
}
}
- public static class HeadMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("d");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "d";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
- }
+ public void testBuilder_withImmutableEntry() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .put(Maps.immutableEntry("one", 1))
+ .build();
+ assertMapEquals(map, "one", 1);
}
- public static class HeadMapInclusiveTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).headMap("c", true);
+ public void testBuilder_withImmutableEntryAndNullContents() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.put(Maps.immutableEntry("one", (Integer) null));
+ fail();
+ } catch (NullPointerException expected) {
}
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "d";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
+ try {
+ builder.put(Maps.immutableEntry((String) null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
}
- public static class TailMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("b");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 1;
- }
+ private static class StringHolder {
+ String string;
}
- public static class TailExclusiveMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).tailMap("a", false);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 1;
- }
+ public void testBuilder_withMutableEntry() {
+ ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ final StringHolder holder = new StringHolder();
+ holder.string = "one";
+ Entry<String, Integer> entry =
+ new AbstractMapEntry<String, Integer>() {
+ @Override
+ public String getKey() {
+ return holder.string;
+ }
+
+ @Override
+ public Integer getValue() {
+ return 1;
+ }
+ };
+
+ builder.put(entry);
+ holder.string = "two";
+ assertMapEquals(builder.build(), "one", 1);
}
- public static class SubMapTests extends AbstractMapTests<String, Integer> {
- @Override
- protected SortedMap<String, Integer> makePopulatedMap() {
- return ImmutableSortedMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5).subMap("b", "d");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
-
- @Override
- protected Integer getValueNotInPopulatedMap() {
- return 4;
- }
+ public void testBuilderPutAllWithEmptyMap() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .putAll(Collections.<String, Integer>emptyMap())
+ .build();
+ assertEquals(Collections.<String, Integer>emptyMap(), map);
}
- public static class CreationTests extends TestCase {
- public void testEmptyBuilder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder().build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
- }
-
- public void testSingletonBuilder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder().put("one", 1).build();
- assertMapEquals(map, "one", 1);
- }
-
- public void testBuilder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
- }
-
- @SuppressWarnings("DoNotCall")
- public void testBuilder_orderEntriesByValueFails() {
- ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.orderEntriesByValue(Ordering.natural());
- fail("Expected UnsupportedOperationException");
- } catch (UnsupportedOperationException expected) {
- }
- }
+ public void testBuilderPutAll() {
+ Map<String, Integer> toPut = new LinkedHashMap<>();
+ toPut.put("one", 1);
+ toPut.put("two", 2);
+ toPut.put("three", 3);
+ Map<String, Integer> moreToPut = new LinkedHashMap<>();
+ moreToPut.put("four", 4);
+ moreToPut.put("five", 5);
+
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>naturalOrder().putAll(toPut).putAll(moreToPut).build();
+ assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
+ }
- public void testBuilder_withImmutableEntry() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .put(Maps.immutableEntry("one", 1))
- .build();
- assertMapEquals(map, "one", 1);
- }
+ public void testBuilderReuse() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ ImmutableSortedMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
+ ImmutableSortedMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
- public void testBuilder_withImmutableEntryAndNullContents() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.put(Maps.immutableEntry("one", (Integer) null));
- fail();
- } catch (NullPointerException expected) {
- }
- try {
- builder.put(Maps.immutableEntry((String) null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ assertMapEquals(mapOne, "one", 1, "two", 2);
+ assertMapEquals(mapTwo, "four", 4, "one", 1, "three", 3, "two", 2);
+ }
- private static class StringHolder {
- String string;
+ public void testBuilderPutNullKey() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.put(null, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilder_withMutableEntry() {
- ImmutableSortedMap.Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- final StringHolder holder = new StringHolder();
- holder.string = "one";
- Entry<String, Integer> entry =
- new AbstractMapEntry<String, Integer>() {
- @Override
- public String getKey() {
- return holder.string;
- }
-
- @Override
- public Integer getValue() {
- return 1;
- }
- };
-
- builder.put(entry);
- holder.string = "two";
- assertMapEquals(builder.build(), "one", 1);
+ public void testBuilderPutNullValue() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.put("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAllWithEmptyMap() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .putAll(Collections.<String, Integer>emptyMap())
- .build();
- assertEquals(Collections.<String, Integer>emptyMap(), map);
+ public void testBuilderPutNullKeyViaPutAll() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutAll() {
- Map<String, Integer> toPut = new LinkedHashMap<>();
- toPut.put("one", 1);
- toPut.put("two", 2);
- toPut.put("three", 3);
- Map<String, Integer> moreToPut = new LinkedHashMap<>();
- moreToPut.put("four", 4);
- moreToPut.put("five", 5);
-
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .putAll(toPut)
- .putAll(moreToPut)
- .build();
- assertMapEquals(map, "five", 5, "four", 4, "one", 1, "three", 3, "two", 2);
+ public void testBuilderPutNullValueViaPutAll() {
+ Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
+ try {
+ builder.putAll(Collections.<String, Integer>singletonMap("one", null));
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderReuse() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- ImmutableSortedMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
- ImmutableSortedMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();
+ public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
+ Builder<String, Integer> builder =
+ ImmutableSortedMap.<String, Integer>naturalOrder()
+ .put("one", 1)
+ .put("one", 2); // throwing on this line would be even better
- assertMapEquals(mapOne, "one", 1, "two", 2);
- assertMapEquals(mapTwo, "four", 4, "one", 1, "three", 3, "two", 2);
+ try {
+ builder.build();
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testBuilderPutNullKey() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.put(null, 1);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testOf() {
+ assertMapEquals(ImmutableSortedMap.of("one", 1), "one", 1);
+ assertMapEquals(ImmutableSortedMap.of("one", 1, "two", 2), "one", 1, "two", 2);
+ assertMapEquals(
+ ImmutableSortedMap.of("one", 1, "two", 2, "three", 3), "one", 1, "three", 3, "two", 2);
+ assertMapEquals(
+ ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4),
+ "four",
+ 4,
+ "one",
+ 1,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6),
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7),
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8),
+ "eight",
+ 8,
+ "five",
+ 5,
+ "four",
+ 4,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9),
+ "eight",
+ 8,
+ "five",
+ 5,
+ "four",
+ 4,
+ "nine",
+ 9,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "three",
+ 3,
+ "two",
+ 2);
+ assertMapEquals(
+ ImmutableSortedMap.of(
+ "one", 1,
+ "two", 2,
+ "three", 3,
+ "four", 4,
+ "five", 5,
+ "six", 6,
+ "seven", 7,
+ "eight", 8,
+ "nine", 9,
+ "ten", 10),
+ "eight",
+ 8,
+ "five",
+ 5,
+ "four",
+ 4,
+ "nine",
+ 9,
+ "one",
+ 1,
+ "seven",
+ 7,
+ "six",
+ 6,
+ "ten",
+ 10,
+ "three",
+ 3,
+ "two",
+ 2);
+ }
- public void testBuilderPutNullValue() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.put("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullKey() {
+ Integer n = null;
+ try {
+ ImmutableSortedMap.of(n, 1);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testBuilderPutNullKeyViaPutAll() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
- fail();
- } catch (NullPointerException expected) {
- }
+ try {
+ ImmutableSortedMap.of("one", 1, null, 2);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testBuilderPutNullValueViaPutAll() {
- Builder<String, Integer> builder = ImmutableSortedMap.naturalOrder();
- try {
- builder.putAll(Collections.<String, Integer>singletonMap("one", null));
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testOfNullValue() {
+ try {
+ ImmutableSortedMap.of("one", null);
+ fail();
+ } catch (NullPointerException expected) {
}
- public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
- Builder<String, Integer> builder =
- ImmutableSortedMap.<String, Integer>naturalOrder()
- .put("one", 1)
- .put("one", 2); // throwing on this line would be even better
-
- try {
- builder.build();
- fail();
- } catch (IllegalArgumentException expected) {
- }
+ try {
+ ImmutableSortedMap.of("one", 1, "two", null);
+ fail();
+ } catch (NullPointerException expected) {
}
+ }
- public void testOf() {
- assertMapEquals(ImmutableSortedMap.of("one", 1), "one", 1);
- assertMapEquals(ImmutableSortedMap.of("one", 1, "two", 2), "one", 1, "two", 2);
- assertMapEquals(
- ImmutableSortedMap.of("one", 1, "two", 2, "three", 3), "one", 1, "three", 3, "two", 2);
- assertMapEquals(
- ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4),
- "four",
- 4,
- "one",
- 1,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6),
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7),
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8),
- "eight",
- 8,
- "five",
- 5,
- "four",
- 4,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9),
- "eight",
- 8,
- "five",
- 5,
- "four",
- 4,
- "nine",
- 9,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "three",
- 3,
- "two",
- 2);
- assertMapEquals(
- ImmutableSortedMap.of(
- "one", 1,
- "two", 2,
- "three", 3,
- "four", 4,
- "five", 5,
- "six", 6,
- "seven", 7,
- "eight", 8,
- "nine", 9,
- "ten", 10),
- "eight",
- 8,
- "five",
- 5,
- "four",
- 4,
- "nine",
- 9,
- "one",
- 1,
- "seven",
- 7,
- "six",
- 6,
- "ten",
- 10,
- "three",
- 3,
- "two",
- 2);
+ public void testOfWithDuplicateKey() {
+ try {
+ ImmutableSortedMap.of("one", 1, "one", 1);
+ fail();
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testOfNullKey() {
- Integer n = null;
- try {
- ImmutableSortedMap.of(n, 1);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOfEmptyMap() {
+ ImmutableSortedMap<String, Integer> copy =
+ ImmutableSortedMap.copyOf(Collections.<String, Integer>emptyMap());
+ assertEquals(Collections.<String, Integer>emptyMap(), copy);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- try {
- ImmutableSortedMap.of("one", 1, null, 2);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ public void testCopyOfSingletonMap() {
+ ImmutableSortedMap<String, Integer> copy =
+ ImmutableSortedMap.copyOf(Collections.singletonMap("one", 1));
+ assertMapEquals(copy, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- public void testOfNullValue() {
- try {
- ImmutableSortedMap.of("one", null);
- fail();
- } catch (NullPointerException expected) {
- }
+ public void testCopyOf() {
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- try {
- ImmutableSortedMap.of("one", 1, "two", null);
- fail();
- } catch (NullPointerException expected) {
- }
- }
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original);
+ assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- public void testOfWithDuplicateKey() {
- try {
- ImmutableSortedMap.of("one", 1, "one", 1);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
+ public void testCopyOfExplicitComparator() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ Map<String, Integer> original = new LinkedHashMap<>();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
+
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
+ assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
+ assertSame(comparator, copy.comparator());
+ }
- public void testCopyOfEmptyMap() {
- ImmutableSortedMap<String, Integer> copy =
- ImmutableSortedMap.copyOf(Collections.<String, Integer>emptyMap());
- assertEquals(Collections.<String, Integer>emptyMap(), copy);
- assertSame(copy, ImmutableSortedMap.copyOf(copy));
- assertSame(Ordering.natural(), copy.comparator());
- }
+ public void testCopyOfImmutableSortedSetDifferentComparator() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ Map<String, Integer> original = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
+ assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
+ assertSame(comparator, copy.comparator());
+ }
- public void testCopyOfSingletonMap() {
- ImmutableSortedMap<String, Integer> copy =
- ImmutableSortedMap.copyOf(Collections.singletonMap("one", 1));
- assertMapEquals(copy, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOf(copy));
- assertSame(Ordering.natural(), copy.comparator());
- }
+ public void testCopyOfSortedNatural() {
+ SortedMap<String, Integer> original = Maps.newTreeMap();
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
- public void testCopyOf() {
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
+ assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
+ assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
+ assertSame(Ordering.natural(), copy.comparator());
+ }
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original);
- assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
- assertSame(copy, ImmutableSortedMap.copyOf(copy));
- assertSame(Ordering.natural(), copy.comparator());
- }
+ public void testCopyOfSortedExplicit() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ SortedMap<String, Integer> original = Maps.newTreeMap(comparator);
+ original.put("one", 1);
+ original.put("two", 2);
+ original.put("three", 3);
+
+ ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
+ assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
+ assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
+ assertSame(comparator, copy.comparator());
+ }
- public void testCopyOfExplicitComparator() {
- Comparator<String> comparator = Ordering.natural().reverse();
- Map<String, Integer> original = new LinkedHashMap<>();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
-
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
- assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
- assertSame(comparator, copy.comparator());
- }
+ private static class IntegerDiv10 implements Comparable<IntegerDiv10> {
+ final int value;
- public void testCopyOfImmutableSortedSetDifferentComparator() {
- Comparator<String> comparator = Ordering.natural().reverse();
- Map<String, Integer> original = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOf(original, comparator);
- assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOf(copy, comparator));
- assertSame(comparator, copy.comparator());
+ IntegerDiv10(int value) {
+ this.value = value;
}
- public void testCopyOfSortedNatural() {
- SortedMap<String, Integer> original = Maps.newTreeMap();
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
-
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
- assertMapEquals(copy, "one", 1, "three", 3, "two", 2);
- assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
- assertSame(Ordering.natural(), copy.comparator());
+ @Override
+ public int compareTo(IntegerDiv10 o) {
+ return value / 10 - o.value / 10;
}
- public void testCopyOfSortedExplicit() {
- Comparator<String> comparator = Ordering.natural().reverse();
- SortedMap<String, Integer> original = Maps.newTreeMap(comparator);
- original.put("one", 1);
- original.put("two", 2);
- original.put("three", 3);
-
- ImmutableSortedMap<String, Integer> copy = ImmutableSortedMap.copyOfSorted(original);
- assertMapEquals(copy, "two", 2, "three", 3, "one", 1);
- assertSame(copy, ImmutableSortedMap.copyOfSorted(copy));
- assertSame(comparator, copy.comparator());
+ @Override
+ public String toString() {
+ return Integer.toString(value);
}
+ }
- private static class IntegerDiv10 implements Comparable<IntegerDiv10> {
- final int value;
-
- IntegerDiv10(int value) {
- this.value = value;
- }
-
- @Override
- public int compareTo(IntegerDiv10 o) {
- return value / 10 - o.value / 10;
- }
-
- @Override
- public String toString() {
- return Integer.toString(value);
- }
- }
+ public void testCopyOfDuplicateKey() {
+ Map<IntegerDiv10, String> original =
+ ImmutableMap.of(
+ new IntegerDiv10(3), "three",
+ new IntegerDiv10(20), "twenty",
+ new IntegerDiv10(11), "eleven",
+ new IntegerDiv10(35), "thirty five",
+ new IntegerDiv10(12), "twelve");
- public void testCopyOfDuplicateKey() {
- Map<IntegerDiv10, String> original =
- ImmutableMap.of(
- new IntegerDiv10(3), "three",
- new IntegerDiv10(20), "twenty",
- new IntegerDiv10(11), "eleven",
- new IntegerDiv10(35), "thirty five",
- new IntegerDiv10(12), "twelve");
-
- try {
- ImmutableSortedMap.copyOf(original);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
+ try {
+ ImmutableSortedMap.copyOf(original);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testImmutableMapCopyOfImmutableSortedMap() {
- IntegerDiv10 three = new IntegerDiv10(3);
- IntegerDiv10 eleven = new IntegerDiv10(11);
- IntegerDiv10 twelve = new IntegerDiv10(12);
- IntegerDiv10 twenty = new IntegerDiv10(20);
- Map<IntegerDiv10, String> original =
- ImmutableSortedMap.of(three, "three", eleven, "eleven", twenty, "twenty");
- Map<IntegerDiv10, String> copy = ImmutableMap.copyOf(original);
- assertTrue(original.containsKey(twelve));
- assertFalse(copy.containsKey(twelve));
- }
+ public void testImmutableMapCopyOfImmutableSortedMap() {
+ IntegerDiv10 three = new IntegerDiv10(3);
+ IntegerDiv10 eleven = new IntegerDiv10(11);
+ IntegerDiv10 twelve = new IntegerDiv10(12);
+ IntegerDiv10 twenty = new IntegerDiv10(20);
+ Map<IntegerDiv10, String> original =
+ ImmutableSortedMap.of(three, "three", eleven, "eleven", twenty, "twenty");
+ Map<IntegerDiv10, String> copy = ImmutableMap.copyOf(original);
+ assertTrue(original.containsKey(twelve));
+ assertFalse(copy.containsKey(twelve));
+ }
- public void testBuilderReverseOrder() {
- ImmutableSortedMap<String, Integer> map =
- ImmutableSortedMap.<String, Integer>reverseOrder()
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
- assertEquals(Ordering.natural().reverse(), map.comparator());
- }
+ public void testBuilderReverseOrder() {
+ ImmutableSortedMap<String, Integer> map =
+ ImmutableSortedMap.<String, Integer>reverseOrder()
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
+ assertEquals(Ordering.natural().reverse(), map.comparator());
+ }
- public void testBuilderComparator() {
- Comparator<String> comparator = Ordering.natural().reverse();
- ImmutableSortedMap<String, Integer> map =
- new ImmutableSortedMap.Builder<String, Integer>(comparator)
- .put("one", 1)
- .put("two", 2)
- .put("three", 3)
- .put("four", 4)
- .put("five", 5)
- .build();
- assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
- assertSame(comparator, map.comparator());
- }
+ public void testBuilderComparator() {
+ Comparator<String> comparator = Ordering.natural().reverse();
+ ImmutableSortedMap<String, Integer> map =
+ new ImmutableSortedMap.Builder<String, Integer>(comparator)
+ .put("one", 1)
+ .put("two", 2)
+ .put("three", 3)
+ .put("four", 4)
+ .put("five", 5)
+ .build();
+ assertMapEquals(map, "two", 2, "three", 3, "one", 1, "four", 4, "five", 5);
+ assertSame(comparator, map.comparator());
+ }
- public void testToImmutableSortedMap() {
- Collector<Entry<String, Integer>, ?, ImmutableSortedMap<String, Integer>> collector =
- ImmutableSortedMap.toImmutableSortedMap(
- String.CASE_INSENSITIVE_ORDER, Entry::getKey, Entry::getValue);
- BiPredicate<ImmutableSortedMap<String, Integer>, ImmutableSortedMap<String, Integer>>
- equivalence =
- Equivalence.equals()
- .onResultOf(ImmutableSortedMap<String, Integer>::comparator)
- .and(Equivalence.equals().onResultOf(map -> map.entrySet().asList()))
- .and(Equivalence.equals());
- ImmutableSortedMap<String, Integer> expected =
- ImmutableSortedMap.<String, Integer>orderedBy(String.CASE_INSENSITIVE_ORDER)
- .put("one", 1)
- .put("three", 3)
- .put("two", 2)
- .build();
- CollectorTester.of(collector, equivalence)
- .expectCollects(expected, mapEntry("one", 1), mapEntry("two", 2), mapEntry("three", 3));
- }
+ public void testToImmutableSortedMap() {
+ Collector<Entry<String, Integer>, ?, ImmutableSortedMap<String, Integer>> collector =
+ ImmutableSortedMap.toImmutableSortedMap(
+ String.CASE_INSENSITIVE_ORDER, Entry::getKey, Entry::getValue);
+ BiPredicate<ImmutableSortedMap<String, Integer>, ImmutableSortedMap<String, Integer>>
+ equivalence =
+ Equivalence.equals()
+ .onResultOf(ImmutableSortedMap<String, Integer>::comparator)
+ .and(Equivalence.equals().onResultOf(map -> map.entrySet().asList()))
+ .and(Equivalence.equals());
+ ImmutableSortedMap<String, Integer> expected =
+ ImmutableSortedMap.<String, Integer>orderedBy(String.CASE_INSENSITIVE_ORDER)
+ .put("one", 1)
+ .put("three", 3)
+ .put("two", 2)
+ .build();
+ CollectorTester.of(collector, equivalence)
+ .expectCollects(expected, mapEntry("one", 1), mapEntry("two", 2), mapEntry("three", 3));
+ }
- public void testToImmutableSortedMap_exceptionOnDuplicateKey() {
- Collector<Entry<String, Integer>, ?, ImmutableSortedMap<String, Integer>> collector =
- ImmutableSortedMap.toImmutableSortedMap(
- Ordering.natural(), Entry::getKey, Entry::getValue);
- try {
- Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException expected) {
- }
+ public void testToImmutableSortedMap_exceptionOnDuplicateKey() {
+ Collector<Entry<String, Integer>, ?, ImmutableSortedMap<String, Integer>> collector =
+ ImmutableSortedMap.toImmutableSortedMap(Ordering.natural(), Entry::getKey, Entry::getValue);
+ try {
+ Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector);
+ fail("Expected IllegalArgumentException");
+ } catch (IllegalArgumentException expected) {
}
+ }
- public void testToImmutableSortedMapMerging() {
- Collector<Entry<String, Integer>, ?, ImmutableSortedMap<String, Integer>> collector =
- ImmutableSortedMap.toImmutableSortedMap(
- Comparator.naturalOrder(), Entry::getKey, Entry::getValue, Integer::sum);
- Equivalence<ImmutableMap<String, Integer>> equivalence =
- Equivalence.equals()
- .<Entry<String, Integer>>pairwise()
- .onResultOf(ImmutableMap::entrySet);
- CollectorTester.of(collector, equivalence)
- .expectCollects(
- ImmutableSortedMap.of("one", 1, "three", 3, "two", 4),
- mapEntry("one", 1),
- mapEntry("two", 2),
- mapEntry("three", 3),
- mapEntry("two", 2));
- }
+ public void testToImmutableSortedMapMerging() {
+ Collector<Entry<String, Integer>, ?, ImmutableSortedMap<String, Integer>> collector =
+ ImmutableSortedMap.toImmutableSortedMap(
+ Comparator.naturalOrder(), Entry::getKey, Entry::getValue, Integer::sum);
+ Equivalence<ImmutableMap<String, Integer>> equivalence =
+ Equivalence.equals().<Entry<String, Integer>>pairwise().onResultOf(ImmutableMap::entrySet);
+ CollectorTester.of(collector, equivalence)
+ .expectCollects(
+ ImmutableSortedMap.of("one", 1, "three", 3, "two", 4),
+ mapEntry("one", 1),
+ mapEntry("two", 2),
+ mapEntry("three", 3),
+ mapEntry("two", 2));
}
+ // Other tests
+
public void testNullGet() {
ImmutableSortedMap<String, Integer> map = ImmutableSortedMap.of("one", 1);
assertNull(map.get(null));
@@ -920,7 +744,7 @@ public class ImmutableSortedMapTest extends TestCase {
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof IntHolder) && ((IntHolder) o).value == value;
}
diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java
index b4cd891b2..9ab3bb867 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java
@@ -52,6 +52,7 @@ import java.util.function.BiPredicate;
import java.util.stream.Collector;
import junit.framework.Test;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link ImmutableSortedSet}.
@@ -754,7 +755,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest {
return Integer.compare(a, o.a);
}
- public boolean fullEquals(TypeWithDuplicates other) {
+ public boolean fullEquals(@Nullable TypeWithDuplicates other) {
return other != null && a == other.a && b == other.b;
}
}
@@ -1006,7 +1007,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest {
assertTrue(copy instanceof ImmutableSortedAsList);
}
- public void testAsListInconsistentComprator() {
+ public void testAsListInconsistentComparator() {
ImmutableSet<String> set =
ImmutableSortedSet.orderedBy(STRING_LENGTH)
.add("in", "the", "quick", "jumped", "over", "a")
diff --git a/guava-tests/test/com/google/common/collect/ImmutableTableTest.java b/guava-tests/test/com/google/common/collect/ImmutableTableTest.java
index d48938cca..9362a6b20 100644
--- a/guava-tests/test/com/google/common/collect/ImmutableTableTest.java
+++ b/guava-tests/test/com/google/common/collect/ImmutableTableTest.java
@@ -485,4 +485,33 @@ public class ImmutableTableTest extends AbstractTableReadTest {
}
assertTrue(builder.build() instanceof SparseImmutableTable);
}
+
+ @GwtIncompatible // NullPointerTester
+ @Override
+ public void testNullPointerInstance() {
+ if (isAndroid()) {
+ /*
+ * NPT fails under the old versions of Android we test under because it performs reflection on
+ * ImmutableTable, which declares static methods that refer to Collector, which is unavailable
+ * under such versions.
+ *
+ * We use a runtime check here instead of @AndroidIncompatible: @AndroidIncompatible operates
+ * by stripping annotated methods entirely, and if we strip this method, then JUnit would just
+ * run the supermethod as usual.
+ *
+ * TODO: b/292578973: Use @AndroidIncompatible if we change our system to keep the methods in
+ * place but to have the test runner skip them. However, note that if we choose to *both*
+ * strip the methods *and* have the test runner not run them (for some unusual cases in which
+ * we don't run the stripping test for technical reasons), then we'd be back to the problem
+ * described above, since the supermethod is *not* annotated @AndroidIncompatible (since it
+ * works fine with the other Table implementations).
+ */
+ return;
+ }
+ super.testNullPointerInstance();
+ }
+
+ private static boolean isAndroid() {
+ return System.getProperty("java.runtime.name", "").contains("Android");
+ }
}
diff --git a/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java b/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java
new file mode 100644
index 000000000..9cd2d9091
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/IterablesFilterArrayListTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredIterableTest;
+
+public final class IterablesFilterArrayListTest
+ extends AbstractFilteredIterableTest<Iterable<Integer>> {
+ @Override
+ Iterable<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Lists.newArrayList(contents);
+ }
+
+ @Override
+ Iterable<Integer> filter(Iterable<Integer> elements, Predicate<? super Integer> predicate) {
+ return Iterables.filter(elements, predicate);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/LegacyComparable.java b/guava-tests/test/com/google/common/collect/LegacyComparable.java
index 8b0c9620c..05a6607a4 100644
--- a/guava-tests/test/com/google/common/collect/LegacyComparable.java
+++ b/guava-tests/test/com/google/common/collect/LegacyComparable.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Arrays;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A class that implements {@code Comparable} without generics, such as those found in libraries
@@ -51,7 +52,7 @@ class LegacyComparable implements Comparable, Serializable {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
if (object instanceof LegacyComparable) {
LegacyComparable that = (LegacyComparable) object;
return this.value.equals(that.value);
diff --git a/guava-tests/test/com/google/common/collect/ListsImplTest.java b/guava-tests/test/com/google/common/collect/ListsImplTest.java
index 1569ba5ab..237bcc2c9 100644
--- a/guava-tests/test/com/google/common/collect/ListsImplTest.java
+++ b/guava-tests/test/com/google/common/collect/ListsImplTest.java
@@ -64,7 +64,7 @@ public class ListsImplTest extends TestCase {
/** Creates a new list with the given contents. */
public abstract <T> List<T> createList(Class<T> listType, Collection<? extends T> contents);
- /** The modifiablity of this list example. */
+ /** The modifiability of this list example. */
public Modifiability modifiability() {
return modifiability;
}
diff --git a/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java b/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java
index 47fc74c82..453e3e74d 100644
--- a/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java
+++ b/guava-tests/test/com/google/common/collect/MapMakerInternalMapTest.java
@@ -90,7 +90,7 @@ public class MapMakerInternalMapTest extends TestCase {
}
public void testSetConcurrencyLevel() {
- // round up to nearest power of two
+ // round up to the nearest power of two
checkConcurrencyLevel(1, 1);
checkConcurrencyLevel(2, 2);
@@ -109,7 +109,7 @@ public class MapMakerInternalMapTest extends TestCase {
}
public void testSetInitialCapacity() {
- // share capacity over each segment, then round up to nearest power of two
+ // share capacity over each segment, then round up to the nearest power of two
checkInitialCapacity(1, 0, 1);
checkInitialCapacity(1, 1, 1);
@@ -152,42 +152,6 @@ public class MapMakerInternalMapTest extends TestCase {
}
}
- public void testSetMaximumSize() {
- // vary maximumSize wrt concurrencyLevel
-
- for (int maxSize = 1; maxSize < 8; maxSize++) {
- checkMaximumSize(1, 8, maxSize);
- checkMaximumSize(2, 8, maxSize);
- checkMaximumSize(4, 8, maxSize);
- checkMaximumSize(8, 8, maxSize);
- }
-
- checkMaximumSize(1, 8, Integer.MAX_VALUE);
- checkMaximumSize(2, 8, Integer.MAX_VALUE);
- checkMaximumSize(4, 8, Integer.MAX_VALUE);
- checkMaximumSize(8, 8, Integer.MAX_VALUE);
-
- // vary initial capacity wrt maximumSize
-
- for (int capacity = 0; capacity < 8; capacity++) {
- checkMaximumSize(1, capacity, 4);
- checkMaximumSize(2, capacity, 4);
- checkMaximumSize(4, capacity, 4);
- checkMaximumSize(8, capacity, 4);
- }
- }
-
- private static void checkMaximumSize(int concurrencyLevel, int initialCapacity, int maxSize) {
- MapMakerInternalMap<Object, Object, ?, ?> map =
- makeMap(
- createMapMaker().concurrencyLevel(concurrencyLevel).initialCapacity(initialCapacity));
- int totalCapacity = 0;
- for (int i = 0; i < map.segments.length; i++) {
- totalCapacity += map.segments[i].maxSegmentSize;
- }
- assertTrue("totalCapcity=" + totalCapacity + ", maxSize=" + maxSize, totalCapacity <= maxSize);
- }
-
public void testSetWeakKeys() {
MapMakerInternalMap<Object, Object, ?, ?> map = makeMap(createMapMaker().weakKeys());
checkStrength(map, Strength.WEAK, Strength.STRONG);
diff --git a/guava-tests/test/com/google/common/collect/MapMakerTest.java b/guava-tests/test/com/google/common/collect/MapMakerTest.java
index 9669ded7c..5e93001c7 100644
--- a/guava-tests/test/com/google/common/collect/MapMakerTest.java
+++ b/guava-tests/test/com/google/common/collect/MapMakerTest.java
@@ -30,7 +30,6 @@ import junit.framework.TestCase;
/** @author Charles Fry */
@GwtCompatible(emulated = true)
public class MapMakerTest extends TestCase {
-
@GwtIncompatible // NullPointerTester
public void testNullParameters() throws Exception {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/collect/MapsTest.java b/guava-tests/test/com/google/common/collect/MapsTest.java
index 50df8cc5f..6c4800550 100644
--- a/guava-tests/test/com/google/common/collect/MapsTest.java
+++ b/guava-tests/test/com/google/common/collect/MapsTest.java
@@ -31,7 +31,6 @@ import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
import com.google.common.collect.Maps.EntryTransformer;
import com.google.common.collect.Maps.ValueDifferenceImpl;
import com.google.common.collect.SetsTest.Derived;
@@ -63,6 +62,7 @@ import java.util.SortedSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@code Maps}.
@@ -126,7 +126,10 @@ public class MapsTest extends TestCase {
for (int size = 1; size < 200; size++) {
assertWontGrow(
- size, Maps.newHashMapWithExpectedSize(size), Maps.newHashMapWithExpectedSize(size));
+ size,
+ new HashMap<>(),
+ Maps.newHashMapWithExpectedSize(size),
+ Maps.newHashMapWithExpectedSize(size));
}
}
@@ -139,6 +142,7 @@ public class MapsTest extends TestCase {
for (int size = 1; size < 200; size++) {
assertWontGrow(
size,
+ new LinkedHashMap<>(),
Maps.newLinkedHashMapWithExpectedSize(size),
Maps.newLinkedHashMapWithExpectedSize(size));
}
@@ -146,7 +150,11 @@ public class MapsTest extends TestCase {
@GwtIncompatible // reflection
private static void assertWontGrow(
- int size, HashMap<Object, Object> map1, HashMap<Object, Object> map2) throws Exception {
+ int size,
+ HashMap<Object, Object> referenceMap,
+ HashMap<Object, Object> map1,
+ HashMap<Object, Object> map2)
+ throws Exception {
// Only start measuring table size after the first element inserted, to
// deal with empty-map optimization.
map1.put(0, null);
@@ -168,6 +176,16 @@ public class MapsTest extends TestCase {
assertWithMessage("table size after adding " + size + " elements")
.that(bucketsOf(map1))
.isEqualTo(initialBuckets);
+
+ // Ensure that referenceMap, which doesn't use WithExpectedSize, ends up with the same table
+ // size as the other two maps. If it ended up with a smaller size that would imply that we
+ // computed the wrong initial capacity.
+ for (int i = 0; i < size; i++) {
+ referenceMap.put(i, null);
+ }
+ assertWithMessage("table size after adding " + size + " elements")
+ .that(initialBuckets)
+ .isAtMost(bucketsOf(referenceMap));
}
@GwtIncompatible // reflection
@@ -1353,23 +1371,23 @@ public class MapsTest extends TestCase {
assertEquals(ImmutableSet.of(1, 2, 3), sync.inverse().keySet());
}
- private static final Predicate<String> NOT_LENGTH_3 =
- new Predicate<String>() {
+ static final Predicate<@Nullable String> NOT_LENGTH_3 =
+ new Predicate<@Nullable String>() {
@Override
- public boolean apply(String input) {
+ public boolean apply(@Nullable String input) {
return input == null || input.length() != 3;
}
};
- private static final Predicate<Integer> EVEN =
- new Predicate<Integer>() {
+ static final Predicate<@Nullable Integer> EVEN =
+ new Predicate<@Nullable Integer>() {
@Override
- public boolean apply(Integer input) {
+ public boolean apply(@Nullable Integer input) {
return input == null || input % 2 == 0;
}
};
- private static final Predicate<Entry<String, Integer>> CORRECT_LENGTH =
+ static final Predicate<Entry<String, Integer>> CORRECT_LENGTH =
new Predicate<Entry<String, Integer>>() {
@Override
public boolean apply(Entry<String, Integer> input) {
@@ -1377,7 +1395,7 @@ public class MapsTest extends TestCase {
}
};
- private static final Function<Integer, Double> SQRT_FUNCTION =
+ static final Function<Integer, Double> SQRT_FUNCTION =
new Function<Integer, Double>() {
@Override
public Double apply(Integer in) {
@@ -1385,233 +1403,6 @@ public class MapsTest extends TestCase {
}
};
- public static class FilteredMapTest extends TestCase {
- Map<String, Integer> createUnfiltered() {
- return Maps.newHashMap();
- }
-
- public void testFilteredKeysIllegalPut() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
- filtered.put("a", 1);
- filtered.put("b", 2);
- assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
-
- try {
- filtered.put("yyy", 3);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- }
-
- public void testFilteredKeysIllegalPutAll() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
- filtered.put("a", 1);
- filtered.put("b", 2);
- assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
-
- try {
- filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5));
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
- }
-
- public void testFilteredKeysFilteredReflectsBackingChanges() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
- unfiltered.put("two", 2);
- unfiltered.put("three", 3);
- unfiltered.put("four", 4);
- assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered);
- assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered);
-
- unfiltered.remove("three");
- assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered);
- assertEquals(ImmutableMap.of("four", 4), filtered);
-
- unfiltered.clear();
- assertEquals(ImmutableMap.of(), unfiltered);
- assertEquals(ImmutableMap.of(), filtered);
- }
-
- public void testFilteredValuesIllegalPut() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- filtered.put("a", 2);
- unfiltered.put("b", 4);
- unfiltered.put("c", 5);
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
-
- try {
- filtered.put("yyy", 3);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
- }
-
- public void testFilteredValuesIllegalPutAll() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- filtered.put("a", 2);
- unfiltered.put("b", 4);
- unfiltered.put("c", 5);
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
-
- try {
- filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6));
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
- }
-
- public void testFilteredValuesIllegalSetValue() {
- Map<String, Integer> unfiltered = createUnfiltered();
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- filtered.put("a", 2);
- filtered.put("b", 4);
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
-
- Entry<String, Integer> entry = filtered.entrySet().iterator().next();
- try {
- entry.setValue(5);
- fail();
- } catch (IllegalArgumentException expected) {
- }
-
- assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered);
- }
-
- public void testFilteredValuesClear() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("one", 1);
- unfiltered.put("two", 2);
- unfiltered.put("three", 3);
- unfiltered.put("four", 4);
- Map<String, Integer> filtered = Maps.filterValues(unfiltered, EVEN);
- assertEquals(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), unfiltered);
- assertEquals(ImmutableMap.of("two", 2, "four", 4), filtered);
-
- filtered.clear();
- assertEquals(ImmutableMap.of("one", 1, "three", 3), unfiltered);
- assertTrue(filtered.isEmpty());
- }
-
- public void testFilteredEntriesIllegalPut() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
-
- filtered.put("chicken", 7);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
-
- try {
- filtered.put("cow", 7);
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
- }
-
- public void testFilteredEntriesIllegalPutAll() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5), filtered);
-
- filtered.put("chicken", 7);
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
-
- try {
- filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7));
- fail();
- } catch (IllegalArgumentException expected) {
- }
- assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered);
- }
-
- public void testFilteredEntriesObjectPredicate() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Predicate<Object> predicate = Predicates.alwaysFalse();
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
- assertTrue(filtered.isEmpty());
- }
-
- public void testFilteredEntriesWildCardEntryPredicate() {
- Map<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 2);
- unfiltered.put("horse", 5);
- Predicate<Entry<?, ?>> predicate =
- new Predicate<Entry<?, ?>>() {
- @Override
- public boolean apply(Entry<?, ?> input) {
- return "cat".equals(input.getKey()) || Integer.valueOf(2) == input.getValue();
- }
- };
- Map<String, Integer> filtered = Maps.filterEntries(unfiltered, predicate);
- assertEquals(ImmutableMap.of("cat", 3, "dog", 2), filtered);
- }
- }
-
- public static class FilteredSortedMapTest extends FilteredMapTest {
- @Override
- SortedMap<String, Integer> createUnfiltered() {
- return Maps.newTreeMap();
- }
-
- public void testFirstAndLastKeyFilteredMap() {
- SortedMap<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("apple", 2);
- unfiltered.put("banana", 6);
- unfiltered.put("cat", 3);
- unfiltered.put("dog", 5);
-
- SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
- assertEquals("banana", filtered.firstKey());
- assertEquals("cat", filtered.lastKey());
- }
-
- public void testHeadSubTailMap_FilteredMap() {
- SortedMap<String, Integer> unfiltered = createUnfiltered();
- unfiltered.put("apple", 2);
- unfiltered.put("banana", 6);
- unfiltered.put("cat", 4);
- unfiltered.put("dog", 3);
- SortedMap<String, Integer> filtered = Maps.filterEntries(unfiltered, CORRECT_LENGTH);
-
- assertEquals(ImmutableMap.of("banana", 6), filtered.headMap("dog"));
- assertEquals(ImmutableMap.of(), filtered.headMap("banana"));
- assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.headMap("emu"));
-
- assertEquals(ImmutableMap.of("banana", 6), filtered.subMap("banana", "dog"));
- assertEquals(ImmutableMap.of("dog", 3), filtered.subMap("cat", "emu"));
-
- assertEquals(ImmutableMap.of("dog", 3), filtered.tailMap("cat"));
- assertEquals(ImmutableMap.of("banana", 6, "dog", 3), filtered.tailMap("banana"));
- }
- }
-
- public static class FilteredBiMapTest extends FilteredMapTest {
- @Override
- BiMap<String, Integer> createUnfiltered() {
- return HashBiMap.create();
- }
- }
-
public void testTransformValues() {
Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
Map<String, Double> transformed = transformValues(map, SQRT_FUNCTION);
diff --git a/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java b/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java
index c20e16616..e35aa3647 100644
--- a/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java
+++ b/guava-tests/test/com/google/common/collect/MapsTransformValuesTest.java
@@ -265,22 +265,22 @@ public class MapsTransformValuesTest extends MapInterfaceTest<String, String> {
}
public void testTransformEntrySetContains() {
- Map<String, Boolean> underlying = Maps.newHashMap();
+ Map<@Nullable String, @Nullable Boolean> underlying = Maps.newHashMap();
underlying.put("a", null);
underlying.put("b", true);
underlying.put(null, true);
- Map<String, Boolean> map =
+ Map<@Nullable String, @Nullable Boolean> map =
Maps.transformValues(
underlying,
- new Function<Boolean, Boolean>() {
+ new Function<@Nullable Boolean, @Nullable Boolean>() {
@Override
- public Boolean apply(@Nullable Boolean from) {
+ public @Nullable Boolean apply(@Nullable Boolean from) {
return (from == null) ? true : null;
}
});
- Set<Entry<String, Boolean>> entries = map.entrySet();
+ Set<Entry<@Nullable String, @Nullable Boolean>> entries = map.entrySet();
assertTrue(entries.contains(Maps.immutableEntry("a", true)));
assertTrue(entries.contains(Maps.immutableEntry("b", (Boolean) null)));
assertTrue(entries.contains(Maps.immutableEntry((String) null, (Boolean) null)));
diff --git a/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java b/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
index 271b3b31d..7411beca4 100644
--- a/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
+++ b/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
@@ -340,22 +340,22 @@ public class MapsTransformValuesUnmodifiableIteratorTest extends MapInterfaceTes
}
public void testTransformEntrySetContains() {
- Map<String, Boolean> underlying = Maps.newHashMap();
+ Map<@Nullable String, @Nullable Boolean> underlying = Maps.newHashMap();
underlying.put("a", null);
underlying.put("b", true);
underlying.put(null, true);
- Map<String, Boolean> map =
+ Map<@Nullable String, @Nullable Boolean> map =
Maps.transformValues(
underlying,
- new Function<Boolean, Boolean>() {
+ new Function<@Nullable Boolean, @Nullable Boolean>() {
@Override
- public Boolean apply(@Nullable Boolean from) {
+ public @Nullable Boolean apply(@Nullable Boolean from) {
return (from == null) ? true : null;
}
});
- Set<Entry<String, Boolean>> entries = map.entrySet();
+ Set<Entry<@Nullable String, @Nullable Boolean>> entries = map.entrySet();
assertTrue(entries.contains(Maps.immutableEntry("a", true)));
assertTrue(entries.contains(Maps.immutableEntry("b", (Boolean) null)));
assertTrue(entries.contains(Maps.immutableEntry((String) null, (Boolean) null)));
diff --git a/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java b/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
index 5471e3609..9a39e192d 100644
--- a/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
+++ b/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
@@ -276,7 +276,7 @@ public class MinMaxPriorityQueueTest extends TestCase {
public void testRemove() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(1, 2, 3, 4, 47, 1, 5, 3, 0));
- assertTrue("Heap is not intact initally", mmHeap.isIntact());
+ assertTrue("Heap is not intact initially", mmHeap.isIntact());
assertEquals(9, mmHeap.size());
mmHeap.remove(5);
assertEquals(8, mmHeap.size());
diff --git a/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java b/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java
index bef27b9b2..870490e5f 100644
--- a/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java
+++ b/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset.Entry;
import java.util.Collections;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Multisets#immutableEntry}.
@@ -28,7 +29,7 @@ import junit.framework.TestCase;
*/
@GwtCompatible
public class MultisetsImmutableEntryTest extends TestCase {
- private static final String NE = null;
+ private static final @Nullable String NE = null;
private static <E> Entry<E> entry(final E element, final int count) {
return Multisets.immutableEntry(element, count);
diff --git a/guava-tests/test/com/google/common/collect/OrderingTest.java b/guava-tests/test/com/google/common/collect/OrderingTest.java
index 36b63d8d9..a98379986 100644
--- a/guava-tests/test/com/google/common/collect/OrderingTest.java
+++ b/guava-tests/test/com/google/common/collect/OrderingTest.java
@@ -833,7 +833,7 @@ public class OrderingTest extends TestCase {
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
return other instanceof NumberOrdering;
}
diff --git a/guava-tests/test/com/google/common/collect/QueuesTest.java b/guava-tests/test/com/google/common/collect/QueuesTest.java
index ba5f4f0a2..e2c3485f9 100644
--- a/guava-tests/test/com/google/common/collect/QueuesTest.java
+++ b/guava-tests/test/com/google/common/collect/QueuesTest.java
@@ -40,13 +40,13 @@ import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Queues}.
*
* @author Dimitris Andreou
*/
-
public class QueuesTest extends TestCase {
/*
* All the following tests relate to BlockingQueue methods in Queues.
@@ -221,9 +221,9 @@ public class QueuesTest extends TestCase {
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError =
threadPool.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws InterruptedException {
+ public @Nullable Void call() throws InterruptedException {
new Producer(q, 50).call();
new Interrupter(mainThread).run();
new Producer(q, 50).call();
@@ -304,7 +304,7 @@ public class QueuesTest extends TestCase {
}
}
- private static class Producer implements Callable<Void> {
+ private static class Producer implements Callable<@Nullable Void> {
final BlockingQueue<Object> q;
final int elements;
final CountDownLatch beganProducing = new CountDownLatch(1);
@@ -316,7 +316,7 @@ public class QueuesTest extends TestCase {
}
@Override
- public Void call() throws InterruptedException {
+ public @Nullable Void call() throws InterruptedException {
try {
beganProducing.countDown();
for (int i = 0; i < elements; i++) {
diff --git a/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..4035d6955
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/RegularImmutableMapMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class RegularImmutableMapMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makeEmptyMap() {
+ return ImmutableMap.of();
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableMap.of("one", 1, "two", 2, "three", 3);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java
new file mode 100644
index 000000000..5bbf247b8
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/RegularImmutableMapWithUnhashableValuesMapInterfaceTest.java
@@ -0,0 +1,47 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.testing.SampleElements.Unhashables;
+import com.google.common.collect.testing.UnhashableObject;
+import java.util.Map;
+
+@GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
+public class RegularImmutableMapWithUnhashableValuesMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<Integer, UnhashableObject> {
+ @Override
+ protected Map<Integer, UnhashableObject> makeEmptyMap() {
+ return ImmutableMap.of();
+ }
+
+ @Override
+ protected Map<Integer, UnhashableObject> makePopulatedMap() {
+ Unhashables unhashables = new Unhashables();
+ return ImmutableMap.of(0, unhashables.e0(), 1, unhashables.e1(), 2, unhashables.e2());
+ }
+
+ @Override
+ protected Integer getKeyNotInPopulatedMap() {
+ return 3;
+ }
+
+ @Override
+ protected UnhashableObject getValueNotInPopulatedMap() {
+ return new Unhashables().e3();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..d825eac5e
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/RegularImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class RegularImmutableSortedMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makeEmptyMap() {
+ return ImmutableSortedMap.of();
+ }
+
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("one", 1, "two", 2, "three", 3);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..6eef9f30b
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ReserializedImmutableMapMapInterfaceTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.testing.SerializableTester;
+import java.util.Map;
+
+@GwtIncompatible // SerializableTester
+public class ReserializedImmutableMapMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return SerializableTester.reserialize(ImmutableMap.of("one", 1, "two", 2, "three", 3));
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..1011cfef3
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/ReserializedImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2009 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.GwtIncompatible;
+import com.google.common.testing.SerializableTester;
+import java.util.SortedMap;
+
+@GwtIncompatible // SerializableTester
+public class ReserializedImmutableSortedMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return SerializableTester.reserialize(ImmutableSortedMap.of("one", 1, "two", 2, "three", 3));
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java b/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java
new file mode 100644
index 000000000..a550f0487
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/SetsFilterHashSetTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredSetTest;
+import java.util.Set;
+
+public final class SetsFilterHashSetTest extends AbstractFilteredSetTest<Set<Integer>> {
+ @Override
+ Set<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Sets.newHashSet(contents);
+ }
+
+ @Override
+ Set<Integer> filter(Set<Integer> elements, Predicate<? super Integer> predicate) {
+ return Sets.filter(elements, predicate);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java b/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java
new file mode 100644
index 000000000..350c09150
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/SetsFilterNavigableSetTest.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredNavigableSetTest;
+import java.util.NavigableSet;
+
+public final class SetsFilterNavigableSetTest extends AbstractFilteredNavigableSetTest {
+ @Override
+ NavigableSet<Integer> createUnfiltered(Iterable<Integer> contents) {
+ return Sets.newTreeSet(contents);
+ }
+
+ @Override
+ NavigableSet<Integer> filter(
+ NavigableSet<Integer> elements, Predicate<? super Integer> predicate) {
+ return Sets.filter(elements, predicate);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java b/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java
new file mode 100644
index 000000000..0529bead6
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/SetsFilterSortedSetTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2012 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.base.Predicate;
+import com.google.common.collect.FilteredCollectionsTestUtil.AbstractFilteredSortedSetTest;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+public final class SetsFilterSortedSetTest
+ extends AbstractFilteredSortedSetTest<SortedSet<Integer>> {
+ @Override
+ SortedSet<Integer> createUnfiltered(Iterable<Integer> contents) {
+ final TreeSet<Integer> result = Sets.newTreeSet(contents);
+ // we have to make the result not Navigable
+ return new ForwardingSortedSet<Integer>() {
+ @Override
+ protected SortedSet<Integer> delegate() {
+ return result;
+ }
+ };
+ }
+
+ @Override
+ SortedSet<Integer> filter(SortedSet<Integer> elements, Predicate<? super Integer> predicate) {
+ return Sets.filter(elements, predicate);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SetsTest.java b/guava-tests/test/com/google/common/collect/SetsTest.java
index 72131bfc3..50fb456e5 100644
--- a/guava-tests/test/com/google/common/collect/SetsTest.java
+++ b/guava-tests/test/com/google/common/collect/SetsTest.java
@@ -73,6 +73,8 @@ import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.function.BiConsumer;
+import java.util.stream.Collector;
import java.util.stream.Stream;
import junit.framework.Test;
import junit.framework.TestCase;
@@ -354,6 +356,23 @@ public class SetsTest extends TestCase {
assertThat(units).isEmpty();
}
+ public <A> void testToImmutableEnumSetReused() {
+ // An unchecked cast lets us refer to the accumulator as an A and invoke the callbacks manually
+ @SuppressWarnings("unchecked")
+ Collector<SomeEnum, A, ImmutableSet<SomeEnum>> collector =
+ (Collector) Sets.<SomeEnum>toImmutableEnumSet();
+ A accumulator = collector.supplier().get();
+ BiConsumer<A, SomeEnum> adder = collector.accumulator();
+ adder.accept(accumulator, SomeEnum.A);
+ adder.accept(accumulator, SomeEnum.B);
+ ImmutableSet<SomeEnum> set = collector.finisher().apply(accumulator);
+ assertThat(set).containsExactly(SomeEnum.A, SomeEnum.B);
+
+ // Subsequent manual manipulation of the accumulator must not affect the state of the built set
+ adder.accept(accumulator, SomeEnum.C);
+ assertThat(set).containsExactly(SomeEnum.A, SomeEnum.B);
+ }
+
@GwtIncompatible // SerializableTester
public void testImmutableEnumSet_serialized() {
Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B);
@@ -590,48 +609,56 @@ public class SetsTest extends TestCase {
verifySetContents(set, SOME_COLLECTION);
}
+ @GwtIncompatible // complementOf
public void testComplementOfEnumSet() {
Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEnumSetWithType() {
Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfRegularSet() {
Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfRegularSetWithType() {
Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D);
EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class);
verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEmptySet() {
Set<SomeEnum> noUnits = Collections.emptySet();
EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits, SomeEnum.class);
verifySetContents(EnumSet.allOf(SomeEnum.class), allUnits);
}
+ @GwtIncompatible // complementOf
public void testComplementOfFullSet() {
Set<SomeEnum> allUnits = Sets.newHashSet(SomeEnum.values());
EnumSet<SomeEnum> noUnits = Sets.complementOf(allUnits, SomeEnum.class);
verifySetContents(noUnits, EnumSet.noneOf(SomeEnum.class));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEmptyEnumSetWithoutType() {
Set<SomeEnum> noUnits = EnumSet.noneOf(SomeEnum.class);
EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits);
verifySetContents(allUnits, EnumSet.allOf(SomeEnum.class));
}
+ @GwtIncompatible // complementOf
public void testComplementOfEmptySetWithoutTypeDoesntWork() {
Set<SomeEnum> set = Collections.emptySet();
try {
@@ -1125,7 +1152,7 @@ public class SetsTest extends TestCase {
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(@Nullable Object other) {
if (other == null) {
return false;
} else if (other instanceof Base) {
diff --git a/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java
new file mode 100644
index 000000000..2a9197d6c
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/SingletonImmutableMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.util.Map;
+
+@GwtCompatible
+public class SingletonImmutableMapMapInterfaceTest
+ extends AbstractImmutableMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ return ImmutableMap.of("one", 1);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java
new file mode 100644
index 000000000..851e5d8c5
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/SingletonImmutableMapWithUnhashableValueMapInterfaceTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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.GwtIncompatible;
+import com.google.common.collect.testing.SampleElements.Unhashables;
+import com.google.common.collect.testing.UnhashableObject;
+import java.util.Map;
+
+@GwtIncompatible // GWT's ImmutableMap emulation is backed by java.util.HashMap.
+public class SingletonImmutableMapWithUnhashableValueMapInterfaceTest
+ extends RegularImmutableMapWithUnhashableValuesMapInterfaceTest {
+ @Override
+ protected Map<Integer, UnhashableObject> makePopulatedMap() {
+ Unhashables unhashables = new Unhashables();
+ return ImmutableMap.of(0, unhashables.e0());
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java
new file mode 100644
index 000000000..4cb7ca5f4
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/SingletonImmutableSortedMapMapInterfaceTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 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.util.SortedMap;
+
+@GwtCompatible
+public class SingletonImmutableSortedMapMapInterfaceTest
+ extends AbstractImmutableSortedMapMapInterfaceTest<String, Integer> {
+ @Override
+ protected SortedMap<String, Integer> makePopulatedMap() {
+ return ImmutableSortedMap.of("one", 1);
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "minus one";
+ }
+
+ @Override
+ protected Integer getValueNotInPopulatedMap() {
+ return -1;
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java b/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java
index 2219ca11b..d0cc8132a 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedBiMapTest.java
@@ -30,6 +30,7 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiFunction;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Synchronized#biMap}.
@@ -112,7 +113,7 @@ public class SynchronizedBiMapTest extends SynchronizedMapTest {
}
@Override
- public V forcePut(K key, V value) {
+ public @Nullable V forcePut(K key, V value) {
assertTrue(Thread.holdsLock(mutex));
return delegate.forcePut(key, value);
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java b/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java
index 1df6aa1bf..09f9c429b 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java
@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Synchronized#deque} and {@link Queues#synchronizedDeque}.
@@ -47,7 +48,7 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E poll() {
+ public @Nullable E poll() {
assertTrue(Thread.holdsLock(mutex));
return delegate.poll();
}
@@ -65,7 +66,7 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E peek() {
+ public @Nullable E peek() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peek();
}
@@ -186,13 +187,13 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E pollFirst() {
+ public @Nullable E pollFirst() {
assertTrue(Thread.holdsLock(mutex));
return delegate.pollFirst();
}
@Override
- public E pollLast() {
+ public @Nullable E pollLast() {
assertTrue(Thread.holdsLock(mutex));
return delegate.pollLast();
}
@@ -210,13 +211,13 @@ public class SynchronizedDequeTest extends TestCase {
}
@Override
- public E peekFirst() {
+ public @Nullable E peekFirst() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peekFirst();
}
@Override
- public E peekLast() {
+ public @Nullable E peekLast() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peekLast();
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java b/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java
index 2e15eda32..1aeae36cc 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedMapTest.java
@@ -28,6 +28,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@code Synchronized#map}.
@@ -71,7 +72,7 @@ public class SynchronizedMapTest extends TestCase {
}
@Override
- public V remove(Object object) {
+ public @Nullable V remove(Object object) {
assertTrue(Thread.holdsLock(mutex));
return super.remove(object);
}
@@ -95,13 +96,13 @@ public class SynchronizedMapTest extends TestCase {
}
@Override
- public V get(Object key) {
+ public @Nullable V get(Object key) {
assertTrue(Thread.holdsLock(mutex));
return super.get(key);
}
@Override
- public V put(K key, V value) {
+ public @Nullable V put(K key, V value) {
assertTrue(Thread.holdsLock(mutex));
return super.put(key, value);
}
@@ -131,7 +132,7 @@ public class SynchronizedMapTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(obj);
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java b/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java
index 41b597aac..ad9fd230d 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java
@@ -33,6 +33,7 @@ import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.SortedMap;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Maps#synchronizedNavigableMap(NavigableMap)}.
@@ -65,7 +66,7 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public boolean equals(Object object) {
+ public boolean equals(@Nullable Object object) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(object);
}
@@ -110,13 +111,13 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> ceilingEntry(K key) {
+ public @Nullable Entry<K, V> ceilingEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceilingEntry(key);
}
@Override
- public K ceilingKey(K key) {
+ public @Nullable K ceilingKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceilingKey(key);
}
@@ -134,19 +135,19 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> firstEntry() {
+ public @Nullable Entry<K, V> firstEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().firstEntry();
}
@Override
- public Entry<K, V> floorEntry(K key) {
+ public @Nullable Entry<K, V> floorEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().floorEntry(key);
}
@Override
- public K floorKey(K key) {
+ public @Nullable K floorKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().floorKey(key);
}
@@ -163,31 +164,31 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> higherEntry(K key) {
+ public @Nullable Entry<K, V> higherEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().higherEntry(key);
}
@Override
- public K higherKey(K key) {
+ public @Nullable K higherKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().higherKey(key);
}
@Override
- public Entry<K, V> lastEntry() {
+ public @Nullable Entry<K, V> lastEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().lastEntry();
}
@Override
- public Entry<K, V> lowerEntry(K key) {
+ public @Nullable Entry<K, V> lowerEntry(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().lowerEntry(key);
}
@Override
- public K lowerKey(K key) {
+ public @Nullable K lowerKey(K key) {
assertTrue(Thread.holdsLock(mutex));
return delegate().lowerKey(key);
}
@@ -199,13 +200,13 @@ public class SynchronizedNavigableMapTest extends SynchronizedMapTest {
}
@Override
- public Entry<K, V> pollFirstEntry() {
+ public @Nullable Entry<K, V> pollFirstEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollFirstEntry();
}
@Override
- public Entry<K, V> pollLastEntry() {
+ public @Nullable Entry<K, V> pollLastEntry() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollLastEntry();
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java b/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java
index c4ee70ce7..93969556a 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java
@@ -32,6 +32,7 @@ import java.util.SortedSet;
import java.util.TreeSet;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Sets#synchronizedNavigableSet(NavigableSet)}.
@@ -51,7 +52,7 @@ public class SynchronizedNavigableSetTest extends TestCase {
static class TestSet<E> extends SynchronizedSetTest.TestSet<E> implements NavigableSet<E> {
- TestSet(NavigableSet<E> delegate, Object mutex) {
+ TestSet(NavigableSet<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@@ -61,7 +62,7 @@ public class SynchronizedNavigableSetTest extends TestCase {
}
@Override
- public E ceiling(E e) {
+ public @Nullable E ceiling(E e) {
assertTrue(Thread.holdsLock(mutex));
return delegate().ceiling(e);
}
@@ -78,7 +79,7 @@ public class SynchronizedNavigableSetTest extends TestCase {
}
@Override
- public E floor(E e) {
+ public @Nullable E floor(E e) {
assertTrue(Thread.holdsLock(mutex));
return delegate().floor(e);
}
@@ -95,24 +96,24 @@ public class SynchronizedNavigableSetTest extends TestCase {
}
@Override
- public E higher(E e) {
+ public @Nullable E higher(E e) {
assertTrue(Thread.holdsLock(mutex));
return delegate().higher(e);
}
@Override
- public E lower(E e) {
+ public @Nullable E lower(E e) {
return delegate().lower(e);
}
@Override
- public E pollFirst() {
+ public @Nullable E pollFirst() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollFirst();
}
@Override
- public E pollLast() {
+ public @Nullable E pollLast() {
assertTrue(Thread.holdsLock(mutex));
return delegate().pollLast();
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java b/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java
index 1e2290d88..e29966367 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedQueueTest.java
@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Synchronized#queue} and {@link Queues#synchronizedQueue}.
@@ -48,7 +49,7 @@ public class SynchronizedQueueTest extends TestCase {
}
@Override
- public E poll() {
+ public @Nullable E poll() {
assertTrue(Thread.holdsLock(mutex));
return delegate.poll();
}
@@ -66,7 +67,7 @@ public class SynchronizedQueueTest extends TestCase {
}
@Override
- public E peek() {
+ public @Nullable E peek() {
assertTrue(Thread.holdsLock(mutex));
return delegate.peek();
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java b/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java
index 313a94f66..9db478cbb 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedSetTest.java
@@ -38,6 +38,9 @@ public class SynchronizedSetTest extends TestCase {
public static final Object MUTEX = new Integer(1); // something Serializable
+ // TODO(cpovirk): Resolve difference between branches in their choice of mutex:
+ // - The mainline uses `null` (even since the change in cl/99720576 was integrated).
+ // - The backport continued to use MUTEX.
public static Test suite() {
return SetTestSuiteBuilder.using(
new TestStringSetGenerator() {
@@ -63,7 +66,7 @@ public class SynchronizedSetTest extends TestCase {
final Set<E> delegate;
public Object mutex;
- public TestSet(Set<E> delegate, Object mutex) {
+ public TestSet(Set<E> delegate, @Nullable Object mutex) {
this.delegate = delegate;
this.mutex = mutex;
}
diff --git a/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java b/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java
index 934ad7a9e..216f32b2e 100644
--- a/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java
+++ b/guava-tests/test/com/google/common/collect/SynchronizedTableTest.java
@@ -119,13 +119,13 @@ public class SynchronizedTableTest extends AbstractTableTest {
}
@Override
- public V get(Object rowKey, Object columnKey) {
+ public @Nullable V get(Object rowKey, Object columnKey) {
assertTrue(Thread.holdsLock(mutex));
return delegate.get(rowKey, columnKey);
}
@Override
- public V put(R rowKey, C columnKey, V value) {
+ public @Nullable V put(R rowKey, C columnKey, V value) {
assertTrue(Thread.holdsLock(mutex));
return delegate.put(rowKey, columnKey, value);
}
@@ -137,7 +137,7 @@ public class SynchronizedTableTest extends AbstractTableTest {
}
@Override
- public V remove(Object rowKey, Object columnKey) {
+ public @Nullable V remove(Object rowKey, Object columnKey) {
assertTrue(Thread.holdsLock(mutex));
return delegate.remove(rowKey, columnKey);
}
diff --git a/guava-tests/test/com/google/common/collect/TableCollectionTest.java b/guava-tests/test/com/google/common/collect/TableCollectionTest.java
index 7c944441a..18ad54939 100644
--- a/guava-tests/test/com/google/common/collect/TableCollectionTest.java
+++ b/guava-tests/test/com/google/common/collect/TableCollectionTest.java
@@ -35,17 +35,16 @@ import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.SortedMap;
import java.util.SortedSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Collection tests for {@link Table} implementations.
@@ -78,35 +77,6 @@ public class TableCollectionTest extends TestCase {
@GwtIncompatible // suite
public static Test suite() {
TestSuite suite = new TestSuite();
- suite.addTestSuite(ArrayRowTests.class);
- suite.addTestSuite(HashRowTests.class);
- suite.addTestSuite(TreeRowTests.class);
- suite.addTestSuite(TransposeRowTests.class);
- suite.addTestSuite(TransformValueRowTests.class);
- suite.addTestSuite(UnmodifiableHashRowTests.class);
- suite.addTestSuite(UnmodifiableTreeRowTests.class);
- suite.addTestSuite(ArrayColumnTests.class);
- suite.addTestSuite(HashColumnTests.class);
- suite.addTestSuite(TreeColumnTests.class);
- suite.addTestSuite(TransposeColumnTests.class);
- suite.addTestSuite(TransformValueColumnTests.class);
- suite.addTestSuite(UnmodifiableHashColumnTests.class);
- suite.addTestSuite(UnmodifiableTreeColumnTests.class);
- suite.addTestSuite(ArrayRowMapTests.class);
- suite.addTestSuite(HashRowMapTests.class);
- suite.addTestSuite(TreeRowMapTests.class);
- suite.addTestSuite(TreeRowMapHeadMapTests.class);
- suite.addTestSuite(TreeRowMapTailMapTests.class);
- suite.addTestSuite(TreeRowMapSubMapTests.class);
- suite.addTestSuite(TransformValueRowMapTests.class);
- suite.addTestSuite(UnmodifiableHashRowMapTests.class);
- suite.addTestSuite(UnmodifiableTreeRowMapTests.class);
- suite.addTestSuite(ArrayColumnMapTests.class);
- suite.addTestSuite(HashColumnMapTests.class);
- suite.addTestSuite(TreeColumnMapTests.class);
- suite.addTestSuite(TransformValueColumnMapTests.class);
- suite.addTestSuite(UnmodifiableHashColumnMapTests.class);
- suite.addTestSuite(UnmodifiableTreeColumnMapTests.class);
// Not testing rowKeySet() or columnKeySet() of Table.transformValues()
// since the transformation doesn't affect the row and column key sets.
@@ -770,7 +740,7 @@ public class TableCollectionTest extends TestCase {
}
}
- private abstract static class RowTests extends MapTests {
+ abstract static class RowTests extends MapTests {
RowTests(
boolean allowsNullValues,
boolean supportsPut,
@@ -798,138 +768,15 @@ public class TableCollectionTest extends TestCase {
}
}
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayRowTests extends RowTests {
- public ArrayRowTests() {
- super(true, true, false, false, false);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected Table<Character, String, Integer> makeTable() {
- return ArrayTable.create(
- Arrays.asList('a', 'b', 'c'), Arrays.asList("one", "two", "three", "four"));
- }
- }
-
- public static class HashRowTests extends RowTests {
- public HashRowTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeRowTests extends RowTests {
- public TreeRowTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TransposeRowTests extends RowTests {
- public TransposeRowTests() {
- super(false, true, true, true, false);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- Table<String, Character, Integer> original = TreeBasedTable.create();
- return Tables.transpose(original);
- }
- }
-
- private static final Function<Integer, Integer> DIVIDE_BY_2 =
- new Function<Integer, Integer>() {
+ static final Function<@Nullable Integer, @Nullable Integer> DIVIDE_BY_2 =
+ new Function<@Nullable Integer, @Nullable Integer>() {
@Override
- public Integer apply(Integer input) {
+ public @Nullable Integer apply(@Nullable Integer input) {
return (input == null) ? null : input / 2;
}
};
- public static class TransformValueRowTests extends RowTests {
- public TransformValueRowTests() {
- super(false, false, true, true, true);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- return Tables.transformValues(table, DIVIDE_BY_2);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- table.put('a', "one", 2);
- table.put('a', "two", 4);
- table.put('a', "three", 6);
- table.put('b', "four", 8);
- return Tables.transformValues(table, DIVIDE_BY_2).row('a');
- }
- }
-
- public static class UnmodifiableHashRowTests extends RowTests {
- public UnmodifiableHashRowTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- return Tables.unmodifiableTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<Character, String, Integer> table = HashBasedTable.create();
- table.put('a', "one", 1);
- table.put('a', "two", 2);
- table.put('a', "three", 3);
- table.put('b', "four", 4);
- return Tables.unmodifiableTable(table).row('a');
- }
- }
-
- public static class UnmodifiableTreeRowTests extends RowTests {
- public UnmodifiableTreeRowTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<Character, String, Integer> makeTable() {
- RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
- table.put('a', "one", 1);
- table.put('a', "two", 2);
- table.put('a', "three", 3);
- table.put('b', "four", 4);
- return Tables.unmodifiableRowSortedTable(table).row('a');
- }
- }
-
- private abstract static class ColumnTests extends MapTests {
+ abstract static class ColumnTests extends MapTests {
ColumnTests(
boolean allowsNullValues,
boolean supportsPut,
@@ -957,129 +804,6 @@ public class TableCollectionTest extends TestCase {
}
}
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayColumnTests extends ColumnTests {
- public ArrayColumnTests() {
- super(true, true, false, false, false);
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected Map<String, Integer> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- return ArrayTable.create(
- Arrays.asList("one", "two", "three", "four"), Arrays.asList('a', 'b', 'c'));
- }
- }
-
- public static class HashColumnTests extends ColumnTests {
- public HashColumnTests() {
- super(false, true, true, true, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeColumnTests extends ColumnTests {
- public TreeColumnTests() {
- super(false, true, true, true, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TransposeColumnTests extends ColumnTests {
- public TransposeColumnTests() {
- super(false, true, true, true, true);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- Table<Character, String, Integer> original = TreeBasedTable.create();
- return Tables.transpose(original);
- }
- }
-
- public static class TransformValueColumnTests extends ColumnTests {
- public TransformValueColumnTests() {
- super(false, false, true, true, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- return Tables.transformValues(table, DIVIDE_BY_2);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- table.put("one", 'a', 1);
- table.put("two", 'a', 2);
- table.put("three", 'a', 3);
- table.put("four", 'b', 4);
- return Tables.transformValues(table, DIVIDE_BY_2).column('a');
- }
- }
-
- public static class UnmodifiableHashColumnTests extends ColumnTests {
- public UnmodifiableHashColumnTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- return Tables.unmodifiableTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- Table<String, Character, Integer> table = HashBasedTable.create();
- table.put("one", 'a', 1);
- table.put("two", 'a', 2);
- table.put("three", 'a', 3);
- table.put("four", 'b', 4);
- return Tables.unmodifiableTable(table).column('a');
- }
- }
-
- public static class UnmodifiableTreeColumnTests extends ColumnTests {
- public UnmodifiableTreeColumnTests() {
- super(false, false, false, false, false);
- }
-
- @Override
- Table<String, Character, Integer> makeTable() {
- RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(table);
- }
-
- @Override
- protected Map<String, Integer> makePopulatedMap() {
- RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
- table.put("one", 'a', 1);
- table.put("two", 'a', 2);
- table.put("three", 'a', 3);
- table.put("four", 'b', 4);
- return Tables.unmodifiableRowSortedTable(table).column('a');
- }
- }
-
private abstract static class MapMapTests
extends MapInterfaceTest<String, Map<Integer, Character>> {
@@ -1136,7 +860,7 @@ public class TableCollectionTest extends TestCase {
}
}
- private abstract static class RowMapTests extends MapMapTests {
+ abstract static class RowMapTests extends MapMapTests {
RowMapTests(
boolean allowsNullValues,
boolean supportsRemove,
@@ -1166,208 +890,15 @@ public class TableCollectionTest extends TestCase {
}
}
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayRowMapTests extends RowMapTests {
- public ArrayRowMapTests() {
- super(true, false, false, false);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- return ArrayTable.create(Arrays.asList("foo", "bar", "dog"), Arrays.asList(1, 2, 3));
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
- }
-
- public static class HashRowMapTests extends RowMapTests {
- public HashRowMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeRowMapTests extends RowMapTests {
- public TreeRowMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TreeRowMapHeadMapTests extends RowMapTests {
- public TreeRowMapHeadMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- TreeBasedTable<String, Integer, Character> makeTable() {
- TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("z", 1, 'a');
- return table;
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- TreeBasedTable<String, Integer, Character> table = makeTable();
- populateTable(table);
- return table.rowMap().headMap("x");
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- return makeTable().rowMap().headMap("x");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "z";
- }
- }
-
- public static class TreeRowMapTailMapTests extends RowMapTests {
- public TreeRowMapTailMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- TreeBasedTable<String, Integer, Character> makeTable() {
- TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("a", 1, 'a');
- return table;
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- TreeBasedTable<String, Integer, Character> table = makeTable();
- populateTable(table);
- return table.rowMap().tailMap("b");
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- return makeTable().rowMap().tailMap("b");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "a";
- }
- }
-
- public static class TreeRowMapSubMapTests extends RowMapTests {
- public TreeRowMapSubMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- TreeBasedTable<String, Integer, Character> makeTable() {
- TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("a", 1, 'a');
- table.put("z", 1, 'a');
- return table;
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- TreeBasedTable<String, Integer, Character> table = makeTable();
- populateTable(table);
- return table.rowMap().subMap("b", "x");
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- return makeTable().rowMap().subMap("b", "x");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "z";
- }
- }
-
- private static final Function<String, Character> FIRST_CHARACTER =
- new Function<String, Character>() {
+ static final Function<@Nullable String, @Nullable Character> FIRST_CHARACTER =
+ new Function<@Nullable String, @Nullable Character>() {
@Override
- public Character apply(String input) {
+ public @Nullable Character apply(@Nullable String input) {
return input == null ? null : input.charAt(0);
}
};
- public static class TransformValueRowMapTests extends RowMapTests {
- public TransformValueRowMapTests() {
- super(false, true, true, true);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- Table<String, Integer, String> original = HashBasedTable.create();
- return Tables.transformValues(original, FIRST_CHARACTER);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<String, Integer, String> table = HashBasedTable.create();
- table.put("foo", 1, "apple");
- table.put("bar", 1, "banana");
- table.put("foo", 3, "cat");
- return Tables.transformValues(table, FIRST_CHARACTER).rowMap();
- }
- }
-
- public static class UnmodifiableHashRowMapTests extends RowMapTests {
- public UnmodifiableHashRowMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- Table<String, Integer, Character> makeTable() {
- Table<String, Integer, Character> original = HashBasedTable.create();
- return Tables.unmodifiableTable(original);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<String, Integer, Character> table = HashBasedTable.create();
- table.put("foo", 1, 'a');
- table.put("bar", 1, 'b');
- table.put("foo", 3, 'c');
- return Tables.unmodifiableTable(table).rowMap();
- }
- }
-
- public static class UnmodifiableTreeRowMapTests extends RowMapTests {
- public UnmodifiableTreeRowMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- RowSortedTable<String, Integer, Character> makeTable() {
- RowSortedTable<String, Integer, Character> original = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(original);
- }
-
- @Override
- protected SortedMap<String, Map<Integer, Character>> makePopulatedMap() {
- RowSortedTable<String, Integer, Character> table = TreeBasedTable.create();
- table.put("foo", 1, 'a');
- table.put("bar", 1, 'b');
- table.put("foo", 3, 'c');
- return Tables.unmodifiableRowSortedTable(table).rowMap();
- }
- }
-
- private abstract static class ColumnMapTests extends MapMapTests {
+ abstract static class ColumnMapTests extends MapMapTests {
ColumnMapTests(
boolean allowsNullValues,
boolean supportsRemove,
@@ -1392,106 +923,4 @@ public class TableCollectionTest extends TestCase {
return makeTable().columnMap();
}
}
-
- @GwtIncompatible // TODO(hhchan): ArrayTable
- public static class ArrayColumnMapTests extends ColumnMapTests {
- public ArrayColumnMapTests() {
- super(true, false, false, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- return ArrayTable.create(Arrays.asList(1, 2, 3), Arrays.asList("foo", "bar", "dog"));
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makeEmptyMap() {
- throw new UnsupportedOperationException();
- }
- }
-
- public static class HashColumnMapTests extends ColumnMapTests {
- public HashColumnMapTests() {
- super(false, true, true, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- return HashBasedTable.create();
- }
- }
-
- public static class TreeColumnMapTests extends ColumnMapTests {
- public TreeColumnMapTests() {
- super(false, true, true, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- return TreeBasedTable.create();
- }
- }
-
- public static class TransformValueColumnMapTests extends ColumnMapTests {
- public TransformValueColumnMapTests() {
- super(false, true, true, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- Table<Integer, String, String> original = HashBasedTable.create();
- return Tables.transformValues(original, FIRST_CHARACTER);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<Integer, String, String> table = HashBasedTable.create();
- table.put(1, "foo", "apple");
- table.put(1, "bar", "banana");
- table.put(3, "foo", "cat");
- return Tables.transformValues(table, FIRST_CHARACTER).columnMap();
- }
- }
-
- public static class UnmodifiableHashColumnMapTests extends ColumnMapTests {
- public UnmodifiableHashColumnMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- Table<Integer, String, Character> original = HashBasedTable.create();
- return Tables.unmodifiableTable(original);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- Table<Integer, String, Character> table = HashBasedTable.create();
- table.put(1, "foo", 'a');
- table.put(1, "bar", 'b');
- table.put(3, "foo", 'c');
- return Tables.unmodifiableTable(table).columnMap();
- }
- }
-
- public static class UnmodifiableTreeColumnMapTests extends ColumnMapTests {
- public UnmodifiableTreeColumnMapTests() {
- super(false, false, false, false);
- }
-
- @Override
- Table<Integer, String, Character> makeTable() {
- RowSortedTable<Integer, String, Character> original = TreeBasedTable.create();
- return Tables.unmodifiableRowSortedTable(original);
- }
-
- @Override
- protected Map<String, Map<Integer, Character>> makePopulatedMap() {
- RowSortedTable<Integer, String, Character> table = TreeBasedTable.create();
- table.put(1, "foo", 'a');
- table.put(1, "bar", 'b');
- table.put(3, "foo", 'c');
- return Tables.unmodifiableRowSortedTable(table).columnMap();
- }
- }
}
diff --git a/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java b/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java
new file mode 100644
index 000000000..0344b56c1
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnMapTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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 static com.google.common.collect.TableCollectionTest.FIRST_CHARACTER;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesColumnMapTest extends ColumnMapTests {
+ public TablesTransformValuesColumnMapTest() {
+ super(false, true, true, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ Table<Integer, String, String> original = HashBasedTable.create();
+ return Tables.transformValues(original, FIRST_CHARACTER);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<Integer, String, String> table = HashBasedTable.create();
+ table.put(1, "foo", "apple");
+ table.put(1, "bar", "banana");
+ table.put(3, "foo", "cat");
+ return Tables.transformValues(table, FIRST_CHARACTER).columnMap();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java b/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java
new file mode 100644
index 000000000..b28f5c506
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TablesTransformValuesColumnTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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 static com.google.common.collect.TableCollectionTest.DIVIDE_BY_2;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesColumnTest extends ColumnTests {
+ public TablesTransformValuesColumnTest() {
+ super(false, false, true, true, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ return Tables.transformValues(table, DIVIDE_BY_2);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ table.put("one", 'a', 1);
+ table.put("two", 'a', 2);
+ table.put("three", 'a', 3);
+ table.put("four", 'b', 4);
+ return Tables.transformValues(table, DIVIDE_BY_2).column('a');
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java b/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java
new file mode 100644
index 000000000..661a23255
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TablesTransformValuesRowMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesRowMapTest extends RowMapTests {
+ public TablesTransformValuesRowMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ Table<String, Integer, String> original = HashBasedTable.create();
+ return Tables.transformValues(original, TableCollectionTest.FIRST_CHARACTER);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<String, Integer, String> table = HashBasedTable.create();
+ table.put("foo", 1, "apple");
+ table.put("bar", 1, "banana");
+ table.put("foo", 3, "cat");
+ return Tables.transformValues(table, TableCollectionTest.FIRST_CHARACTER).rowMap();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java b/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java
new file mode 100644
index 000000000..71571b983
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TablesTransformValuesRowTest extends RowTests {
+ public TablesTransformValuesRowTest() {
+ super(false, false, true, true, true);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ return Tables.transformValues(table, TableCollectionTest.DIVIDE_BY_2);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ table.put('a', "one", 2);
+ table.put('a', "two", 4);
+ table.put('a', "three", 6);
+ table.put('b', "four", 8);
+ return Tables.transformValues(table, TableCollectionTest.DIVIDE_BY_2).row('a');
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java b/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java
index 6730b3f51..d6330a246 100644
--- a/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java
+++ b/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java
@@ -21,6 +21,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Test cases for {@link Tables#transformValues}.
@@ -30,10 +31,10 @@ import com.google.common.base.Function;
@GwtCompatible(emulated = true)
public class TablesTransformValuesTest extends AbstractTableTest {
- private static final Function<String, Character> FIRST_CHARACTER =
- new Function<String, Character>() {
+ private static final Function<@Nullable String, @Nullable Character> FIRST_CHARACTER =
+ new Function<@Nullable String, @Nullable Character>() {
@Override
- public Character apply(String input) {
+ public @Nullable Character apply(@Nullable String input) {
return input == null ? null : input.charAt(0);
}
};
diff --git a/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java b/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java
new file mode 100644
index 000000000..142dbc7cf
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TablesTransposeColumnTest.java
@@ -0,0 +1,33 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+
+@GwtCompatible
+public class TablesTransposeColumnTest extends ColumnTests {
+ public TablesTransposeColumnTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ Table<Character, String, Integer> original = TreeBasedTable.create();
+ return Tables.transpose(original);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java b/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java
new file mode 100644
index 000000000..03caae1de
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TablesTransposeRowTest.java
@@ -0,0 +1,33 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+
+@GwtCompatible
+public class TablesTransposeRowTest extends RowTests {
+ public TablesTransposeRowTest() {
+ super(false, true, true, true, false);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ Table<String, Character, Integer> original = TreeBasedTable.create();
+ return Tables.transpose(original);
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java
new file mode 100644
index 000000000..b5c92c8e7
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableColumnMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+
+@GwtCompatible
+public class TreeBasedTableColumnMapTest extends ColumnMapTests {
+ public TreeBasedTableColumnMapTest() {
+ super(false, true, true, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java
new file mode 100644
index 000000000..b90f46b4b
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableColumnTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+
+@GwtCompatible
+public class TreeBasedTableColumnTest extends ColumnTests {
+ public TreeBasedTableColumnTest() {
+ super(false, true, true, true, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java
new file mode 100644
index 000000000..05bfc4133
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapHeadMapTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TreeBasedTableRowMapHeadMapTest extends RowMapTests {
+ public TreeBasedTableRowMapHeadMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ TreeBasedTable<String, Integer, Character> makeTable() {
+ TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("z", 1, 'a');
+ return table;
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ TreeBasedTable<String, Integer, Character> table = makeTable();
+ populateTable(table);
+ return table.rowMap().headMap("x");
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ return makeTable().rowMap().headMap("x");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "z";
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java
new file mode 100644
index 000000000..dd8aec3aa
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapInterfaceTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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 com.google.common.collect.testing.SortedMapInterfaceTest;
+import java.util.SortedMap;
+
+@GwtCompatible
+public class TreeBasedTableRowMapInterfaceTest extends SortedMapInterfaceTest<String, String> {
+ public TreeBasedTableRowMapInterfaceTest() {
+ super(false, false, true, true, true);
+ }
+
+ @Override
+ protected SortedMap<String, String> makeEmptyMap() {
+ TreeBasedTable<String, String, String> table = TreeBasedTable.create();
+ table.put("a", "b", "c");
+ table.put("c", "b", "a");
+ table.put("a", "a", "d");
+ return table.row("b");
+ }
+
+ @Override
+ protected SortedMap<String, String> makePopulatedMap() {
+ TreeBasedTable<String, String, String> table = TreeBasedTable.create();
+ table.put("a", "b", "c");
+ table.put("c", "b", "a");
+ table.put("b", "b", "x");
+ table.put("b", "c", "y");
+ table.put("b", "x", "n");
+ table.put("a", "a", "d");
+ return table.row("b");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "q";
+ }
+
+ @Override
+ protected String getValueNotInPopulatedMap() {
+ return "p";
+ }
+
+ public void testClearSubMapOfRowMap() {
+ TreeBasedTable<String, String, String> table = TreeBasedTable.create();
+ table.put("a", "b", "c");
+ table.put("c", "b", "a");
+ table.put("b", "b", "x");
+ table.put("b", "c", "y");
+ table.put("b", "x", "n");
+ table.put("a", "a", "d");
+ table.row("b").subMap("c", "x").clear();
+ assertEquals(table.row("b"), ImmutableMap.of("b", "x", "x", "n"));
+ table.row("b").subMap("b", "y").clear();
+ assertEquals(table.row("b"), ImmutableMap.of());
+ assertFalse(table.backingMap.containsKey("b"));
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java
new file mode 100644
index 000000000..a9c7e9ff4
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapSubMapTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TreeBasedTableRowMapSubMapTest extends RowMapTests {
+ public TreeBasedTableRowMapSubMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ TreeBasedTable<String, Integer, Character> makeTable() {
+ TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("a", 1, 'a');
+ table.put("z", 1, 'a');
+ return table;
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ TreeBasedTable<String, Integer, Character> table = makeTable();
+ populateTable(table);
+ return table.rowMap().subMap("b", "x");
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ return makeTable().rowMap().subMap("b", "x");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "z";
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java
new file mode 100644
index 000000000..7d7b82e43
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTailMapTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class TreeBasedTableRowMapTailMapTest extends RowMapTests {
+ public TreeBasedTableRowMapTailMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ TreeBasedTable<String, Integer, Character> makeTable() {
+ TreeBasedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("a", 1, 'a');
+ return table;
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ TreeBasedTable<String, Integer, Character> table = makeTable();
+ populateTable(table);
+ return table.rowMap().tailMap("b");
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makeEmptyMap() {
+ return makeTable().rowMap().tailMap("b");
+ }
+
+ @Override
+ protected String getKeyNotInPopulatedMap() {
+ return "a";
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java
new file mode 100644
index 000000000..63a86bfcc
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableRowMapTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+
+@GwtCompatible
+public class TreeBasedTableRowMapTest extends RowMapTests {
+ public TreeBasedTableRowMapTest() {
+ super(false, true, true, true);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java
new file mode 100644
index 000000000..9a67fe934
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableRowTest.java
@@ -0,0 +1,32 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+
+@GwtCompatible
+public class TreeBasedTableRowTest extends RowTests {
+ public TreeBasedTableRowTest() {
+ super(false, true, true, true, true);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ return TreeBasedTable.create();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java
index 084e6492f..7975111ed 100644
--- a/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java
+++ b/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java
@@ -20,7 +20,6 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.collect.testing.SortedMapInterfaceTest;
import com.google.common.collect.testing.SortedMapTestSuiteBuilder;
import com.google.common.collect.testing.TestStringSortedMapGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
@@ -48,7 +47,6 @@ public class TreeBasedTableTest extends AbstractTableTest {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(TreeBasedTableTest.class);
- suite.addTestSuite(TreeRowTest.class);
suite.addTest(
SortedMapTestSuiteBuilder.using(
new TestStringSortedMapGenerator() {
@@ -73,58 +71,6 @@ public class TreeBasedTableTest extends AbstractTableTest {
return suite;
}
- public static class TreeRowTest extends SortedMapInterfaceTest<String, String> {
- public TreeRowTest() {
- super(false, false, true, true, true);
- }
-
- @Override
- protected SortedMap<String, String> makeEmptyMap() {
- TreeBasedTable<String, String, String> table = TreeBasedTable.create();
- table.put("a", "b", "c");
- table.put("c", "b", "a");
- table.put("a", "a", "d");
- return table.row("b");
- }
-
- @Override
- protected SortedMap<String, String> makePopulatedMap() {
- TreeBasedTable<String, String, String> table = TreeBasedTable.create();
- table.put("a", "b", "c");
- table.put("c", "b", "a");
- table.put("b", "b", "x");
- table.put("b", "c", "y");
- table.put("b", "x", "n");
- table.put("a", "a", "d");
- return table.row("b");
- }
-
- @Override
- protected String getKeyNotInPopulatedMap() {
- return "q";
- }
-
- @Override
- protected String getValueNotInPopulatedMap() {
- return "p";
- }
-
- public void testClearSubMapOfRowMap() {
- TreeBasedTable<String, String, String> table = TreeBasedTable.create();
- table.put("a", "b", "c");
- table.put("c", "b", "a");
- table.put("b", "b", "x");
- table.put("b", "c", "y");
- table.put("b", "x", "n");
- table.put("a", "a", "d");
- table.row("b").subMap("c", "x").clear();
- assertEquals(table.row("b"), ImmutableMap.of("b", "x", "x", "n"));
- table.row("b").subMap("b", "y").clear();
- assertEquals(table.row("b"), ImmutableMap.of());
- assertFalse(table.backingMap.containsKey("b"));
- }
- }
-
private TreeBasedTable<String, Integer, Character> sortedTable;
protected TreeBasedTable<String, Integer, Character> create(
diff --git a/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java b/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java
index 92a3d83a7..4b00570a6 100644
--- a/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java
+++ b/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java
@@ -28,6 +28,7 @@ import java.util.Iterator;
import java.util.Map.Entry;
import java.util.SortedSet;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@code TreeMultimap} with explicit comparators.
@@ -41,11 +42,11 @@ public class TreeMultimapExplicitTest extends TestCase {
* Compare strings lengths, and if the lengths are equal compare the strings. A {@code null} is
* less than any non-null value.
*/
- private enum StringLength implements Comparator<String> {
+ private enum StringLength implements Comparator<@Nullable String> {
COMPARATOR;
@Override
- public int compare(String first, String second) {
+ public int compare(@Nullable String first, @Nullable String second) {
if (first == second) {
return 0;
} else if (first == null) {
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java
new file mode 100644
index 000000000..3f49178c3
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableColumnMapTest extends ColumnMapTests {
+ public UnmodifiableRowSortedTableColumnMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ RowSortedTable<Integer, String, Character> original = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(original);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ RowSortedTable<Integer, String, Character> table = TreeBasedTable.create();
+ table.put(1, "foo", 'a');
+ table.put(1, "bar", 'b');
+ table.put(3, "foo", 'c');
+ return Tables.unmodifiableRowSortedTable(table).columnMap();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java
new file mode 100644
index 000000000..ff7008160
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableColumnTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableColumnTest extends ColumnTests {
+ public UnmodifiableRowSortedTableColumnTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ RowSortedTable<String, Character, Integer> table = TreeBasedTable.create();
+ table.put("one", 'a', 1);
+ table.put("two", 'a', 2);
+ table.put("three", 'a', 3);
+ table.put("four", 'b', 4);
+ return Tables.unmodifiableRowSortedTable(table).column('a');
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java
new file mode 100644
index 000000000..76dadc334
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowMapTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+import java.util.SortedMap;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableRowMapTest extends RowMapTests {
+ public UnmodifiableRowSortedTableRowMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ RowSortedTable<String, Integer, Character> makeTable() {
+ RowSortedTable<String, Integer, Character> original = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(original);
+ }
+
+ @Override
+ protected SortedMap<String, Map<Integer, Character>> makePopulatedMap() {
+ RowSortedTable<String, Integer, Character> table = TreeBasedTable.create();
+ table.put("foo", 1, 'a');
+ table.put("bar", 1, 'b');
+ table.put("foo", 3, 'c');
+ return Tables.unmodifiableRowSortedTable(table).rowMap();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java
new file mode 100644
index 000000000..0de5f0e34
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableRowSortedTableRowTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableRowSortedTableRowTest extends RowTests {
+ public UnmodifiableRowSortedTableRowTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
+ return Tables.unmodifiableRowSortedTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ RowSortedTable<Character, String, Integer> table = TreeBasedTable.create();
+ table.put('a', "one", 1);
+ table.put('a', "two", 2);
+ table.put('a', "three", 3);
+ table.put('b', "four", 4);
+ return Tables.unmodifiableRowSortedTable(table).row('a');
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java
new file mode 100644
index 000000000..a5cc6fba9
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableColumnMapTest extends ColumnMapTests {
+ public UnmodifiableTableColumnMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ Table<Integer, String, Character> makeTable() {
+ Table<Integer, String, Character> original = HashBasedTable.create();
+ return Tables.unmodifiableTable(original);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<Integer, String, Character> table = HashBasedTable.create();
+ table.put(1, "foo", 'a');
+ table.put(1, "bar", 'b');
+ table.put(3, "foo", 'c');
+ return Tables.unmodifiableTable(table).columnMap();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java
new file mode 100644
index 000000000..ebf378b87
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableTableColumnTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.ColumnTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableColumnTest extends ColumnTests {
+ public UnmodifiableTableColumnTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<String, Character, Integer> makeTable() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ return Tables.unmodifiableTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<String, Character, Integer> table = HashBasedTable.create();
+ table.put("one", 'a', 1);
+ table.put("two", 'a', 2);
+ table.put("three", 'a', 3);
+ table.put("four", 'b', 4);
+ return Tables.unmodifiableTable(table).column('a');
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java
new file mode 100644
index 000000000..c53f15777
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableTableRowMapTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowMapTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableRowMapTest extends RowMapTests {
+ public UnmodifiableTableRowMapTest() {
+ super(false, false, false, false);
+ }
+
+ @Override
+ Table<String, Integer, Character> makeTable() {
+ Table<String, Integer, Character> original = HashBasedTable.create();
+ return Tables.unmodifiableTable(original);
+ }
+
+ @Override
+ protected Map<String, Map<Integer, Character>> makePopulatedMap() {
+ Table<String, Integer, Character> table = HashBasedTable.create();
+ table.put("foo", 1, 'a');
+ table.put("bar", 1, 'b');
+ table.put("foo", 3, 'c');
+ return Tables.unmodifiableTable(table).rowMap();
+ }
+}
diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java
new file mode 100644
index 000000000..f0440abc5
--- /dev/null
+++ b/guava-tests/test/com/google/common/collect/UnmodifiableTableRowTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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 com.google.common.collect.TableCollectionTest.RowTests;
+import java.util.Map;
+
+@GwtCompatible
+public class UnmodifiableTableRowTest extends RowTests {
+ public UnmodifiableTableRowTest() {
+ super(false, false, false, false, false);
+ }
+
+ @Override
+ Table<Character, String, Integer> makeTable() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ return Tables.unmodifiableTable(table);
+ }
+
+ @Override
+ protected Map<String, Integer> makePopulatedMap() {
+ Table<Character, String, Integer> table = HashBasedTable.create();
+ table.put('a', "one", 1);
+ table.put('a', "two", 2);
+ table.put('a', "three", 3);
+ table.put('b', "four", 4);
+ return Tables.unmodifiableTable(table).row('a');
+ }
+}
diff --git a/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java b/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java
index 6d9c1d89d..47d04bfc9 100644
--- a/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java
+++ b/guava-tests/test/com/google/common/escape/ArrayBasedEscaperMapTest.java
@@ -62,7 +62,7 @@ public class ArrayBasedEscaperMapTest extends TestCase {
char[][] replacementArray = fem.getReplacementArray();
// Array length is highest character value + 1
assertEquals(65536, replacementArray.length);
- // The final element should always be non null.
+ // The final element should always be non-null.
assertNotNull(replacementArray[replacementArray.length - 1]);
// Exhaustively check all mappings (an int index avoids wrapping).
for (int n = 0; n < replacementArray.length; ++n) {
diff --git a/guava-tests/test/com/google/common/escape/EscapersTest.java b/guava-tests/test/com/google/common/escape/EscapersTest.java
index 442232030..e9549d083 100644
--- a/guava-tests/test/com/google/common/escape/EscapersTest.java
+++ b/guava-tests/test/com/google/common/escape/EscapersTest.java
@@ -60,7 +60,7 @@ public class EscapersTest extends TestCase {
}
public void testBuilderCreatesIndependentEscapers() {
- // Setup a simple builder and create the first escaper.
+ // Set up a simple builder and create the first escaper.
Escapers.Builder builder = Escapers.builder();
builder.setSafeRange('a', 'z');
builder.setUnsafeReplacement("X");
@@ -108,7 +108,7 @@ public class EscapersTest extends TestCase {
}
}
- // A trival non-optimized escaper for testing.
+ // A trivial non-optimized escaper for testing.
static CharEscaper createSimpleCharEscaper(final ImmutableMap<Character, char[]> replacementMap) {
return new CharEscaper() {
@Override
@@ -118,7 +118,7 @@ public class EscapersTest extends TestCase {
};
}
- // A trival non-optimized escaper for testing.
+ // A trivial non-optimized escaper for testing.
static UnicodeEscaper createSimpleUnicodeEscaper(
final ImmutableMap<Integer, char[]> replacementMap) {
return new UnicodeEscaper() {
diff --git a/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java b/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java
index 96cfa10b0..48f2f1715 100644
--- a/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java
+++ b/guava-tests/test/com/google/common/escape/UnicodeEscaperTest.java
@@ -18,6 +18,7 @@ package com.google.common.escape;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link UnicodeEscaper}.
@@ -39,7 +40,7 @@ public class UnicodeEscaperTest extends TestCase {
private static final UnicodeEscaper NOP_ESCAPER =
new UnicodeEscaper() {
@Override
- protected char[] escape(int c) {
+ protected char @Nullable [] escape(int c) {
return null;
}
};
@@ -48,7 +49,7 @@ public class UnicodeEscaperTest extends TestCase {
private static final UnicodeEscaper SIMPLE_ESCAPER =
new UnicodeEscaper() {
@Override
- protected char[] escape(int cp) {
+ protected char @Nullable [] escape(int cp) {
return ('a' <= cp && cp <= 'z') || ('A' <= cp && cp <= 'Z') || ('0' <= cp && cp <= '9')
? null
: ("[" + String.valueOf(cp) + "]").toCharArray();
@@ -163,7 +164,7 @@ public class UnicodeEscaperTest extends TestCase {
new UnicodeEscaper() {
// Canonical escaper method that only escapes lower case ASCII letters.
@Override
- protected char[] escape(int cp) {
+ protected char @Nullable [] escape(int cp) {
return ('a' <= cp && cp <= 'z') ? new char[] {Character.toUpperCase((char) cp)} : null;
}
// Inefficient implementation that defines all letters as escapable.
diff --git a/guava-tests/test/com/google/common/eventbus/DispatcherTest.java b/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
index b63a99543..ec78c716f 100644
--- a/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
+++ b/guava-tests/test/com/google/common/eventbus/DispatcherTest.java
@@ -31,7 +31,6 @@ import junit.framework.TestCase;
*
* @author Colin Decker
*/
-
public class DispatcherTest extends TestCase {
private final EventBus bus = new EventBus();
diff --git a/guava-tests/test/com/google/common/eventbus/EventBusTest.java b/guava-tests/test/com/google/common/eventbus/EventBusTest.java
index 249d3b06c..d314f7ee7 100644
--- a/guava-tests/test/com/google/common/eventbus/EventBusTest.java
+++ b/guava-tests/test/com/google/common/eventbus/EventBusTest.java
@@ -168,7 +168,7 @@ public class EventBusTest extends TestCase {
GhostCatcher catcher = new GhostCatcher();
bus.register(catcher);
- // A String -- an event for which noone has registered.
+ // A String -- an event for which no one has registered.
bus.post(EVENT);
List<DeadEvent> events = catcher.getEvents();
@@ -239,7 +239,6 @@ public class EventBusTest extends TestCase {
// NOTE: This test will always pass if register() is thread-safe but may also
// pass if it isn't, though this is unlikely.
-
public void testRegisterThreadSafety() throws Exception {
List<StringCatcher> catchers = Lists.newCopyOnWriteArrayList();
List<Future<?>> futures = Lists.newArrayList();
diff --git a/guava-tests/test/com/google/common/eventbus/SubscriberTest.java b/guava-tests/test/com/google/common/eventbus/SubscriberTest.java
index e2380df21..14210ac14 100644
--- a/guava-tests/test/com/google/common/eventbus/SubscriberTest.java
+++ b/guava-tests/test/com/google/common/eventbus/SubscriberTest.java
@@ -22,6 +22,7 @@ import com.google.common.testing.EqualsTester;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link Subscriber}.
@@ -35,7 +36,7 @@ public class SubscriberTest extends TestCase {
private EventBus bus;
private boolean methodCalled;
- private Object methodArgument;
+ private @Nullable Object methodArgument;
@Override
protected void setUp() throws Exception {
diff --git a/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java b/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java
index f4af7a751..54d6c93f5 100644
--- a/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java
+++ b/guava-tests/test/com/google/common/eventbus/outside/AbstractEventBusTest.java
@@ -18,6 +18,7 @@ package com.google.common.eventbus.outside;
import com.google.common.eventbus.EventBus;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Abstract base class for tests that EventBus finds the correct subscribers.
@@ -34,7 +35,7 @@ abstract class AbstractEventBusTest<H> extends TestCase {
abstract H createSubscriber();
- private H subscriber;
+ private @Nullable H subscriber;
H getSubscriber() {
return subscriber;
diff --git a/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java b/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java
index e5e8e7f01..be551ce34 100644
--- a/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java
+++ b/guava-tests/test/com/google/common/graph/AbstractNetworkTest.java
@@ -36,6 +36,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -792,7 +793,6 @@ public abstract class AbstractNetworkTest {
assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12);
}
-
@Test
public void concurrentIteration() throws Exception {
addEdge(1, 2, "foo");
@@ -806,9 +806,9 @@ public abstract class AbstractNetworkTest {
for (int i = 0; i < threadCount; i++) {
futures.add(
executor.submit(
- new Callable<Object>() {
+ new Callable<@Nullable Void>() {
@Override
- public Object call() throws Exception {
+ public @Nullable Void call() throws Exception {
barrier.await();
Integer first = network.nodes().iterator().next();
for (Integer node : network.nodes()) {
diff --git a/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java b/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java
index a483f42d1..da9226c31 100644
--- a/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java
+++ b/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedGraphTest.java
@@ -166,8 +166,8 @@ public abstract class AbstractStandardUndirectedGraphTest extends AbstractGraphT
@Test
public void hasEdgeConnecting_mismatch() {
putEdge(N1, N2);
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N1, N2))).isTrue();
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N2, N1))).isTrue();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N1, N2))).isFalse();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(N2, N1))).isFalse();
}
@Test
diff --git a/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java b/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java
index 7939ad835..de6fee22e 100644
--- a/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java
+++ b/guava-tests/test/com/google/common/graph/AbstractStandardUndirectedNetworkTest.java
@@ -16,14 +16,15 @@
package com.google.common.graph;
+import static com.google.common.graph.GraphConstants.ENDPOINTS_MISMATCH;
import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth8.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
+import java.util.Optional;
import java.util.Set;
import org.junit.After;
import org.junit.Test;
@@ -196,29 +197,41 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
@Test
public void edges_containsOrderMismatch() {
addEdge(N1, N2, E12);
- assertThat(network.asGraph().edges()).contains(ENDPOINTS_N2N1);
- assertThat(network.asGraph().edges()).contains(ENDPOINTS_N1N2);
+ assertThat(network.asGraph().edges()).doesNotContain(ENDPOINTS_N2N1);
+ assertThat(network.asGraph().edges()).doesNotContain(ENDPOINTS_N1N2);
}
@Test
public void edgesConnecting_orderMismatch() {
addEdge(N1, N2, E12);
- assertThat(network.edgesConnecting(ENDPOINTS_N2N1)).containsExactly(E12);
- assertThat(network.edgesConnecting(ENDPOINTS_N1N2)).containsExactly(E12);
+ try {
+ Set<String> unused = network.edgesConnecting(ENDPOINTS_N1N2);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
public void edgeConnecting_orderMismatch() {
addEdge(N1, N2, E12);
- assertThat(network.edgeConnecting(ENDPOINTS_N2N1)).hasValue(E12);
- assertThat(network.edgeConnecting(ENDPOINTS_N1N2)).hasValue(E12);
+ try {
+ Optional<String> unused = network.edgeConnecting(ENDPOINTS_N1N2);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
public void edgeConnectingOrNull_orderMismatch() {
addEdge(N1, N2, E12);
- assertThat(network.edgeConnectingOrNull(ENDPOINTS_N2N1)).isEqualTo(E12);
- assertThat(network.edgeConnectingOrNull(ENDPOINTS_N1N2)).isEqualTo(E12);
+ try {
+ String unused = network.edgeConnectingOrNull(ENDPOINTS_N1N2);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -433,7 +446,7 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N4, N5, E12);
fail(ERROR_ADDED_EXISTING_EDGE);
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
}
@@ -447,13 +460,13 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N1, N2, EDGE_NOT_IN_GRAPH);
fail(ERROR_ADDED_PARALLEL_EDGE);
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_PARALLEL_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_PARALLEL_EDGE);
}
try {
networkAsMutableNetwork.addEdge(N2, N1, EDGE_NOT_IN_GRAPH);
fail(ERROR_ADDED_PARALLEL_EDGE);
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_PARALLEL_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_PARALLEL_EDGE);
}
}
@@ -473,7 +486,12 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
assume().that(graphIsMutable()).isTrue();
EndpointPair<Integer> endpoints = EndpointPair.ordered(N1, N2);
- assertThat(networkAsMutableNetwork.addEdge(endpoints, E12)).isTrue();
+ try {
+ networkAsMutableNetwork.addEdge(endpoints, E12);
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -542,20 +560,20 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N1, N2, E11);
fail("Reusing an existing self-loop edge to connect different nodes succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
try {
networkAsMutableNetwork.addEdge(N2, N2, E11);
fail("Reusing an existing self-loop edge to make a different self-loop edge succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
addEdge(N1, N2, E12);
try {
networkAsMutableNetwork.addEdge(N1, N1, E12);
fail("Reusing an existing edge to add a self-loop edge between different nodes succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_REUSE_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_REUSE_EDGE);
}
}
@@ -570,7 +588,7 @@ public abstract class AbstractStandardUndirectedNetworkTest extends AbstractNetw
networkAsMutableNetwork.addEdge(N1, N1, EDGE_NOT_IN_GRAPH);
fail("Adding a parallel self-loop edge succeeded");
} catch (IllegalArgumentException e) {
- assertThat(e.getMessage()).contains(ERROR_PARALLEL_EDGE);
+ assertThat(e).hasMessageThat().contains(ERROR_PARALLEL_EDGE);
}
}
diff --git a/guava-tests/test/com/google/common/graph/ElementOrderTest.java b/guava-tests/test/com/google/common/graph/ElementOrderTest.java
index 0557fb7ba..5e4c8d4d8 100644
--- a/guava-tests/test/com/google/common/graph/ElementOrderTest.java
+++ b/guava-tests/test/com/google/common/graph/ElementOrderTest.java
@@ -150,7 +150,7 @@ public final class ElementOrderTest {
// Combined node and edge order tests
@Test
- public void nodeOrderUnorderedandEdgesSorted() {
+ public void nodeOrderUnorderedAndEdgesSorted() {
MutableNetwork<Integer, String> network =
NetworkBuilder.directed()
.nodeOrder(unordered())
diff --git a/guava-tests/test/com/google/common/graph/EndpointPairTest.java b/guava-tests/test/com/google/common/graph/EndpointPairTest.java
index 099be1d22..c67693a71 100644
--- a/guava-tests/test/com/google/common/graph/EndpointPairTest.java
+++ b/guava-tests/test/com/google/common/graph/EndpointPairTest.java
@@ -214,8 +214,8 @@ public final class EndpointPairTest {
assertThat(edges).contains(EndpointPair.unordered(N1, N2));
assertThat(edges).contains(EndpointPair.unordered(N2, N1)); // equal to unordered(N1, N2)
- // ordered endpoints OK for undirected graph (because ordering is irrelevant)
- assertThat(edges).contains(EndpointPair.ordered(N1, N2));
+ // ordered endpoints not compatible with undirected graph
+ assertThat(edges).doesNotContain(EndpointPair.ordered(N1, N2));
assertThat(edges).doesNotContain(EndpointPair.unordered(N2, N2)); // edge not present
assertThat(edges).doesNotContain(EndpointPair.unordered(N3, N4)); // nodes not in graph
diff --git a/guava-tests/test/com/google/common/graph/ValueGraphTest.java b/guava-tests/test/com/google/common/graph/ValueGraphTest.java
index 31d41aa5d..c9be9818d 100644
--- a/guava-tests/test/com/google/common/graph/ValueGraphTest.java
+++ b/guava-tests/test/com/google/common/graph/ValueGraphTest.java
@@ -30,6 +30,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -175,8 +176,8 @@ public final class ValueGraphTest {
public void hasEdgeConnecting_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(1, 2))).isTrue();
- assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(2, 1))).isTrue();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(1, 2))).isFalse();
+ assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(2, 1))).isFalse();
}
@Test
@@ -224,8 +225,19 @@ public final class ValueGraphTest {
public void edgeValue_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
- assertThat(graph.edgeValue(EndpointPair.ordered(1, 2))).hasValue("A");
- assertThat(graph.edgeValue(EndpointPair.ordered(2, 1))).hasValue("A");
+ // Check that edgeValue() throws on each possible ordering of an ordered EndpointPair
+ try {
+ Optional<String> unused = graph.edgeValue(EndpointPair.ordered(1, 2));
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
+ try {
+ Optional<String> unused = graph.edgeValue(EndpointPair.ordered(2, 1));
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -274,8 +286,19 @@ public final class ValueGraphTest {
public void edgeValueOrDefault_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
- assertThat(graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default")).isEqualTo("A");
- assertThat(graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default")).isEqualTo("A");
+ // Check that edgeValueOrDefault() throws on each possible ordering of an ordered EndpointPair
+ try {
+ String unused = graph.edgeValueOrDefault(EndpointPair.ordered(1, 2), "default");
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
+ try {
+ String unused = graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default");
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -302,7 +325,12 @@ public final class ValueGraphTest {
@Test
public void putEdgeValue_undirected_orderMismatch() {
graph = ValueGraphBuilder.undirected().build();
- assertThat(graph.putEdgeValue(EndpointPair.ordered(1, 2), "irrelevant")).isNull();
+ try {
+ graph.putEdgeValue(EndpointPair.ordered(1, 2), "irrelevant");
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -362,7 +390,19 @@ public final class ValueGraphTest {
public void removeEdge_undirected_orderMismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "1-2");
- assertThat(graph.removeEdge(EndpointPair.ordered(1, 2))).isEqualTo("1-2");
+ // Check that removeEdge() throws on each possible ordering of an ordered EndpointPair
+ try {
+ graph.removeEdge(EndpointPair.ordered(1, 2));
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
+ try {
+ graph.removeEdge(EndpointPair.ordered(2, 1));
+ fail("Expected IllegalArgumentException: " + ENDPOINTS_MISMATCH);
+ } catch (IllegalArgumentException e) {
+ assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
+ }
}
@Test
@@ -440,7 +480,6 @@ public final class ValueGraphTest {
.inOrder();
}
-
@Test
public void concurrentIteration() throws Exception {
graph = ValueGraphBuilder.directed().build();
@@ -455,9 +494,9 @@ public final class ValueGraphTest {
for (int i = 0; i < threadCount; i++) {
futures.add(
executor.submit(
- new Callable<Object>() {
+ new Callable<@Nullable Void>() {
@Override
- public Object call() throws Exception {
+ public @Nullable Void call() throws Exception {
barrier.await();
Integer first = graph.nodes().iterator().next();
for (Integer node : graph.nodes()) {
diff --git a/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java b/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java
index e5c359aaf..7ceb25e0c 100644
--- a/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java
+++ b/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java
@@ -17,7 +17,6 @@ package com.google.common.hash;
import static com.google.common.base.Charsets.UTF_16LE;
import static org.junit.Assert.assertArrayEquals;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import junit.framework.TestCase;
@@ -110,7 +109,6 @@ public class AbstractByteHasherTest extends TestCase {
}
}
- @CanIgnoreReturnValue
private class TestHasher extends AbstractByteHasher {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
diff --git a/guava-tests/test/com/google/common/hash/HashCodeTest.java b/guava-tests/test/com/google/common/hash/HashCodeTest.java
index 4cccefe7e..231fd402b 100644
--- a/guava-tests/test/com/google/common/hash/HashCodeTest.java
+++ b/guava-tests/test/com/google/common/hash/HashCodeTest.java
@@ -24,6 +24,7 @@ import com.google.common.io.BaseEncoding;
import com.google.common.testing.ClassSanityTester;
import java.util.Arrays;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link HashCode}.
@@ -391,7 +392,7 @@ public class HashCodeTest extends TestCase {
final Long asLong; // null means that asLong should throw an exception
final String toString;
- ExpectedHashCode(byte[] bytes, int asInt, Long asLong, String toString) {
+ ExpectedHashCode(byte[] bytes, int asInt, @Nullable Long asLong, String toString) {
this.bytes = bytes;
this.asInt = asInt;
this.asLong = asLong;
diff --git a/guava-tests/test/com/google/common/hash/HashTestUtils.java b/guava-tests/test/com/google/common/hash/HashTestUtils.java
index 9e9944b5a..3a9b46c8e 100644
--- a/guava-tests/test/com/google/common/hash/HashTestUtils.java
+++ b/guava-tests/test/com/google/common/hash/HashTestUtils.java
@@ -376,7 +376,7 @@ final class HashTestUtils {
for (int j = 0; j < keyBits; j++) {
if (j <= i) continue;
int count = 0;
- int maxCount = 20; // the probability of error here is miniscule
+ int maxCount = 20; // the probability of error here is minuscule
boolean diff = false;
while (!diff) {
diff --git a/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java b/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java
index 4dbb4241e..7783b5fc3 100644
--- a/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java
+++ b/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java
@@ -29,6 +29,7 @@ import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
import sun.security.jca.ProviderList;
import sun.security.jca.Providers;
@@ -155,7 +156,7 @@ public class MacHashFunctionTest extends TestCase {
}
@Override
- public byte[] getEncoded() {
+ public byte @Nullable [] getEncoded() {
return null;
}
diff --git a/guava-tests/test/com/google/common/io/BaseEncodingTest.java b/guava-tests/test/com/google/common/io/BaseEncodingTest.java
index 06659ab4b..e67f70c5a 100644
--- a/guava-tests/test/com/google/common/io/BaseEncodingTest.java
+++ b/guava-tests/test/com/google/common/io/BaseEncodingTest.java
@@ -125,7 +125,6 @@ public class BaseEncodingTest extends TestCase {
base64().upperCase();
fail();
} catch (IllegalStateException expected) {
- // success
}
}
@@ -134,7 +133,14 @@ public class BaseEncodingTest extends TestCase {
base64().lowerCase();
fail();
} catch (IllegalStateException expected) {
- // success
+ }
+ }
+
+ public void testBase64CannotIgnoreCase() {
+ try {
+ base64().ignoreCase();
+ fail();
+ } catch (IllegalStateException expected) {
}
}
@@ -262,7 +268,19 @@ public class BaseEncodingTest extends TestCase {
}
public void testBase32UpperCaseIsNoOp() {
- assertSame(base32(), base32().upperCase());
+ assertThat(base32().upperCase()).isSameInstanceAs(base32());
+ }
+
+ public void testBase32LowerCase() {
+ testEncodingWithCasing(base32().lowerCase(), "foobar", "mzxw6ytboi======");
+ }
+
+ public void testBase32IgnoreCase() {
+ BaseEncoding ignoreCase = base32().ignoreCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base32());
+ assertThat(ignoreCase).isSameInstanceAs(base32().ignoreCase());
+ testDecodes(ignoreCase, "MZXW6YTBOI======", "foobar");
+ testDecodes(ignoreCase, "mzxw6ytboi======", "foobar");
}
public void testBase32Offset() {
@@ -318,7 +336,7 @@ public class BaseEncodingTest extends TestCase {
}
public void testBase32HexUpperCaseIsNoOp() {
- assertSame(base32Hex(), base32Hex().upperCase());
+ assertThat(base32Hex().upperCase()).isSameInstanceAs(base32Hex());
}
public void testBase16() {
@@ -332,7 +350,44 @@ public class BaseEncodingTest extends TestCase {
}
public void testBase16UpperCaseIsNoOp() {
- assertSame(base16(), base16().upperCase());
+ assertThat(base16().upperCase()).isSameInstanceAs(base16());
+ }
+
+ public void testBase16LowerCase() {
+ BaseEncoding lowerCase = base16().lowerCase();
+ assertThat(lowerCase).isNotSameInstanceAs(base16());
+ assertThat(lowerCase).isSameInstanceAs(base16().lowerCase());
+ testEncodingWithCasing(lowerCase, "foobar", "666f6f626172");
+ }
+
+ public void testBase16IgnoreCase() {
+ BaseEncoding ignoreCase = base16().ignoreCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base16());
+ assertThat(ignoreCase).isSameInstanceAs(base16().ignoreCase());
+ testEncodingWithCasing(ignoreCase, "foobar", "666F6F626172");
+ testDecodes(ignoreCase, "666F6F626172", "foobar");
+ testDecodes(ignoreCase, "666f6f626172", "foobar");
+ testDecodes(ignoreCase, "666F6f626172", "foobar");
+ }
+
+ public void testBase16LowerCaseIgnoreCase() {
+ BaseEncoding ignoreCase = base16().lowerCase().ignoreCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base16());
+ assertThat(ignoreCase).isSameInstanceAs(base16().lowerCase().ignoreCase());
+ testEncodingWithCasing(ignoreCase, "foobar", "666f6f626172");
+ testDecodes(ignoreCase, "666F6F626172", "foobar");
+ testDecodes(ignoreCase, "666f6f626172", "foobar");
+ testDecodes(ignoreCase, "666F6f626172", "foobar");
+ }
+
+ // order the methods are called should not matter
+ public void testBase16IgnoreCaseLowerCase() {
+ BaseEncoding ignoreCase = base16().ignoreCase().lowerCase();
+ assertThat(ignoreCase).isNotSameInstanceAs(base16());
+ testEncodingWithCasing(ignoreCase, "foobar", "666f6f626172");
+ testDecodes(ignoreCase, "666F6F626172", "foobar");
+ testDecodes(ignoreCase, "666f6f626172", "foobar");
+ testDecodes(ignoreCase, "666F6f626172", "foobar");
}
public void testBase16InvalidDecodings() {
@@ -344,6 +399,8 @@ public class BaseEncodingTest extends TestCase {
assertFailsToDecode(base16(), "ABC");
// These have a combination of invalid length and unrecognized characters.
assertFailsToDecode(base16(), "?", "Invalid input length 1");
+ assertFailsToDecode(base16(), "ab");
+ assertFailsToDecode(base16().lowerCase(), "AB");
}
public void testBase16Offset() {
@@ -391,12 +448,12 @@ public class BaseEncodingTest extends TestCase {
}
private static void testDecodes(BaseEncoding encoding, String encoded, String decoded) {
- assertTrue(encoding.canDecode(encoded));
+ assertThat(encoding.canDecode(encoded)).isTrue();
assertThat(encoding.decode(encoded)).isEqualTo(decoded.getBytes(UTF_8));
}
private static void testDecodesByBytes(BaseEncoding encoding, String encoded, byte[] decoded) {
- assertTrue(encoding.canDecode(encoded));
+ assertThat(encoding.canDecode(encoded)).isTrue();
assertThat(encoding.decode(encoded)).isEqualTo(decoded);
}
@@ -441,7 +498,7 @@ public class BaseEncodingTest extends TestCase {
@Override
void assertFailsToDecode(
BaseEncoding encoding, String cannotDecode, @Nullable String expectedMessage) {
- assertFalse(encoding.canDecode(cannotDecode));
+ assertThat(encoding.canDecode(cannotDecode)).isFalse();
}
},
DECODE {
@@ -512,9 +569,9 @@ public class BaseEncodingTest extends TestCase {
private static void testStreamingEncodes(BaseEncoding encoding, String decoded, String encoded)
throws IOException {
StringWriter writer = new StringWriter();
- OutputStream encodingStream = encoding.encodingStream(writer);
- encodingStream.write(decoded.getBytes(UTF_8));
- encodingStream.close();
+ try (OutputStream encodingStream = encoding.encodingStream(writer)) {
+ encodingStream.write(decoded.getBytes(UTF_8));
+ }
assertThat(writer.toString()).isEqualTo(encoded);
}
@@ -522,22 +579,21 @@ public class BaseEncodingTest extends TestCase {
private static void testStreamingDecodes(BaseEncoding encoding, String encoded, String decoded)
throws IOException {
byte[] bytes = decoded.getBytes(UTF_8);
- InputStream decodingStream = encoding.decodingStream(new StringReader(encoded));
- for (int i = 0; i < bytes.length; i++) {
- assertThat(decodingStream.read()).isEqualTo(bytes[i] & 0xFF);
+ try (InputStream decodingStream = encoding.decodingStream(new StringReader(encoded))) {
+ for (int i = 0; i < bytes.length; i++) {
+ assertThat(decodingStream.read()).isEqualTo(bytes[i] & 0xFF);
+ }
+ assertThat(decodingStream.read()).isEqualTo(-1);
}
- assertThat(decodingStream.read()).isEqualTo(-1);
- decodingStream.close();
}
public void testToString() {
- assertEquals("BaseEncoding.base64().withPadChar('=')", base64().toString());
- assertEquals("BaseEncoding.base32Hex().omitPadding()", base32Hex().omitPadding().toString());
- assertEquals(
- "BaseEncoding.base32().lowerCase().withPadChar('$')",
- base32().lowerCase().withPadChar('$').toString());
- assertEquals(
- "BaseEncoding.base16().withSeparator(\"\n\", 10)",
- base16().withSeparator("\n", 10).toString());
+ assertThat(base64().toString()).isEqualTo("BaseEncoding.base64().withPadChar('=')");
+ assertThat(base32Hex().omitPadding().toString())
+ .isEqualTo("BaseEncoding.base32Hex().omitPadding()");
+ assertThat(base32().lowerCase().withPadChar('$').toString())
+ .isEqualTo("BaseEncoding.base32().lowerCase().withPadChar('$')");
+ assertThat(base16().withSeparator("\n", 10).toString())
+ .isEqualTo("BaseEncoding.base16().withSeparator(\"\n\", 10)");
}
}
diff --git a/guava-tests/test/com/google/common/io/ByteSinkTester.java b/guava-tests/test/com/google/common/io/ByteSinkTester.java
index a8ed36f81..6baf3779d 100644
--- a/guava-tests/test/com/google/common/io/ByteSinkTester.java
+++ b/guava-tests/test/com/google/common/io/ByteSinkTester.java
@@ -31,12 +31,12 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code ByteSink} implementations.
- * Generates tests of a all methods on a {@code ByteSink} given various inputs written to it as well
+ * Generates tests of all methods on a {@code ByteSink} given various inputs written to it as well
* as sub-suites for testing the {@code CharSink} view in the same way.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class ByteSinkTester extends SourceSinkTester<ByteSink, byte[], ByteSinkFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(ByteSinkTester.class);
diff --git a/guava-tests/test/com/google/common/io/ByteSourceTest.java b/guava-tests/test/com/google/common/io/ByteSourceTest.java
index 3cf6cca44..58ad653c2 100644
--- a/guava-tests/test/com/google/common/io/ByteSourceTest.java
+++ b/guava-tests/test/com/google/common/io/ByteSourceTest.java
@@ -40,6 +40,7 @@ import java.io.OutputStream;
import java.util.Arrays;
import java.util.EnumSet;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for the default implementations of {@code ByteSource} methods.
@@ -151,8 +152,8 @@ public class ByteSourceTest extends IoTestCase {
}
public void testRead_withProcessor_stopsOnFalse() throws IOException {
- ByteProcessor<Void> processor =
- new ByteProcessor<Void>() {
+ ByteProcessor<@Nullable Void> processor =
+ new ByteProcessor<@Nullable Void>() {
boolean firstCall = true;
@Override
@@ -163,7 +164,7 @@ public class ByteSourceTest extends IoTestCase {
}
@Override
- public Void getResult() {
+ public @Nullable Void getResult() {
return null;
}
};
@@ -473,7 +474,9 @@ public class ByteSourceTest extends IoTestCase {
}
}
- /** @return the number of exceptions that were suppressed on the expected thrown exception */
+ /**
+ * @return the number of exceptions that were suppressed on the expected thrown exception
+ */
private static int runSuppressionFailureTest(ByteSource in, ByteSink out) {
try {
in.copyTo(out);
diff --git a/guava-tests/test/com/google/common/io/ByteSourceTester.java b/guava-tests/test/com/google/common/io/ByteSourceTester.java
index 758541256..fe10810f6 100644
--- a/guava-tests/test/com/google/common/io/ByteSourceTester.java
+++ b/guava-tests/test/com/google/common/io/ByteSourceTester.java
@@ -37,13 +37,13 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code ByteSource} implementations.
- * Generates tests of a all methods on a {@code ByteSource} given various inputs the source is
+ * Generates tests of all methods on a {@code ByteSource} given various inputs the source is
* expected to contain as well as sub-suites for testing the {@code CharSource} view and {@code
* slice()} views in the same way.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class ByteSourceTester extends SourceSinkTester<ByteSource, byte[], ByteSourceFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(ByteSourceTester.class);
diff --git a/guava-tests/test/com/google/common/io/ByteStreamsTest.java b/guava-tests/test/com/google/common/io/ByteStreamsTest.java
index dddae1ffc..2598b9fed 100644
--- a/guava-tests/test/com/google/common/io/ByteStreamsTest.java
+++ b/guava-tests/test/com/google/common/io/ByteStreamsTest.java
@@ -380,7 +380,7 @@ public class ByteStreamsTest extends IoTestCase {
assertThat(out.toByteArray()).isEqualTo(expected);
}
- @AndroidIncompatible // https://code.google.com/p/android/issues/detail?id=196848
+ @AndroidIncompatible // https://issuetracker.google.com/issues/37074504
public void testUtf16Expected() {
byte[] hardcodedExpected = utf16ExpectedWithBom;
byte[] computedExpected = "r\u00C9sum\u00C9".getBytes(Charsets.UTF_16);
diff --git a/guava-tests/test/com/google/common/io/CharSinkTester.java b/guava-tests/test/com/google/common/io/CharSinkTester.java
index d3e7a9027..4c8d3db1b 100644
--- a/guava-tests/test/com/google/common/io/CharSinkTester.java
+++ b/guava-tests/test/com/google/common/io/CharSinkTester.java
@@ -27,11 +27,11 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code CharSink} implementations.
- * Generates tests of a all methods on a {@code CharSink} given various inputs written to it.
+ * Generates tests of all methods on a {@code CharSink} given various inputs written to it.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class CharSinkTester extends SourceSinkTester<CharSink, String, CharSinkFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(CharSinkTester.class);
diff --git a/guava-tests/test/com/google/common/io/CharSourceTester.java b/guava-tests/test/com/google/common/io/CharSourceTester.java
index 2a10de0e8..fc0c16c13 100644
--- a/guava-tests/test/com/google/common/io/CharSourceTester.java
+++ b/guava-tests/test/com/google/common/io/CharSourceTester.java
@@ -36,12 +36,12 @@ import junit.framework.TestSuite;
/**
* A generator of {@code TestSuite} instances for testing {@code CharSource} implementations.
- * Generates tests of a all methods on a {@code CharSource} given various inputs the source is
+ * Generates tests of all methods on a {@code CharSource} given various inputs the source is
* expected to contain.
*
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class CharSourceTester extends SourceSinkTester<CharSource, String, CharSourceFactory> {
private static final ImmutableList<Method> testMethods = getTestMethods(CharSourceTester.class);
diff --git a/guava-tests/test/com/google/common/io/CloserTest.java b/guava-tests/test/com/google/common/io/CloserTest.java
index 3876174ea..f30d771a8 100644
--- a/guava-tests/test/com/google/common/io/CloserTest.java
+++ b/guava-tests/test/com/google/common/io/CloserTest.java
@@ -393,7 +393,7 @@ public class CloserTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof Suppression) {
Suppression other = (Suppression) obj;
return closeable.equals(other.closeable)
diff --git a/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java b/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java
new file mode 100644
index 000000000..4ecdcf8d5
--- /dev/null
+++ b/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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.io;
+
+import static com.google.common.io.FileBackedOutputStreamTest.write;
+
+import com.google.common.testing.GcFinalization;
+import java.io.File;
+
+/**
+ * Android-incompatible tests for {@link FileBackedOutputStream}.
+ *
+ * @author Chris Nokleberg
+ */
+@AndroidIncompatible // Finalization probably just doesn't happen fast enough?
+public class FileBackedOutputStreamAndroidIncompatibleTest extends IoTestCase {
+
+ public void testFinalizeDeletesFile() throws Exception {
+ byte[] data = newPreFilledByteArray(100);
+ FileBackedOutputStream out = new FileBackedOutputStream(0, true);
+
+ write(out, data, 0, 100, true);
+ final File file = out.getFile();
+ assertEquals(100, file.length());
+ assertTrue(file.exists());
+ out.close();
+
+ // Make sure that finalize deletes the file
+ out = null;
+
+ // times out and throws RuntimeException on failure
+ GcFinalization.awaitDone(
+ new GcFinalization.FinalizationPredicate() {
+ @Override
+ public boolean isDone() {
+ return !file.exists();
+ }
+ });
+ }
+}
diff --git a/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java b/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java
index 6841a41a9..3d756a88b 100644
--- a/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java
+++ b/guava-tests/test/com/google/common/io/FileBackedOutputStreamTest.java
@@ -16,16 +16,25 @@
package com.google.common.io;
+import static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
+import static com.google.common.truth.Truth.assertThat;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
+import static org.junit.Assert.assertThrows;
-import com.google.common.testing.GcFinalization;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFileAttributes;
import java.util.Arrays;
/**
* Unit tests for {@link FileBackedOutputStream}.
*
+ * <p>For a tiny bit more testing, see {@link FileBackedOutputStreamAndroidIncompatibleTest}.
+ *
* @author Chris Nokleberg
*/
public class FileBackedOutputStreamTest extends IoTestCase {
@@ -61,10 +70,21 @@ public class FileBackedOutputStreamTest extends IoTestCase {
// Write data to go over the threshold
if (chunk2 > 0) {
+ if (JAVA_IO_TMPDIR.value().equals("/sdcard")) {
+ assertThrows(IOException.class, () -> write(out, data, chunk1, chunk2, singleByte));
+ return;
+ }
write(out, data, chunk1, chunk2, singleByte);
file = out.getFile();
assertEquals(dataSize, file.length());
assertTrue(file.exists());
+ assertThat(file.getName()).contains("FileBackedOutputStream");
+ if (!isAndroid() && !isWindows()) {
+ PosixFileAttributes attributes =
+ java.nio.file.Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class)
+ .readAttributes();
+ assertThat(attributes.permissions()).containsExactly(OWNER_READ, OWNER_WRITE);
+ }
}
out.close();
@@ -79,30 +99,6 @@ public class FileBackedOutputStreamTest extends IoTestCase {
}
- public void testFinalizeDeletesFile() throws Exception {
- byte[] data = newPreFilledByteArray(100);
- FileBackedOutputStream out = new FileBackedOutputStream(0, true);
-
- write(out, data, 0, 100, true);
- final File file = out.getFile();
- assertEquals(100, file.length());
- assertTrue(file.exists());
- out.close();
-
- // Make sure that finalize deletes the file
- out = null;
-
- // times out and throws RuntimeException on failure
- GcFinalization.awaitDone(
- new GcFinalization.FinalizationPredicate() {
- @Override
- public boolean isDone() {
- return !file.exists();
- }
- });
- }
-
-
public void testThreshold_resetOnFinalize() throws Exception {
testThreshold(0, 100, true, true);
testThreshold(10, 100, true, true);
@@ -114,7 +110,7 @@ public class FileBackedOutputStreamTest extends IoTestCase {
testThreshold(1000, 100, false, true);
}
- private static void write(OutputStream out, byte[] b, int off, int len, boolean singleByte)
+ static void write(OutputStream out, byte[] b, int off, int len, boolean singleByte)
throws IOException {
if (singleByte) {
for (int i = off; i < off + len; i++) {
@@ -133,6 +129,10 @@ public class FileBackedOutputStreamTest extends IoTestCase {
FileBackedOutputStream out = new FileBackedOutputStream(50);
ByteSource source = out.asByteSource();
+ if (JAVA_IO_TMPDIR.value().equals("/sdcard")) {
+ assertThrows(IOException.class, () -> out.write(data));
+ return;
+ }
out.write(data);
assertTrue(Arrays.equals(data, source.read()));
@@ -164,4 +164,12 @@ public class FileBackedOutputStreamTest extends IoTestCase {
out.close();
}
+
+ private static boolean isAndroid() {
+ return System.getProperty("java.runtime.name", "").contains("Android");
+ }
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java b/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java
new file mode 100644
index 000000000..a31c43770
--- /dev/null
+++ b/guava-tests/test/com/google/common/io/FilesCreateTempDirTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2007 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.io;
+
+import static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
+import static com.google.common.truth.Truth.assertThat;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
+import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
+import static org.junit.Assert.assertThrows;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFileAttributes;
+import junit.framework.TestCase;
+
+/**
+ * Unit test for {@link Files#createTempDir}.
+ *
+ * @author Chris Nokleberg
+ */
+
+@SuppressWarnings("deprecation") // tests of a deprecated method
+public class FilesCreateTempDirTest extends TestCase {
+ public void testCreateTempDir() throws IOException {
+ if (JAVA_IO_TMPDIR.value().equals("/sdcard")) {
+ assertThrows(IllegalStateException.class, Files::createTempDir);
+ return;
+ }
+ File temp = Files.createTempDir();
+ try {
+ assertThat(temp.exists()).isTrue();
+ assertThat(temp.isDirectory()).isTrue();
+ assertThat(temp.listFiles()).isEmpty();
+ File child = new File(temp, "child");
+ assertThat(child.createNewFile()).isTrue();
+ assertThat(child.delete()).isTrue();
+
+ if (!isAndroid() && !isWindows()) {
+ PosixFileAttributes attributes =
+ java.nio.file.Files.getFileAttributeView(temp.toPath(), PosixFileAttributeView.class)
+ .readAttributes();
+ assertThat(attributes.permissions())
+ .containsExactly(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
+ }
+ } finally {
+ assertThat(temp.delete()).isTrue();
+ }
+ }
+
+ private static boolean isAndroid() {
+ return System.getProperty("java.runtime.name", "").contains("Android");
+ }
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
+}
diff --git a/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java b/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java
index c13240685..9409d216d 100644
--- a/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java
+++ b/guava-tests/test/com/google/common/io/FilesFileTraverserTest.java
@@ -22,11 +22,6 @@ import com.google.common.collect.Iterables;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.File;
import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Path;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-import junit.framework.TestCase;
/**
* Tests for {@link Files#fileTraverser()}.
@@ -34,37 +29,13 @@ import junit.framework.TestCase;
* @author Jens Nyman
*/
-public class FilesFileTraverserTest extends TestCase {
+public class FilesFileTraverserTest extends IoTestCase {
private File rootDir;
@Override
public void setUp() throws IOException {
- rootDir = Files.createTempDir();
- }
-
- @Override
- public void tearDown() throws IOException {
- // delete rootDir and its contents
- java.nio.file.Files.walkFileTree(
- rootDir.toPath(),
- new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
- throws IOException {
- java.nio.file.Files.deleteIfExists(file);
- return FileVisitResult.CONTINUE;
- }
-
- @Override
- public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
- if (exc != null) {
- return FileVisitResult.TERMINATE;
- }
- java.nio.file.Files.deleteIfExists(dir);
- return FileVisitResult.CONTINUE;
- }
- });
+ rootDir = createTempDir();
}
public void testFileTraverser_emptyDirectory() throws Exception {
diff --git a/guava-tests/test/com/google/common/io/FilesTest.java b/guava-tests/test/com/google/common/io/FilesTest.java
index 8446da1d5..6ffcf5c81 100644
--- a/guava-tests/test/com/google/common/io/FilesTest.java
+++ b/guava-tests/test/com/google/common/io/FilesTest.java
@@ -42,13 +42,19 @@ import junit.framework.TestSuite;
/**
* Unit test for {@link Files}.
*
- * <p>Note: {@link Files#fileTraverser()} is tested in {@link FilesFileTraverserTest}.
+ * <p>Some methods are tested in separate files:
+ *
+ * <ul>
+ * <li>{@link Files#fileTraverser()} is tested in {@link FilesFileTraverserTest}.
+ * <li>{@link Files#createTempDir()} is tested in {@link FilesCreateTempDirTest}.
+ * </ul>
*
* @author Chris Nokleberg
*/
public class FilesTest extends IoTestCase {
+ @AndroidIncompatible // suites, ByteSourceTester (b/230620681)
public static TestSuite suite() {
TestSuite suite = new TestSuite();
suite.addTest(
@@ -357,14 +363,6 @@ public class FilesTest extends IoTestCase {
}
}
- public void testCreateTempDir() {
- File temp = Files.createTempDir();
- assertTrue(temp.exists());
- assertTrue(temp.isDirectory());
- assertThat(temp.listFiles()).isEmpty();
- assertTrue(temp.delete());
- }
-
public void testMove() throws IOException {
File i18nFile = getTestFile("i18n.txt");
File temp1 = createTempFile();
diff --git a/guava-tests/test/com/google/common/io/IoTestCase.java b/guava-tests/test/com/google/common/io/IoTestCase.java
index fa8961905..c79ebcbd2 100644
--- a/guava-tests/test/com/google/common/io/IoTestCase.java
+++ b/guava-tests/test/com/google/common/io/IoTestCase.java
@@ -28,6 +28,7 @@ import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base test case class for I/O tests.
@@ -92,7 +93,7 @@ public abstract class IoTestCase extends TestCase {
}
/** Returns the file with the given name under the testdata directory. */
- protected final File getTestFile(String name) throws IOException {
+ protected final @Nullable File getTestFile(String name) throws IOException {
File file = new File(getTestDir(), name);
if (!file.exists()) {
URL resourceUrl = IoTestCase.class.getResource("testdata/" + name);
diff --git a/guava-tests/test/com/google/common/io/MoreFilesTest.java b/guava-tests/test/com/google/common/io/MoreFilesTest.java
index 005cf531d..8076eb352 100644
--- a/guava-tests/test/com/google/common/io/MoreFilesTest.java
+++ b/guava-tests/test/com/google/common/io/MoreFilesTest.java
@@ -16,6 +16,7 @@
package com.google.common.io;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE;
import static com.google.common.jimfs.Feature.SECURE_DIRECTORY_STREAM;
import static com.google.common.jimfs.Feature.SYMBOLIC_LINKS;
@@ -261,6 +262,9 @@ public class MoreFilesTest extends TestCase {
}
public void testCreateParentDirectories_root() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - *Sometimes* fails with "A:\: The device is not ready"
+ }
Path root = root();
assertNull(root.getParent());
assertNull(root.toRealPath().getParent());
@@ -301,6 +305,9 @@ public class MoreFilesTest extends TestCase {
}
public void testCreateParentDirectories_noPermission() {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Create/find a directory that we don't have permissions on?
+ }
Path file = root().resolve("parent/nonexistent.file");
Path parent = file.getParent();
assertFalse(Files.exists(parent));
@@ -325,6 +332,9 @@ public class MoreFilesTest extends TestCase {
}
public void testCreateParentDirectories_symlinkParentExists() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - *Sometimes* fails with FileAlreadyExistsException
+ }
Path symlink = tempDir.resolve("linkToDir");
Files.createSymbolicLink(symlink, root());
Path file = symlink.resolve("foo");
@@ -721,4 +731,8 @@ public class MoreFilesTest extends TestCase {
public abstract void assertDeleteSucceeded(Path path) throws IOException;
}
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/guava-tests/test/com/google/common/io/ResourcesTest.java b/guava-tests/test/com/google/common/io/ResourcesTest.java
index af2abbbc6..b1a46c698 100644
--- a/guava-tests/test/com/google/common/io/ResourcesTest.java
+++ b/guava-tests/test/com/google/common/io/ResourcesTest.java
@@ -22,9 +22,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.NullPointerTester;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -42,6 +40,7 @@ import junit.framework.TestSuite;
public class ResourcesTest extends IoTestCase {
+ @AndroidIncompatible // wouldn't run anyway, but strip the source entirely because of b/230620681
public static TestSuite suite() {
TestSuite suite = new TestSuite();
suite.addTest(
@@ -62,9 +61,9 @@ public class ResourcesTest extends IoTestCase {
assertThat(Resources.toString(resource, Charsets.US_ASCII)).isNotEqualTo(I18N);
}
- public void testToToByteArray() throws IOException {
- byte[] data = Resources.toByteArray(classfile(Resources.class));
- assertEquals(0xCAFEBABE, new DataInputStream(new ByteArrayInputStream(data)).readInt());
+ public void testToByteArray() throws IOException {
+ URL resource = getClass().getResource("testdata/i18n.txt");
+ assertThat(Resources.toByteArray(resource)).isEqualTo(I18N.getBytes(Charsets.UTF_8));
}
public void testReadLines() throws IOException {
@@ -160,7 +159,7 @@ public class ResourcesTest extends IoTestCase {
Thread.currentThread().setContextClassLoader(loader);
URL url = Resources.getResource(tempFile.getName());
String text = Resources.toString(url, Charsets.UTF_8);
- assertEquals("rud a chur ar an méar fhada\n", text);
+ assertEquals("rud a chur ar an méar fhada" + System.lineSeparator(), text);
} finally {
Thread.currentThread().setContextClassLoader(oldContextLoader);
}
@@ -181,6 +180,7 @@ public class ResourcesTest extends IoTestCase {
}
}
+ @AndroidIncompatible // .class files aren't available
public void testNulls() {
new NullPointerTester()
.setDefault(URL.class, classfile(ResourcesTest.class))
diff --git a/guava-tests/test/com/google/common/io/SourceSinkTester.java b/guava-tests/test/com/google/common/io/SourceSinkTester.java
index 55a302f85..544467f9d 100644
--- a/guava-tests/test/com/google/common/io/SourceSinkTester.java
+++ b/guava-tests/test/com/google/common/io/SourceSinkTester.java
@@ -35,7 +35,7 @@ import junit.framework.TestCase;
* @param <F> the factory type
* @author Colin Decker
*/
-@AndroidIncompatible // Android doesn't understand tests that lack default constructors.
+@AndroidIncompatible // TODO(b/230620681): Make this available (even though we won't run it).
public class SourceSinkTester<S, T, F extends SourceSinkFactory<S, T>> extends TestCase {
static final String LOREM_IPSUM =
diff --git a/guava-tests/test/com/google/common/math/BigIntegerMathTest.java b/guava-tests/test/com/google/common/math/BigIntegerMathTest.java
index 170261bb5..2bfe3a325 100644
--- a/guava-tests/test/com/google/common/math/BigIntegerMathTest.java
+++ b/guava-tests/test/com/google/common/math/BigIntegerMathTest.java
@@ -40,7 +40,9 @@ import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
@@ -54,6 +56,7 @@ import junit.framework.TestCase;
*
* @author Louis Wasserman
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class BigIntegerMathTest extends TestCase {
public void testCeilingPowerOfTwo() {
@@ -110,6 +113,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantSqrt2PrecomputedBits() {
assertEquals(
@@ -213,6 +217,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -224,6 +229,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10NegativeAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -235,6 +241,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Floor() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -246,6 +253,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Ceiling() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -258,6 +266,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of log10(BigInteger, FLOOR).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Exact() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -272,6 +281,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10HalfUp() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -284,6 +294,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10HalfDown() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -297,6 +308,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of log10(BigInteger, {HALF_UP,HALF_DOWN}).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10HalfEven() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -308,6 +320,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10TrivialOnPowerOf10() {
BigInteger x = BigInteger.TEN.pow(100);
@@ -316,6 +329,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtZeroAlwaysZero() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -323,6 +337,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtNegativeAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -334,6 +349,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtFloor() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -346,6 +362,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtCeiling() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -359,6 +376,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of sqrt(BigInteger, FLOOR).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtExact() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -374,6 +392,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtHalfUp() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -390,6 +409,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtHalfDown() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -407,6 +427,7 @@ public class BigIntegerMathTest extends TestCase {
}
// Relies on the correctness of sqrt(BigInteger, {HALF_UP,HALF_DOWN}).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtHalfEven() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
@@ -418,6 +439,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // slow
public void testDivNonZero() {
@@ -438,6 +460,7 @@ public class BigIntegerMathTest extends TestCase {
private static final BigInteger BAD_FOR_GINGERBREAD_P = new BigInteger("-9223372036854775808");
private static final BigInteger BAD_FOR_GINGERBREAD_Q = new BigInteger("-4294967296");
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // slow
public void testDivNonZeroExact() {
@@ -469,6 +492,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testZeroDivIsAlwaysZero() {
for (BigInteger q : NONZERO_BIGINTEGER_CANDIDATES) {
@@ -478,6 +502,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testDivByZeroAlwaysFails() {
for (BigInteger p : ALL_BIGINTEGER_CANDIDATES) {
@@ -515,6 +540,7 @@ public class BigIntegerMathTest extends TestCase {
runBinomialTest(0, 30);
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testBinomialLarge() {
runBinomialTest(31, 100);
@@ -548,6 +574,7 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible
private static final class RoundToDoubleTester {
private final BigInteger input;
@@ -558,6 +585,7 @@ public class BigIntegerMathTest extends TestCase {
this.input = input;
}
+ @CanIgnoreReturnValue
RoundToDoubleTester setExpectation(double expectedValue, RoundingMode... modes) {
for (RoundingMode mode : modes) {
Double previous = expectedValues.put(mode, expectedValue);
@@ -568,6 +596,7 @@ public class BigIntegerMathTest extends TestCase {
return this;
}
+ @CanIgnoreReturnValue
public RoundToDoubleTester roundUnnecessaryShouldThrow() {
unnecessaryShouldThrow = true;
return this;
@@ -598,16 +627,19 @@ public class BigIntegerMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_Zero() {
new RoundToDoubleTester(BigInteger.ZERO).setExpectation(0.0, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_smallPositive() {
new RoundToDoubleTester(BigInteger.valueOf(16)).setExpectation(16.0, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxPreciselyRepresentable() {
new RoundToDoubleTester(BigInteger.valueOf(1L << 53))
@@ -615,6 +647,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxPreciselyRepresentablePlusOne() {
double twoToThe53 = Math.pow(2, 53);
@@ -627,6 +660,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_twoToThe54PlusOne() {
double twoToThe54 = Math.pow(2, 54);
@@ -639,6 +673,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_twoToThe54PlusThree() {
double twoToThe54 = Math.pow(2, 54);
@@ -651,6 +686,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_twoToThe54PlusFour() {
new RoundToDoubleTester(BigInteger.valueOf((1L << 54) + 4))
@@ -658,12 +694,14 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxDouble() {
BigInteger maxDoubleAsBI = DoubleMath.roundToBigInteger(Double.MAX_VALUE, UNNECESSARY);
new RoundToDoubleTester(maxDoubleAsBI).setExpectation(Double.MAX_VALUE, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_maxDoublePlusOne() {
BigInteger maxDoubleAsBI =
@@ -675,6 +713,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_wayTooBig() {
BigInteger bi = BigInteger.ONE.shiftLeft(2 * Double.MAX_EXPONENT);
@@ -685,11 +724,13 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_smallNegative() {
new RoundToDoubleTester(BigInteger.valueOf(-16)).setExpectation(-16.0, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minPreciselyRepresentable() {
new RoundToDoubleTester(BigInteger.valueOf(-1L << 53))
@@ -697,6 +738,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minPreciselyRepresentableMinusOne() {
// the representable doubles are -2^53 and -2^53 - 2.
@@ -708,6 +750,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeTwoToThe54MinusOne() {
new RoundToDoubleTester(BigInteger.valueOf((-1L << 54) - 1))
@@ -717,6 +760,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeTwoToThe54MinusThree() {
new RoundToDoubleTester(BigInteger.valueOf((-1L << 54) - 3))
@@ -727,6 +771,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeTwoToThe54MinusFour() {
new RoundToDoubleTester(BigInteger.valueOf((-1L << 54) - 4))
@@ -734,12 +779,14 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minDouble() {
BigInteger minDoubleAsBI = DoubleMath.roundToBigInteger(-Double.MAX_VALUE, UNNECESSARY);
new RoundToDoubleTester(minDoubleAsBI).setExpectation(-Double.MAX_VALUE, values()).test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_minDoubleMinusOne() {
BigInteger minDoubleAsBI =
@@ -751,6 +798,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDouble_negativeWayTooBig() {
BigInteger bi = BigInteger.ONE.shiftLeft(2 * Double.MAX_EXPONENT).negate();
@@ -761,6 +809,7 @@ public class BigIntegerMathTest extends TestCase {
.test();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
@@ -770,6 +819,7 @@ public class BigIntegerMathTest extends TestCase {
tester.testAllPublicStaticMethods(BigIntegerMath.class);
}
+ @J2ktIncompatible
@GwtIncompatible // String.format
private static void failFormat(String template, Object... args) {
fail(String.format(template, args));
diff --git a/guava-tests/test/com/google/common/math/DoubleMathTest.java b/guava-tests/test/com/google/common/math/DoubleMathTest.java
index 724ae96d8..93de8c716 100644
--- a/guava-tests/test/com/google/common/math/DoubleMathTest.java
+++ b/guava-tests/test/com/google/common/math/DoubleMathTest.java
@@ -40,6 +40,7 @@ import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Doubles;
@@ -79,6 +80,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundIntegralDoubleToInt() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -98,6 +100,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundFractionalDoubleToInt() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -120,6 +123,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundExactIntegralDoubleToInt() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -137,6 +141,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundExactFractionalDoubleToIntFails() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -148,6 +153,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundNaNToIntAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -159,6 +165,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToInt(double, RoundingMode)
public void testRoundInfiniteToIntAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -175,6 +182,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundIntegralDoubleToLong() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -194,6 +202,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundFractionalDoubleToLong() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -213,6 +222,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundExactIntegralDoubleToLong() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -231,6 +241,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundExactFractionalDoubleToLongFails() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -242,6 +253,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundNaNToLongAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -253,6 +265,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToLong(double, RoundingMode)
public void testRoundInfiniteToLongAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -269,6 +282,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundIntegralDoubleToBigInteger() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -279,6 +293,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundFractionalDoubleToBigInteger() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -289,6 +304,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundExactIntegralDoubleToBigInteger() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -297,6 +313,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundExactFractionalDoubleToBigIntegerFails() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -308,6 +325,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundNaNToBigIntegerAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -319,6 +337,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundInfiniteToBigIntegerAlwaysFails() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -335,6 +354,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.roundToBigInteger(double, RoundingMode)
public void testRoundLog2Floor() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -344,6 +364,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath
public void testRoundLog2Ceiling() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -354,6 +375,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath
public void testRoundLog2Down() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -370,6 +392,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath
public void testRoundLog2Up() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -386,6 +409,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2Half() {
// We don't expect perfect rounding accuracy.
@@ -404,6 +428,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2Exact() {
for (double x : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -418,6 +443,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2ThrowsOnZerosInfinitiesAndNaN() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -432,6 +458,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.log2(double, RoundingMode)
public void testRoundLog2ThrowsOnNegative() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -445,6 +472,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isPowerOfTwo, DoubleMath.log2(double, RoundingMode), StrictMath
public void testIsPowerOfTwoYes() {
for (int i = -1074; i <= 1023; i++) {
@@ -452,6 +480,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isPowerOfTwo, DoubleMath.log2(double, RoundingMode), StrictMath
public void testIsPowerOfTwo() {
for (double x : ALL_DOUBLE_CANDIDATES) {
@@ -464,6 +493,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // #trueLog2, Math.ulp
public void testLog2Accuracy() {
for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) {
@@ -496,6 +526,7 @@ public class DoubleMathTest extends TestCase {
assertTrue(Double.isNaN(DoubleMath.log2(Double.NaN)));
}
+ @J2ktIncompatible
@GwtIncompatible // StrictMath
private strictfp double trueLog2(double d) {
double trueLog2 = StrictMath.log(d) / StrictMath.log(2);
@@ -514,6 +545,7 @@ public class DoubleMathTest extends TestCase {
return trueLog2;
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isMathematicalInteger
public void testIsMathematicalIntegerIntegral() {
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
@@ -521,6 +553,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isMathematicalInteger
public void testIsMathematicalIntegerFractional() {
for (double d : FRACTIONAL_DOUBLE_CANDIDATES) {
@@ -528,6 +561,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.isMathematicalInteger
public void testIsMathematicalIntegerNotFinite() {
for (double d : Arrays.asList(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN)) {
@@ -535,6 +569,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Math.ulp
public void testFactorial() {
for (int i = 0; i <= DoubleMath.MAX_FACTORIAL; i++) {
@@ -710,6 +745,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_doubleVarargs() {
assertEquals(-1.375, DoubleMath.mean(1.1, -2.2, 4.4, -8.8), 1.0e-10);
@@ -726,18 +762,21 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_intVarargs() {
assertEquals(-13.75, DoubleMath.mean(11, -22, 44, -88), 1.0e-10);
assertEquals(11.0, DoubleMath.mean(11), 1.0e-10);
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_longVarargs() {
assertEquals(-13.75, DoubleMath.mean(11L, -22L, 44L, -88L), 1.0e-10);
assertEquals(11.0, DoubleMath.mean(11L), 1.0e-10);
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_emptyVarargs() {
try {
@@ -747,6 +786,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_doubleIterable() {
assertEquals(-1.375, DoubleMath.mean(ImmutableList.of(1.1, -2.2, 4.4, -8.8)), 1.0e-10);
@@ -768,6 +808,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_intIterable() {
assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11, -22, 44, -88)), 1.0e-10);
@@ -779,6 +820,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_longIterable() {
assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11L, -22L, 44L, -88L)), 1.0e-10);
@@ -790,6 +832,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_intIterator() {
assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11, -22, 44, -88).iterator()), 1.0e-10);
@@ -801,6 +844,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // DoubleMath.mean
public void testMean_longIterator() {
assertEquals(
@@ -813,6 +857,7 @@ public class DoubleMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/math/IntMathTest.java b/guava-tests/test/com/google/common/math/IntMathTest.java
index 4db13adbd..30588875d 100644
--- a/guava-tests/test/com/google/common/math/IntMathTest.java
+++ b/guava-tests/test/com/google/common/math/IntMathTest.java
@@ -30,6 +30,7 @@ import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -110,6 +111,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testConstantMaxPowerOfSqrt2Unsigned() {
assertEquals(
@@ -118,6 +120,7 @@ public class IntMathTest extends TestCase {
/*actual=*/ IntMath.MAX_POWER_OF_SQRT2_UNSIGNED);
}
+ @J2ktIncompatible
@GwtIncompatible // pow()
public void testConstantsPowersOf10() {
for (int i = 0; i < IntMath.powersOf10.length - 1; i++) {
@@ -125,6 +128,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testMaxLog10ForLeadingZeros() {
for (int i = 0; i < Integer.SIZE; i++) {
@@ -134,6 +138,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testConstantsHalfPowersOf10() {
for (int i = 0; i < IntMath.halfPowersOf10.length; i++) {
@@ -160,6 +165,7 @@ public class IntMathTest extends TestCase {
2 * IntMath.biggestBinomials.length, IntMath.biggestBinomials.length)));
}
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testPowersSqrtMaxInt() {
assertEquals(
@@ -180,6 +186,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testIsPowerOfTwo() {
for (int x : ALL_INTEGER_CANDIDATES) {
@@ -212,7 +219,7 @@ public class IntMathTest extends TestCase {
}
}
- // Relies on the correctness of BigIntegrerMath.log2 for all modes except UNNECESSARY.
+ // Relies on the correctness of BigIntegerMath.log2 for all modes except UNNECESSARY.
public void testLog2MatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
@@ -235,6 +242,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // log10
public void testLog10ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -246,6 +254,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // log10
public void testLog10NegativeAlwaysThrows() {
for (int x : NEGATIVE_INTEGER_CANDIDATES) {
@@ -260,6 +269,7 @@ public class IntMathTest extends TestCase {
}
// Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY.
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testLog10MatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -271,6 +281,7 @@ public class IntMathTest extends TestCase {
}
// Relies on the correctness of log10(int, FLOOR) and of pow(int, int).
+ @J2ktIncompatible
@GwtIncompatible // pow()
public void testLog10Exact() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -285,6 +296,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // log10
public void testLog10TrivialOnPowerOfTen() {
int x = 1000000;
@@ -294,6 +306,7 @@ public class IntMathTest extends TestCase {
}
// Simple test to cover sqrt(0) for all types and all modes.
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testSqrtZeroAlwaysZero() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -301,6 +314,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testSqrtNegativeAlwaysThrows() {
for (int x : NEGATIVE_INTEGER_CANDIDATES) {
@@ -315,6 +329,7 @@ public class IntMathTest extends TestCase {
}
/* Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY. */
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testSqrtMatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -328,6 +343,7 @@ public class IntMathTest extends TestCase {
}
/* Relies on the correctness of sqrt(int, FLOOR). */
+ @J2ktIncompatible
@GwtIncompatible // sqrt
public void testSqrtExactMatchesFloorOrThrows() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
@@ -343,6 +359,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // 2147483646^2 expected=4
public void testPow() {
for (int i : ALL_INTEGER_CANDIDATES) {
@@ -353,6 +370,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible // TODO(b/281519661): Fails 2147483646/-2147483648 expected:<1> but was:<-1>
public void testDivNonZero() {
for (int p : NONZERO_INTEGER_CANDIDATES) {
for (int q : NONZERO_INTEGER_CANDIDATES) {
@@ -549,6 +567,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedAdd() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -560,6 +579,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedSubtract() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -575,6 +595,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedMultiply() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -589,6 +610,7 @@ public class IntMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedPow() {
for (int a : ALL_INTEGER_CANDIDATES) {
@@ -674,6 +696,7 @@ public class IntMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testMean() {
// Odd-sized ranges have an obvious mean
@@ -745,6 +768,7 @@ public class IntMathTest extends TestCase {
return big.bitLength() <= 31;
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
@@ -752,6 +776,7 @@ public class IntMathTest extends TestCase {
tester.testAllPublicStaticMethods(IntMath.class);
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrime() {
// Defer correctness tests to Long.isPrime
diff --git a/guava-tests/test/com/google/common/math/LongMathTest.java b/guava-tests/test/com/google/common/math/LongMathTest.java
index 40c2ac9ef..ee6ee1cb8 100644
--- a/guava-tests/test/com/google/common/math/LongMathTest.java
+++ b/guava-tests/test/com/google/common/math/LongMathTest.java
@@ -33,6 +33,7 @@ import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -54,6 +55,7 @@ public class LongMathTest extends TestCase {
assertFalse(LongMath.isPowerOfTwo(LongMath.MAX_SIGNED_POWER_OF_TWO * 2));
}
+ @J2ktIncompatible // TODO(b/281519661): expected:<-2147483648> but was:<2147483648>
public void testCeilingPowerOfTwo() {
for (long x : POSITIVE_LONG_CANDIDATES) {
BigInteger expectedResult = BigIntegerMath.ceilingPowerOfTwo(BigInteger.valueOf(x));
@@ -69,6 +71,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/281519661): expected:<-2147483648> but was:<2147483648>
public void testFloorPowerOfTwo() {
for (long x : POSITIVE_LONG_CANDIDATES) {
BigInteger expectedResult = BigIntegerMath.floorPowerOfTwo(BigInteger.valueOf(x));
@@ -112,6 +115,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantMaxPowerOfSqrt2Unsigned() {
assertEquals(
@@ -120,6 +124,7 @@ public class LongMathTest extends TestCase {
/*actual=*/ LongMath.MAX_POWER_OF_SQRT2_UNSIGNED);
}
+ @J2ktIncompatible
@GwtIncompatible // BigIntegerMath // TODO(cpovirk): GWT-enable BigIntegerMath
public void testMaxLog10ForLeadingZeros() {
for (int i = 0; i < Long.SIZE; i++) {
@@ -129,6 +134,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsPowersOf10() {
for (int i = 0; i < LongMath.powersOf10.length; i++) {
@@ -141,6 +147,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsHalfPowersOf10() {
for (int i = 0; i < LongMath.halfPowersOf10.length; i++) {
@@ -153,6 +160,7 @@ public class LongMathTest extends TestCase {
assertTrue(nextBigger.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0);
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsSqrtMaxLong() {
assertEquals(
@@ -160,6 +168,7 @@ public class LongMathTest extends TestCase {
/*actual=*/ LongMath.FLOOR_SQRT_MAX_LONG);
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsFactorials() {
long expected = 1;
@@ -174,6 +183,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsBiggestBinomials() {
for (int k = 0; k < LongMath.biggestBinomials.length; k++) {
@@ -189,6 +199,7 @@ public class LongMathTest extends TestCase {
// 2 * k is the smallest value for which we don't replace k with (n-k).
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testConstantsBiggestSimpleBinomials() {
for (int k = 0; k < LongMath.biggestSimpleBinomials.length; k++) {
@@ -227,6 +238,7 @@ public class LongMathTest extends TestCase {
}
// Throws an ArithmeticException if "the simple implementation" of binomial coefficients overflows
+ @J2ktIncompatible
@GwtIncompatible // TODO
private long simpleBinomial(int n, int k) {
long accum = 1;
@@ -237,6 +249,7 @@ public class LongMathTest extends TestCase {
return accum;
}
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testIsPowerOfTwo() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -293,6 +306,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
@@ -304,6 +318,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10NegativeAlwaysThrows() {
for (long x : NEGATIVE_LONG_CANDIDATES) {
@@ -318,6 +333,7 @@ public class LongMathTest extends TestCase {
}
// Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY.
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10MatchesBigInteger() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -328,6 +344,7 @@ public class LongMathTest extends TestCase {
}
// Relies on the correctness of log10(long, FLOOR) and of pow(long, int).
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10Exact() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -344,6 +361,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testLog10TrivialOnPowerOf10() {
long x = 1000000000000L;
@@ -352,6 +370,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtNegativeAlwaysThrows() {
for (long x : NEGATIVE_LONG_CANDIDATES) {
@@ -366,6 +385,7 @@ public class LongMathTest extends TestCase {
}
// Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY.
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtMatchesBigInteger() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -378,6 +398,7 @@ public class LongMathTest extends TestCase {
}
/* Relies on the correctness of sqrt(long, FLOOR). */
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSqrtExactMatchesFloorOrThrows() {
for (long x : POSITIVE_LONG_CANDIDATES) {
@@ -393,6 +414,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testPow() {
for (long i : ALL_LONG_CANDIDATES) {
@@ -402,6 +424,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // TODO(cpovirk): File BigDecimal.divide() rounding bug.
public void testDivNonZero() {
@@ -419,6 +442,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // Bug in older versions of Android we test against, since fixed.
public void testDivNonZeroExact() {
@@ -439,6 +463,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testZeroDivIsAlwaysZero() {
for (long q : NONZERO_LONG_CANDIDATES) {
@@ -448,6 +473,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testDivByZeroAlwaysFails() {
for (long p : ALL_LONG_CANDIDATES) {
@@ -461,6 +487,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testIntMod() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -470,6 +497,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testIntModNegativeModulusFails() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -483,6 +511,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testIntModZeroModulusFails() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -495,6 +524,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testMod() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -504,6 +534,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testModNegativeModulusFails() {
for (long x : ALL_LONG_CANDIDATES) {
@@ -517,6 +548,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/281519661): expected:<14> but was:<2>
public void testGCDExhaustive() {
for (long a : POSITIVE_LONG_CANDIDATES) {
for (long b : POSITIVE_LONG_CANDIDATES) {
@@ -525,6 +557,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testGCDZero() {
for (long a : POSITIVE_LONG_CANDIDATES) {
@@ -534,6 +567,7 @@ public class LongMathTest extends TestCase {
assertEquals(0, LongMath.gcd(0, 0));
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testGCDNegativePositiveThrows() {
for (long a : NEGATIVE_LONG_CANDIDATES) {
@@ -550,6 +584,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testGCDNegativeZeroThrows() {
for (long a : NEGATIVE_LONG_CANDIDATES) {
@@ -567,7 +602,6 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
- @GwtIncompatible // TODO
public void testCheckedAdd() {
for (long a : ALL_LONG_CANDIDATES) {
for (long b : ALL_LONG_CANDIDATES) {
@@ -586,6 +620,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
@AndroidIncompatible // slow
public void testCheckedSubtract() {
@@ -638,6 +673,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testCheckedPow() {
for (long b : ALL_LONG_CANDIDATES) {
@@ -659,6 +695,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedAdd() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -670,6 +707,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedSubtract() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -685,6 +723,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedMultiply() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -699,6 +738,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testSaturatedPow() {
for (long a : ALL_LONG_CANDIDATES) {
@@ -716,6 +756,7 @@ public class LongMathTest extends TestCase {
}
// Depends on the correctness of BigIntegerMath.factorial.
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testFactorial() {
for (int n = 0; n <= 50; n++) {
@@ -725,6 +766,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
public void testFactorialNegative() {
for (int n : NEGATIVE_INTEGER_CANDIDATES) {
@@ -737,6 +779,7 @@ public class LongMathTest extends TestCase {
}
// Depends on the correctness of BigIntegerMath.binomial.
+ @J2ktIncompatible // TODO(b/281519661): expected:<-2091005866> but was:<2203961430>
public void testBinomial() {
for (int n = 0; n <= 70; n++) {
for (int k = 0; k <= n; k++) {
@@ -748,6 +791,7 @@ public class LongMathTest extends TestCase {
}
+ @J2ktIncompatible
@GwtIncompatible // Slow
public void testBinomial_exhaustiveNotOverflowing() {
// Tests all of the inputs to LongMath.binomial that won't cause it to overflow, that weren't
@@ -785,6 +829,7 @@ public class LongMathTest extends TestCase {
}
+ @J2ktIncompatible
@GwtIncompatible // far too slow
public void testSqrtOfPerfectSquareAsDoubleIsPerfect() {
// This takes just over a minute on my machine.
@@ -800,6 +845,7 @@ public class LongMathTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // java.math.BigInteger
public void testMean() {
// Odd-sized ranges have an obvious mean
@@ -884,6 +930,7 @@ public class LongMathTest extends TestCase {
return big.longValue();
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
@@ -892,6 +939,7 @@ public class LongMathTest extends TestCase {
tester.testAllPublicStaticMethods(LongMath.class);
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeSmall() {
// Check the first 1000 integers
@@ -900,6 +948,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeManyConstants() {
// Test the thorough test inputs, which also includes special constants in the Miller-Rabin
@@ -909,6 +958,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeOnUniformRandom() {
Random rand = new Random(1);
@@ -921,6 +971,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeOnRandomPrimes() {
Random rand = new Random(1);
@@ -932,6 +983,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeOnRandomComposites() {
Random rand = new Random(1);
@@ -944,6 +996,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // isPrime is GWT-incompatible
public void testIsPrimeThrowsOnNegative() {
try {
@@ -989,6 +1042,7 @@ public class LongMathTest extends TestCase {
Long.MIN_VALUE
};
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDoubleAgainstBigInteger() {
for (RoundingMode roundingMode : EnumSet.complementOf(EnumSet.of(UNNECESSARY))) {
@@ -999,6 +1053,7 @@ public class LongMathTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible
public void testRoundToDoubleAgainstBigIntegerUnnecessary() {
for (long candidate : roundToDoubleTestCandidates) {
diff --git a/guava-tests/test/com/google/common/math/MathPreconditionsTest.java b/guava-tests/test/com/google/common/math/MathPreconditionsTest.java
index 5dbe017c1..46c70a3a6 100644
--- a/guava-tests/test/com/google/common/math/MathPreconditionsTest.java
+++ b/guava-tests/test/com/google/common/math/MathPreconditionsTest.java
@@ -103,7 +103,7 @@ public class MathPreconditionsTest extends TestCase {
}
}
- public void testCheckPositive_postiveBigInteger() {
+ public void testCheckPositive_positiveBigInteger() {
MathPreconditions.checkPositive("BigInteger", BigInteger.ONE);
}
@@ -251,7 +251,7 @@ public class MathPreconditionsTest extends TestCase {
}
}
- public void testCheckRoundingUnnnecessary_success() {
+ public void testCheckRoundingUnnecessary_success() {
MathPreconditions.checkRoundingUnnecessary(true);
}
diff --git a/guava-tests/test/com/google/common/math/MathTesting.java b/guava-tests/test/com/google/common/math/MathTesting.java
index 6b74f11ee..0e49835d8 100644
--- a/guava-tests/test/com/google/common/math/MathTesting.java
+++ b/guava-tests/test/com/google/common/math/MathTesting.java
@@ -150,7 +150,7 @@ public class MathTesting {
static {
ImmutableSet.Builder<Long> longValues = ImmutableSet.builder();
- // First of all add all the integer candidate values.
+ // First add all the integer candidate values.
longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG));
// Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63).
longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE);
@@ -185,7 +185,7 @@ public class MathTesting {
static {
ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder();
- // First of all add all the long candidate values.
+ // First add all the long candidate values.
bigValues.addAll(Iterables.transform(POSITIVE_LONG_CANDIDATES, TO_BIGINTEGER));
// Add boundary values manually to avoid over/under flow.
bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE));
diff --git a/guava-tests/test/com/google/common/math/QuantilesTest.java b/guava-tests/test/com/google/common/math/QuantilesTest.java
index e5d113dfc..9c8d8e65a 100644
--- a/guava-tests/test/com/google/common/math/QuantilesTest.java
+++ b/guava-tests/test/com/google/common/math/QuantilesTest.java
@@ -424,12 +424,12 @@ public class QuantilesTest extends TestCase {
1, 1.5,
2, 2.0,
8, 5.0,
- 9, POSITIVE_INFINITY, // interpolating between 5.0 and POSITIVE_INFNINITY
+ 9, POSITIVE_INFINITY, // interpolating between 5.0 and POSITIVE_INFINITY
10, POSITIVE_INFINITY);
}
public void testScale_index_compute_doubleCollection_positiveInfinity() {
- // interpolating between 5.0 and POSITIVE_INFNINITY
+ // interpolating between 5.0 and POSITIVE_INFINITY
assertThat(Quantiles.scale(10).index(9).compute(ONE_TO_FIVE_AND_POSITIVE_INFINITY))
.isPositiveInfinity();
}
@@ -442,7 +442,7 @@ public class QuantilesTest extends TestCase {
.comparingValuesUsing(QUANTILE_CORRESPONDENCE)
.containsExactly(
0, NEGATIVE_INFINITY,
- 1, NEGATIVE_INFINITY, // interpolating between NEGATIVE_INFNINITY and 1.0
+ 1, NEGATIVE_INFINITY, // interpolating between NEGATIVE_INFINITY and 1.0
2, 1.0,
8, 4.0,
9, 4.5,
@@ -450,7 +450,7 @@ public class QuantilesTest extends TestCase {
}
public void testScale_index_compute_doubleCollection_negativeInfinity() {
- // interpolating between NEGATIVE_INFNINITY and 1.0
+ // interpolating between NEGATIVE_INFINITY and 1.0
assertThat(Quantiles.scale(10).index(1).compute(ONE_TO_FIVE_AND_NEGATIVE_INFINITY))
.isNegativeInfinity();
}
@@ -540,7 +540,7 @@ public class QuantilesTest extends TestCase {
// Assert that the dataset contains the same elements after the in-place computation (although
// they may be reordered). We only do this for one index rather than for all indexes, as it is
- // quite expensives (quadratic in the size of PSEUDORANDOM_DATASET).
+ // quite expensive (quadratic in the size of PSEUDORANDOM_DATASET).
double[] dataset = Doubles.toArray(PSEUDORANDOM_DATASET);
@SuppressWarnings("unused")
double actual = percentiles().index(33).computeInPlace(dataset);
diff --git a/guava-tests/test/com/google/common/math/StatsTesting.java b/guava-tests/test/com/google/common/math/StatsTesting.java
index 261cdd4b1..9652a6af3 100644
--- a/guava-tests/test/com/google/common/math/StatsTesting.java
+++ b/guava-tests/test/com/google/common/math/StatsTesting.java
@@ -64,7 +64,7 @@ class StatsTesting {
+ (-56.78 - TWO_VALUES_MEAN) * (-789.012 - OTHER_TWO_VALUES_MEAN);
/**
- * Helper class for testing with non-finite values. {@link #ALL_MANY_VALUES} gives a number
+ * Helper class for testing with non-finite values. {@link #ALL_MANY_VALUES} gives a number of
* instances with many combinations of finite and non-finite values. All have {@link
* #MANY_VALUES_COUNT} values. If all the values are finite then the mean is {@link
* #MANY_VALUES_MEAN} and the sum-of-squares-of-deltas is {@link
@@ -214,7 +214,7 @@ class StatsTesting {
/**
* Returns a stream of a million primitive doubles. The stream is parallel, which should cause
- * {@code collect} calls to run in multi-threaded mode, so testing the combiner as well as the
+ * {@code collect} calls to run in multithreaded mode, so testing the combiner as well as the
* supplier and accumulator.
*/
static DoubleStream megaPrimitiveDoubleStream() {
@@ -396,7 +396,7 @@ class StatsTesting {
}
/**
- * Asserts that {@code transformation} is diagonal (i.e. neither horizontal or vertical) and
+ * Asserts that {@code transformation} is diagonal (i.e. neither horizontal nor vertical) and
* passes through both {@code (x1, y1)} and {@code (x1 + xDelta, y1 + yDelta)}. Includes
* assertions about all the public instance methods of {@link LinearTransformation} (on both
* {@code transformation} and its inverse). Since the transformation is expected to be diagonal,
diff --git a/guava-tests/test/com/google/common/math/TestPlatform.java b/guava-tests/test/com/google/common/math/TestPlatform.java
index 03eb2ec0d..86d8e50a6 100644
--- a/guava-tests/test/com/google/common/math/TestPlatform.java
+++ b/guava-tests/test/com/google/common/math/TestPlatform.java
@@ -26,6 +26,6 @@ class TestPlatform {
}
static boolean isAndroid() {
- return System.getProperty("java.runtime.name").contains("Android");
+ return System.getProperty("java.runtime.name", "").contains("Android");
}
}
diff --git a/guava-tests/test/com/google/common/net/HostAndPortTest.java b/guava-tests/test/com/google/common/net/HostAndPortTest.java
index 65e80962b..7d36d18f4 100644
--- a/guava-tests/test/com/google/common/net/HostAndPortTest.java
+++ b/guava-tests/test/com/google/common/net/HostAndPortTest.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link HostAndPort}
@@ -99,10 +100,17 @@ public class HostAndPortTest extends TestCase {
checkFromStringCase("\nOMG\t", 89, "\nOMG\t", 89, false);
}
+ public void testFromStringParseableIncompleteAddresses() {
+ checkFromStringCase("1.2.3", 87, "1.2.3", 87, false);
+ checkFromStringCase("1.2.3:99", 87, "1.2.3", 99, true);
+ checkFromStringCase("2001:4860:4864:5", 87, "2001:4860:4864:5", 87, false);
+ checkFromStringCase("[2001:4860:4864:5]:99", 87, "2001:4860:4864:5", 99, true);
+ }
+
private static void checkFromStringCase(
String hpString,
int defaultPort,
- String expectHost,
+ @Nullable String expectHost,
int expectPort,
boolean expectHasExplicitPort) {
HostAndPort hp;
diff --git a/guava-tests/test/com/google/common/net/HttpHeadersTest.java b/guava-tests/test/com/google/common/net/HttpHeadersTest.java
index 5361b3fce..ef32ccfe3 100644
--- a/guava-tests/test/com/google/common/net/HttpHeadersTest.java
+++ b/guava-tests/test/com/google/common/net/HttpHeadersTest.java
@@ -40,6 +40,7 @@ public class HttpHeadersTest extends TestCase {
.put("CDN_LOOP", "CDN-Loop")
.put("ETAG", "ETag")
.put("SOURCE_MAP", "SourceMap")
+ .put("SEC_CH_UA_WOW64", "Sec-CH-UA-WoW64")
.put("SEC_WEBSOCKET_ACCEPT", "Sec-WebSocket-Accept")
.put("SEC_WEBSOCKET_EXTENSIONS", "Sec-WebSocket-Extensions")
.put("SEC_WEBSOCKET_KEY", "Sec-WebSocket-Key")
@@ -47,11 +48,11 @@ public class HttpHeadersTest extends TestCase {
.put("SEC_WEBSOCKET_VERSION", "Sec-WebSocket-Version")
.put("X_WEBKIT_CSP", "X-WebKit-CSP")
.put("X_WEBKIT_CSP_REPORT_ONLY", "X-WebKit-CSP-Report-Only")
- .build();
+ .buildOrThrow();
ImmutableSet<String> uppercaseAcronyms =
ImmutableSet.of(
- "CH", "ID", "DNT", "DNS", "ECT", "HTTP2", "IP", "MD5", "P3P", "RTT", "TE", "UA", "UID",
- "URL", "WWW", "XSS");
+ "CH", "ID", "DNT", "DNS", "DPR", "ECT", "HTTP2", "IP", "MD5", "P3P", "RTT", "TE", "UA",
+ "UID", "URL", "WWW", "XSS");
assertConstantNameMatchesString(HttpHeaders.class, specialCases, uppercaseAcronyms);
}
diff --git a/guava-tests/test/com/google/common/net/InetAddressesTest.java b/guava-tests/test/com/google/common/net/InetAddressesTest.java
index be77e7b17..7d070e404 100644
--- a/guava-tests/test/com/google/common/net/InetAddressesTest.java
+++ b/guava-tests/test/com/google/common/net/InetAddressesTest.java
@@ -645,7 +645,7 @@ public class InetAddressesTest extends TestCase {
InetAddresses.getCoercedIPv4Address(
InetAddresses.forString("2001:0000:4136:e378:8000:63bf:3fff:fdd3")));
- // 2 Teredo addresses NOT differing in the their embedded IPv4 addresses should hash to the same
+ // 2 Teredo addresses NOT differing in their embedded IPv4 addresses should hash to the same
// value.
assertThat(
InetAddresses.getCoercedIPv4Address(
diff --git a/guava-tests/test/com/google/common/net/PercentEscaperTest.java b/guava-tests/test/com/google/common/net/PercentEscaperTest.java
index e600e4c7c..a8b6e2541 100644
--- a/guava-tests/test/com/google/common/net/PercentEscaperTest.java
+++ b/guava-tests/test/com/google/common/net/PercentEscaperTest.java
@@ -45,7 +45,7 @@ public class PercentEscaperTest extends TestCase {
}
}
- // Testing mutlibyte escape sequences
+ // Testing multibyte escape sequences
assertEscaping(e, "%00", '\u0000'); // nul
assertEscaping(e, "%7F", '\u007f'); // del
assertEscaping(e, "%C2%80", '\u0080'); // xx-00010,x-000000
diff --git a/guava-tests/test/com/google/common/primitives/BooleansTest.java b/guava-tests/test/com/google/common/primitives/BooleansTest.java
index 43ec04c4a..1b39ef715 100644
--- a/guava-tests/test/com/google/common/primitives/BooleansTest.java
+++ b/guava-tests/test/com/google/common/primitives/BooleansTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -27,6 +31,7 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Booleans}.
@@ -34,6 +39,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
public class BooleansTest extends TestCase {
private static final boolean[] EMPTY = {};
private static final boolean[] ARRAY_FALSE = {false};
@@ -43,96 +49,94 @@ public class BooleansTest extends TestCase {
private static final boolean[] VALUES = {false, true};
+ @J2ktIncompatible // TODO(b/285538920): Fix and enable.
public void testHashCode() {
- assertEquals(Boolean.TRUE.hashCode(), Booleans.hashCode(true));
- assertEquals(Boolean.FALSE.hashCode(), Booleans.hashCode(false));
+ assertThat(Booleans.hashCode(true)).isEqualTo(Boolean.TRUE.hashCode());
+ assertThat(Booleans.hashCode(false)).isEqualTo(Boolean.FALSE.hashCode());
}
public void testTrueFirst() {
- assertEquals(0, Booleans.trueFirst().compare(true, true));
- assertEquals(0, Booleans.trueFirst().compare(false, false));
- assertTrue(Booleans.trueFirst().compare(true, false) < 0);
- assertTrue(Booleans.trueFirst().compare(false, true) > 0);
+ assertThat(Booleans.trueFirst().compare(true, true)).isEqualTo(0);
+ assertThat(Booleans.trueFirst().compare(false, false)).isEqualTo(0);
+ assertThat(Booleans.trueFirst().compare(true, false)).isLessThan(0);
+ assertThat(Booleans.trueFirst().compare(false, true)).isGreaterThan(0);
}
public void testFalseFirst() {
- assertEquals(0, Booleans.falseFirst().compare(true, true));
- assertEquals(0, Booleans.falseFirst().compare(false, false));
- assertTrue(Booleans.falseFirst().compare(false, true) < 0);
- assertTrue(Booleans.falseFirst().compare(true, false) > 0);
+ assertThat(Booleans.falseFirst().compare(true, true)).isEqualTo(0);
+ assertThat(Booleans.falseFirst().compare(false, false)).isEqualTo(0);
+ assertThat(Booleans.falseFirst().compare(false, true)).isLessThan(0);
+ assertThat(Booleans.falseFirst().compare(true, false)).isGreaterThan(0);
}
public void testCompare() {
for (boolean x : VALUES) {
for (boolean y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Boolean.valueOf(x).compareTo(y), Booleans.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Booleans.compare(x, y))
+ .isEqualTo(Boolean.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Booleans.contains(EMPTY, false));
- assertFalse(Booleans.contains(ARRAY_FALSE, true));
- assertTrue(Booleans.contains(ARRAY_FALSE, false));
- assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, false));
- assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, true));
+ assertThat(Booleans.contains(EMPTY, false)).isFalse();
+ assertThat(Booleans.contains(ARRAY_FALSE, true)).isFalse();
+ assertThat(Booleans.contains(ARRAY_FALSE, false)).isTrue();
+ assertThat(Booleans.contains(ARRAY_FALSE_TRUE, false)).isTrue();
+ assertThat(Booleans.contains(ARRAY_FALSE_TRUE, true)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Booleans.indexOf(EMPTY, ARRAY_FALSE));
- assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE_TRUE));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE_FALSE, ARRAY_FALSE));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_FALSE));
- assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_TRUE));
- assertEquals(0, Booleans.indexOf(ARRAY_TRUE, new boolean[0]));
+ assertThat(Booleans.indexOf(EMPTY, ARRAY_FALSE)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE_TRUE)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_FALSE, ARRAY_FALSE)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_FALSE)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_TRUE)).isEqualTo(1);
+ assertThat(Booleans.indexOf(ARRAY_TRUE, new boolean[0])).isEqualTo(0);
}
public void testIndexOf_arrays() {
- assertEquals(-1, Booleans.indexOf(EMPTY, false));
- assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, true));
- assertEquals(-1, Booleans.indexOf(ARRAY_FALSE_FALSE, true));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE, false));
- assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, false));
- assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, true));
- assertEquals(2, Booleans.indexOf(new boolean[] {false, false, true}, true));
+ assertThat(Booleans.indexOf(EMPTY, false)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.indexOf(ARRAY_FALSE, false)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, false)).isEqualTo(0);
+ assertThat(Booleans.indexOf(ARRAY_FALSE_TRUE, true)).isEqualTo(1);
+ assertThat(Booleans.indexOf(new boolean[] {false, false, true}, true)).isEqualTo(2);
}
public void testLastIndexOf() {
- assertEquals(-1, Booleans.lastIndexOf(EMPTY, false));
- assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE, true));
- assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE_FALSE, true));
- assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE, false));
- assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, false));
- assertEquals(1, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, true));
- assertEquals(2, Booleans.lastIndexOf(new boolean[] {false, true, true}, true));
+ assertThat(Booleans.lastIndexOf(EMPTY, false)).isEqualTo(-1);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE_FALSE, true)).isEqualTo(-1);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE, false)).isEqualTo(0);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE_TRUE, false)).isEqualTo(0);
+ assertThat(Booleans.lastIndexOf(ARRAY_FALSE_TRUE, true)).isEqualTo(1);
+ assertThat(Booleans.lastIndexOf(new boolean[] {false, true, true}, true)).isEqualTo(2);
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Booleans.concat()));
- assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE)));
- assertNotSame(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE));
- assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(EMPTY, ARRAY_FALSE, EMPTY)));
- assertTrue(
- Arrays.equals(
- new boolean[] {false, false, false},
- Booleans.concat(ARRAY_FALSE, ARRAY_FALSE, ARRAY_FALSE)));
- assertTrue(
- Arrays.equals(
- new boolean[] {false, false, true}, Booleans.concat(ARRAY_FALSE, ARRAY_FALSE_TRUE)));
+ assertThat(Booleans.concat()).isEqualTo(EMPTY);
+ assertThat(Booleans.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Booleans.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Booleans.concat(ARRAY_FALSE)).isEqualTo(ARRAY_FALSE);
+ assertThat(Booleans.concat(ARRAY_FALSE)).isNotSameInstanceAs(ARRAY_FALSE);
+ assertThat(Booleans.concat(EMPTY, ARRAY_FALSE, EMPTY)).isEqualTo(ARRAY_FALSE);
+ assertThat(Booleans.concat(ARRAY_FALSE, ARRAY_FALSE, ARRAY_FALSE))
+ .isEqualTo(new boolean[] {false, false, false});
+ assertThat(Booleans.concat(ARRAY_FALSE, ARRAY_FALSE_TRUE))
+ .isEqualTo(new boolean[] {false, false, true});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Booleans.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 0, 1));
- assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 1, 1));
- assertTrue(
- Arrays.equals(
- new boolean[] {true, false, false},
- Booleans.ensureCapacity(new boolean[] {true}, 2, 1)));
+ assertThat(Booleans.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Booleans.ensureCapacity(ARRAY_FALSE, 0, 1)).isSameInstanceAs(ARRAY_FALSE);
+ assertThat(Booleans.ensureCapacity(ARRAY_FALSE, 1, 1)).isSameInstanceAs(ARRAY_FALSE);
+ assertThat(Booleans.ensureCapacity(new boolean[] {true}, 2, 1))
+ .isEqualTo(new boolean[] {true, false, false});
}
public void testEnsureCapacity_fail() {
@@ -150,10 +154,10 @@ public class BooleansTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Booleans.join(",", EMPTY));
- assertEquals("false", Booleans.join(",", ARRAY_FALSE));
- assertEquals("false,true", Booleans.join(",", false, true));
- assertEquals("falsetruefalse", Booleans.join("", false, true, false));
+ assertThat(Booleans.join(",", EMPTY)).isEmpty();
+ assertThat(Booleans.join(",", ARRAY_FALSE)).isEqualTo("false");
+ assertThat(Booleans.join(",", false, true)).isEqualTo("false,true");
+ assertThat(Booleans.join("", false, true, false)).isEqualTo("falsetruefalse");
}
public void testLexicographicalComparator() {
@@ -172,10 +176,11 @@ public class BooleansTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<boolean[]> comparator = Booleans.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -189,14 +194,14 @@ public class BooleansTest extends TestCase {
private static void testReverse(boolean[] input, boolean[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Booleans.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
boolean[] input, int fromIndex, int toIndex, boolean[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Booleans.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -209,20 +214,251 @@ public class BooleansTest extends TestCase {
new boolean[] {true, true, false, false}, 1, 3, new boolean[] {true, false, true, false});
}
+ private static void testRotate(boolean[] input, int distance, boolean[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Booleans.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ boolean[] input, int distance, int fromIndex, int toIndex, boolean[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Booleans.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new boolean[] {}, -1, new boolean[] {});
+ testRotate(new boolean[] {}, 0, new boolean[] {});
+ testRotate(new boolean[] {}, 1, new boolean[] {});
+
+ testRotate(new boolean[] {true}, -2, new boolean[] {true});
+ testRotate(new boolean[] {true}, -1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 0, new boolean[] {true});
+ testRotate(new boolean[] {true}, 1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 2, new boolean[] {true});
+
+ testRotate(new boolean[] {true, false}, -3, new boolean[] {false, true});
+ testRotate(new boolean[] {true, false}, -1, new boolean[] {false, true});
+ testRotate(new boolean[] {true, false}, -2, new boolean[] {true, false});
+ testRotate(new boolean[] {true, false}, 0, new boolean[] {true, false});
+ testRotate(new boolean[] {true, false}, 1, new boolean[] {false, true});
+ testRotate(new boolean[] {true, false}, 2, new boolean[] {true, false});
+ testRotate(new boolean[] {true, false}, 3, new boolean[] {false, true});
+
+ testRotate(new boolean[] {true, false, true}, -5, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, -4, new boolean[] {false, true, true});
+ testRotate(new boolean[] {true, false, true}, -3, new boolean[] {true, false, true});
+ testRotate(new boolean[] {true, false, true}, -2, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, -1, new boolean[] {false, true, true});
+ testRotate(new boolean[] {true, false, true}, 0, new boolean[] {true, false, true});
+ testRotate(new boolean[] {true, false, true}, 1, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, 2, new boolean[] {false, true, true});
+ testRotate(new boolean[] {true, false, true}, 3, new boolean[] {true, false, true});
+ testRotate(new boolean[] {true, false, true}, 4, new boolean[] {true, true, false});
+ testRotate(new boolean[] {true, false, true}, 5, new boolean[] {false, true, true});
+
+ testRotate(
+ new boolean[] {true, false, true, false}, -9, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, -5, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, -1, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, 0, new boolean[] {true, false, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false}, 1, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, 5, new boolean[] {false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false}, 9, new boolean[] {false, true, false, true});
+
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -6,
+ new boolean[] {false, true, false, true, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -4,
+ new boolean[] {true, true, false, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -3,
+ new boolean[] {false, true, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ -1,
+ new boolean[] {false, true, false, true, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 0,
+ new boolean[] {true, false, true, false, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 1,
+ new boolean[] {true, true, false, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 3,
+ new boolean[] {true, false, true, true, false});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 4,
+ new boolean[] {false, true, false, true, true});
+ testRotate(
+ new boolean[] {true, false, true, false, true},
+ 6,
+ new boolean[] {true, true, false, true, false});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new boolean[] {}, 0, 0, 0, new boolean[] {});
+
+ testRotate(new boolean[] {true}, 0, 0, 1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 1, 0, 1, new boolean[] {true});
+ testRotate(new boolean[] {true}, 1, 1, 1, new boolean[] {true});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -6,
+ 1,
+ 6,
+ new boolean[] {false, false, true, false, true, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -1,
+ 1,
+ 6,
+ new boolean[] {false, false, true, false, true, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 0,
+ 1,
+ 6,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 5,
+ 1,
+ 6,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 14,
+ 1,
+ 6,
+ new boolean[] {false, false, true, false, true, true, false});
+
+ // Rotate the first three elements
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -2,
+ 0,
+ 3,
+ new boolean[] {false, false, true, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -1,
+ 0,
+ 3,
+ new boolean[] {true, false, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 0,
+ 0,
+ 3,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 1,
+ 0,
+ 3,
+ new boolean[] {false, false, true, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 2,
+ 0,
+ 3,
+ new boolean[] {true, false, false, true, false, true, false});
+
+ // Rotate the last four elements
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -6,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -5,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -4,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -3,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -2,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ -1,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 0,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 1,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 2,
+ 3,
+ 7,
+ new boolean[] {false, true, false, true, false, true, false});
+ testRotate(
+ new boolean[] {false, true, false, true, false, true, false},
+ 3,
+ 3,
+ 7,
+ new boolean[] {false, true, false, false, true, false, true});
+ }
+
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Boolean> none = Arrays.<Boolean>asList();
- assertTrue(Arrays.equals(EMPTY, Booleans.toArray(none)));
+ assertThat(Booleans.toArray(none)).isEqualTo(EMPTY);
List<Boolean> one = Arrays.asList(false);
- assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.toArray(one)));
+ assertThat(Booleans.toArray(one)).isEqualTo(ARRAY_FALSE);
boolean[] array = {false, false, true};
List<Boolean> three = Arrays.asList(false, false, true);
- assertTrue(Arrays.equals(array, Booleans.toArray(three)));
+ assertThat(Booleans.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Booleans.toArray(Booleans.asList(array))));
+ assertThat(Booleans.toArray(Booleans.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -236,16 +472,16 @@ public class BooleansTest extends TestCase {
Collection<Boolean> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
boolean[] arr = Booleans.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Boolean> list = Arrays.asList(false, true, null);
+ List<@Nullable Boolean> list = Arrays.asList(false, true, null);
try {
Booleans.toArray(list);
fail();
@@ -253,72 +489,80 @@ public class BooleansTest extends TestCase {
}
}
+ @SuppressWarnings({"CollectionIsEmptyTruth", "CollectionIsNotEmptyTruth"})
public void testAsListIsEmpty() {
- assertTrue(Booleans.asList(EMPTY).isEmpty());
- assertFalse(Booleans.asList(ARRAY_FALSE).isEmpty());
+ assertThat(Booleans.asList(EMPTY).isEmpty()).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE).isEmpty()).isFalse();
}
+ @SuppressWarnings("CollectionSizeTruth")
public void testAsListSize() {
- assertEquals(0, Booleans.asList(EMPTY).size());
- assertEquals(1, Booleans.asList(ARRAY_FALSE).size());
- assertEquals(2, Booleans.asList(ARRAY_FALSE_TRUE).size());
+ assertThat(Booleans.asList(EMPTY).size()).isEqualTo(0);
+ assertThat(Booleans.asList(ARRAY_FALSE).size()).isEqualTo(1);
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).size()).isEqualTo(2);
}
+ @SuppressWarnings("BooleanArrayIndexOfBoolean")
public void testAsListIndexOf() {
- assertEquals(-1, Booleans.asList(EMPTY).indexOf((Object) "wrong type"));
- assertEquals(-1, Booleans.asList(EMPTY).indexOf(true));
- assertEquals(-1, Booleans.asList(ARRAY_FALSE).indexOf(true));
- assertEquals(0, Booleans.asList(ARRAY_FALSE).indexOf(false));
- assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).indexOf(true));
+ assertThat(Booleans.asList(EMPTY).indexOf((Object) "wrong type")).isEqualTo(-1);
+ assertThat(Booleans.asList(EMPTY).indexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE).indexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE).indexOf(false)).isEqualTo(0);
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).indexOf(true)).isEqualTo(1);
}
public void testAsListLastIndexOf() {
- assertEquals(-1, Booleans.asList(EMPTY).lastIndexOf((Object) "wrong type"));
- assertEquals(-1, Booleans.asList(EMPTY).lastIndexOf(true));
- assertEquals(-1, Booleans.asList(ARRAY_FALSE).lastIndexOf(true));
- assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true));
- assertEquals(1, Booleans.asList(ARRAY_FALSE_FALSE).lastIndexOf(false));
+ assertThat(Booleans.asList(EMPTY).lastIndexOf((Object) "wrong type")).isEqualTo(-1);
+ assertThat(Booleans.asList(EMPTY).lastIndexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE).lastIndexOf(true)).isEqualTo(-1);
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true)).isEqualTo(1);
+ assertThat(Booleans.asList(ARRAY_FALSE_FALSE).lastIndexOf(false)).isEqualTo(1);
}
+ @SuppressWarnings({"BooleanArrayContainsBoolean", "CollectionDoesNotContainTruth"})
public void testAsListContains() {
- assertFalse(Booleans.asList(EMPTY).contains((Object) "wrong type"));
- assertFalse(Booleans.asList(EMPTY).contains(true));
- assertFalse(Booleans.asList(ARRAY_FALSE).contains(true));
- assertTrue(Booleans.asList(ARRAY_TRUE).contains(true));
- assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(false));
- assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(true));
+ assertThat(Booleans.asList(EMPTY).contains((Object) "wrong type")).isFalse();
+ assertThat(Booleans.asList(EMPTY).contains(true)).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE).contains(true)).isFalse();
+ assertThat(Booleans.asList(ARRAY_TRUE).contains(true)).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).contains(false)).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).contains(true)).isTrue();
}
public void testAsListEquals() {
- assertEquals(Booleans.asList(EMPTY), Collections.emptyList());
- assertEquals(Booleans.asList(ARRAY_FALSE), Booleans.asList(ARRAY_FALSE));
- assertFalse(Booleans.asList(ARRAY_FALSE).equals(ARRAY_FALSE));
- assertFalse(Booleans.asList(ARRAY_FALSE).equals(null));
- assertFalse(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)));
- assertFalse(Booleans.asList(ARRAY_FALSE_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)));
+ assertThat(Booleans.asList(EMPTY).equals(Collections.emptyList())).isTrue();
+ assertThat(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE))).isTrue();
+ @SuppressWarnings("EqualsIncompatibleType")
+ boolean listEqualsArray = Booleans.asList(ARRAY_FALSE).equals(ARRAY_FALSE);
+ assertThat(listEqualsArray).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE).equals(null)).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE))).isFalse();
+ assertThat(Booleans.asList(ARRAY_FALSE_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)))
+ .isFalse();
assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true));
List<Boolean> reference = Booleans.asList(ARRAY_FALSE);
assertEquals(Booleans.asList(ARRAY_FALSE), reference);
// Explicitly call `equals`; `assertEquals` might return fast
- assertTrue(reference.equals(reference));
+ assertThat(reference.equals(reference)).isTrue();
}
public void testAsListHashcode() {
- assertEquals(1, Booleans.asList(EMPTY).hashCode());
- assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), Booleans.asList(ARRAY_FALSE).hashCode());
+ assertThat(Booleans.asList(EMPTY).hashCode()).isEqualTo(1);
+ assertThat(Booleans.asList(ARRAY_FALSE).hashCode())
+ .isEqualTo(Booleans.asList(ARRAY_FALSE).hashCode());
List<Boolean> reference = Booleans.asList(ARRAY_FALSE);
- assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), reference.hashCode());
+ assertThat(reference.hashCode()).isEqualTo(Booleans.asList(ARRAY_FALSE).hashCode());
}
public void testAsListToString() {
- assertEquals("[false]", Booleans.asList(ARRAY_FALSE).toString());
- assertEquals("[false, true]", Booleans.asList(ARRAY_FALSE_TRUE).toString());
+ assertThat(Booleans.asList(ARRAY_FALSE).toString()).isEqualTo("[false]");
+ assertThat(Booleans.asList(ARRAY_FALSE_TRUE).toString()).isEqualTo("[false, true]");
}
public void testAsListSet() {
List<Boolean> list = Booleans.asList(ARRAY_FALSE);
- assertFalse(list.set(0, true));
- assertTrue(list.set(0, false));
+ assertThat(list.set(0, true)).isFalse();
+ assertThat(list.set(0, false)).isTrue();
try {
list.set(0, null);
fail();
@@ -331,14 +575,29 @@ public class BooleansTest extends TestCase {
}
}
+ public void testAsListCanonicalValues() {
+ List<Boolean> list = Booleans.asList(true, false);
+ assertThat(list.get(0)).isSameInstanceAs(true);
+ assertThat(list.get(1)).isSameInstanceAs(false);
+ @SuppressWarnings("deprecation")
+ Boolean anotherTrue = new Boolean(true);
+ @SuppressWarnings("deprecation")
+ Boolean anotherFalse = new Boolean(false);
+ list.set(0, anotherTrue);
+ assertThat(list.get(0)).isSameInstanceAs(true);
+ list.set(1, anotherFalse);
+ assertThat(list.get(1)).isSameInstanceAs(false);
+ }
+
public void testCountTrue() {
- assertEquals(0, Booleans.countTrue());
- assertEquals(0, Booleans.countTrue(false));
- assertEquals(1, Booleans.countTrue(true));
- assertEquals(3, Booleans.countTrue(false, true, false, true, false, true));
- assertEquals(1, Booleans.countTrue(false, false, true, false, false));
+ assertThat(Booleans.countTrue()).isEqualTo(0);
+ assertThat(Booleans.countTrue(false)).isEqualTo(0);
+ assertThat(Booleans.countTrue(true)).isEqualTo(1);
+ assertThat(Booleans.countTrue(false, true, false, true, false, true)).isEqualTo(3);
+ assertThat(Booleans.countTrue(false, false, true, false, false)).isEqualTo(1);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Booleans.class);
diff --git a/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java
index c3d0be1ab..c7e693655 100644
--- a/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/ByteArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class ByteArrayAsListTest extends TestCase {
return Bytes.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Byte>> builders =
diff --git a/guava-tests/test/com/google/common/primitives/BytesTest.java b/guava-tests/test/com/google/common/primitives/BytesTest.java
index 233a0150c..55302d7bc 100644
--- a/guava-tests/test/com/google/common/primitives/BytesTest.java
+++ b/guava-tests/test/com/google/common/primitives/BytesTest.java
@@ -16,8 +16,11 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import java.util.Arrays;
@@ -25,12 +28,14 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Bytes}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
public class BytesTest extends TestCase {
private static final byte[] EMPTY = {};
@@ -41,97 +46,97 @@ public class BytesTest extends TestCase {
public void testHashCode() {
for (byte value : VALUES) {
- assertEquals(((Byte) value).hashCode(), Bytes.hashCode(value));
+ assertThat(Bytes.hashCode(value)).isEqualTo(((Byte) value).hashCode());
}
}
public void testContains() {
- assertFalse(Bytes.contains(EMPTY, (byte) 1));
- assertFalse(Bytes.contains(ARRAY1, (byte) 2));
- assertFalse(Bytes.contains(ARRAY234, (byte) 1));
- assertTrue(Bytes.contains(new byte[] {(byte) -1}, (byte) -1));
- assertTrue(Bytes.contains(ARRAY234, (byte) 2));
- assertTrue(Bytes.contains(ARRAY234, (byte) 3));
- assertTrue(Bytes.contains(ARRAY234, (byte) 4));
+ assertThat(Bytes.contains(EMPTY, (byte) 1)).isFalse();
+ assertThat(Bytes.contains(ARRAY1, (byte) 2)).isFalse();
+ assertThat(Bytes.contains(ARRAY234, (byte) 1)).isFalse();
+ assertThat(Bytes.contains(new byte[] {(byte) -1}, (byte) -1)).isTrue();
+ assertThat(Bytes.contains(ARRAY234, (byte) 2)).isTrue();
+ assertThat(Bytes.contains(ARRAY234, (byte) 3)).isTrue();
+ assertThat(Bytes.contains(ARRAY234, (byte) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Bytes.indexOf(EMPTY, (byte) 1));
- assertEquals(-1, Bytes.indexOf(ARRAY1, (byte) 2));
- assertEquals(-1, Bytes.indexOf(ARRAY234, (byte) 1));
- assertEquals(0, Bytes.indexOf(new byte[] {(byte) -1}, (byte) -1));
- assertEquals(0, Bytes.indexOf(ARRAY234, (byte) 2));
- assertEquals(1, Bytes.indexOf(ARRAY234, (byte) 3));
- assertEquals(2, Bytes.indexOf(ARRAY234, (byte) 4));
- assertEquals(1, Bytes.indexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3));
+ assertThat(Bytes.indexOf(EMPTY, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY1, (byte) 2)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(new byte[] {(byte) -1}, (byte) -1)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 2)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 3)).isEqualTo(1);
+ assertThat(Bytes.indexOf(ARRAY234, (byte) 4)).isEqualTo(2);
+ assertThat(Bytes.indexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Bytes.indexOf(EMPTY, EMPTY));
- assertEquals(0, Bytes.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Bytes.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Bytes.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Bytes.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Bytes.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Bytes.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Bytes.indexOf(ARRAY234, new byte[] {(byte) 2, (byte) 3}));
- assertEquals(1, Bytes.indexOf(ARRAY234, new byte[] {(byte) 3, (byte) 4}));
- assertEquals(1, Bytes.indexOf(ARRAY234, new byte[] {(byte) 3}));
- assertEquals(2, Bytes.indexOf(ARRAY234, new byte[] {(byte) 4}));
- assertEquals(
- 1,
- Bytes.indexOf(
- new byte[] {(byte) 2, (byte) 3, (byte) 3, (byte) 3, (byte) 3}, new byte[] {(byte) 3}));
- assertEquals(
- 2,
- Bytes.indexOf(
- new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3},
- new byte[] {(byte) 2, (byte) 3, (byte) 4}));
- assertEquals(
- 1,
- Bytes.indexOf(
- new byte[] {(byte) 2, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3, (byte) 4},
- new byte[] {(byte) 2, (byte) 3, (byte) 4}));
- assertEquals(
- -1,
- Bytes.indexOf(
- new byte[] {(byte) 4, (byte) 3, (byte) 2}, new byte[] {(byte) 2, (byte) 3, (byte) 4}));
+ assertThat(Bytes.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Bytes.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Bytes.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 2, (byte) 3})).isEqualTo(0);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 3, (byte) 4})).isEqualTo(1);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 3})).isEqualTo(1);
+ assertThat(Bytes.indexOf(ARRAY234, new byte[] {(byte) 4})).isEqualTo(2);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 2, (byte) 3, (byte) 3, (byte) 3, (byte) 3},
+ new byte[] {(byte) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3},
+ new byte[] {(byte) 2, (byte) 3, (byte) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 2, (byte) 2, (byte) 3, (byte) 4, (byte) 2, (byte) 3, (byte) 4},
+ new byte[] {(byte) 2, (byte) 3, (byte) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Bytes.indexOf(
+ new byte[] {(byte) 4, (byte) 3, (byte) 2},
+ new byte[] {(byte) 2, (byte) 3, (byte) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Bytes.lastIndexOf(EMPTY, (byte) 1));
- assertEquals(-1, Bytes.lastIndexOf(ARRAY1, (byte) 2));
- assertEquals(-1, Bytes.lastIndexOf(ARRAY234, (byte) 1));
- assertEquals(0, Bytes.lastIndexOf(new byte[] {(byte) -1}, (byte) -1));
- assertEquals(0, Bytes.lastIndexOf(ARRAY234, (byte) 2));
- assertEquals(1, Bytes.lastIndexOf(ARRAY234, (byte) 3));
- assertEquals(2, Bytes.lastIndexOf(ARRAY234, (byte) 4));
- assertEquals(
- 3, Bytes.lastIndexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3));
+ assertThat(Bytes.lastIndexOf(EMPTY, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.lastIndexOf(ARRAY1, (byte) 2)).isEqualTo(-1);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 1)).isEqualTo(-1);
+ assertThat(Bytes.lastIndexOf(new byte[] {(byte) -1}, (byte) -1)).isEqualTo(0);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 2)).isEqualTo(0);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 3)).isEqualTo(1);
+ assertThat(Bytes.lastIndexOf(ARRAY234, (byte) 4)).isEqualTo(2);
+ assertThat(Bytes.lastIndexOf(new byte[] {(byte) 2, (byte) 3, (byte) 2, (byte) 3}, (byte) 3))
+ .isEqualTo(3);
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Bytes.concat()));
- assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Bytes.concat(ARRAY1)));
- assertNotSame(ARRAY1, Bytes.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Bytes.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 1, (byte) 1, (byte) 1}, Bytes.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 1, (byte) 2, (byte) 3, (byte) 4}, Bytes.concat(ARRAY1, ARRAY234)));
+ assertThat(Bytes.concat()).isEqualTo(EMPTY);
+ assertThat(Bytes.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Bytes.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Bytes.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Bytes.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Bytes.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Bytes.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new byte[] {(byte) 1, (byte) 1, (byte) 1});
+ assertThat(Bytes.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new byte[] {(byte) 1, (byte) 2, (byte) 3, (byte) 4});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Bytes.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 1, (byte) 0, (byte) 0}, Bytes.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Bytes.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Bytes.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Bytes.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Bytes.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new byte[] {(byte) 1, (byte) 0, (byte) 0});
}
public void testEnsureCapacity_fail() {
@@ -151,17 +156,17 @@ public class BytesTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Byte> none = Arrays.<Byte>asList();
- assertTrue(Arrays.equals(EMPTY, Bytes.toArray(none)));
+ assertThat(Bytes.toArray(none)).isEqualTo(EMPTY);
List<Byte> one = Arrays.asList((byte) 1);
- assertTrue(Arrays.equals(ARRAY1, Bytes.toArray(one)));
+ assertThat(Bytes.toArray(one)).isEqualTo(ARRAY1);
byte[] array = {(byte) 0, (byte) 1, (byte) 0x55};
List<Byte> three = Arrays.asList((byte) 0, (byte) 1, (byte) 0x55);
- assertTrue(Arrays.equals(array, Bytes.toArray(three)));
+ assertThat(Bytes.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Bytes.toArray(Bytes.asList(array))));
+ assertThat(Bytes.toArray(Bytes.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -171,16 +176,16 @@ public class BytesTest extends TestCase {
Collection<Byte> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
byte[] arr = Bytes.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Byte> list = Arrays.asList((byte) 0, (byte) 1, null);
+ List<@Nullable Byte> list = Arrays.asList((byte) 0, (byte) 1, null);
try {
Bytes.toArray(list);
fail();
@@ -198,21 +203,22 @@ public class BytesTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Bytes.toArray(bytes)));
- assertTrue(Arrays.equals(array, Bytes.toArray(shorts)));
- assertTrue(Arrays.equals(array, Bytes.toArray(ints)));
- assertTrue(Arrays.equals(array, Bytes.toArray(floats)));
- assertTrue(Arrays.equals(array, Bytes.toArray(longs)));
- assertTrue(Arrays.equals(array, Bytes.toArray(doubles)));
+ assertThat(Bytes.toArray(bytes)).isEqualTo(array);
+ assertThat(Bytes.toArray(shorts)).isEqualTo(array);
+ assertThat(Bytes.toArray(ints)).isEqualTo(array);
+ assertThat(Bytes.toArray(floats)).isEqualTo(array);
+ assertThat(Bytes.toArray(longs)).isEqualTo(array);
+ assertThat(Bytes.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // TODO(b/278877942): Enable
public void testAsList_isAView() {
byte[] array = {(byte) 0, (byte) 1};
List<Byte> list = Bytes.asList(array);
list.set(0, (byte) 2);
- assertTrue(Arrays.equals(new byte[] {(byte) 2, (byte) 1}, array));
+ assertThat(array).isEqualTo(new byte[] {(byte) 2, (byte) 1});
array[1] = (byte) 3;
- assertEquals(Arrays.asList((byte) 2, (byte) 3), list);
+ assertThat(list).containsExactly((byte) 2, (byte) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -222,21 +228,21 @@ public class BytesTest extends TestCase {
// Make sure it returned a copy
list.set(0, (byte) 4);
- assertTrue(Arrays.equals(new byte[] {(byte) 0, (byte) 1, (byte) 2}, newArray));
+ assertThat(newArray).isEqualTo(new byte[] {(byte) 0, (byte) 1, (byte) 2});
newArray[1] = (byte) 5;
- assertEquals((byte) 1, (byte) list.get(1));
+ assertThat((byte) list.get(1)).isEqualTo((byte) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
byte[] array = {(byte) 0, (byte) 1, (byte) 2, (byte) 3};
List<Byte> list = Bytes.asList(array);
- assertTrue(Arrays.equals(new byte[] {(byte) 1, (byte) 2}, Bytes.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new byte[] {}, Bytes.toArray(list.subList(2, 2))));
+ assertThat(Bytes.toArray(list.subList(1, 3))).isEqualTo(new byte[] {(byte) 1, (byte) 2});
+ assertThat(Bytes.toArray(list.subList(2, 2))).isEqualTo(new byte[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Bytes.asList(EMPTY));
+ assertThat(Bytes.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
public void testReverse() {
@@ -250,13 +256,13 @@ public class BytesTest extends TestCase {
private static void testReverse(byte[] input, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Bytes.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(byte[] input, int fromIndex, int toIndex, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Bytes.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -268,6 +274,104 @@ public class BytesTest extends TestCase {
testReverse(new byte[] {-1, 1, -2, 2}, 1, 3, new byte[] {-1, -2, 1, 2});
}
+ private static void testRotate(byte[] input, int distance, byte[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Bytes.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ byte[] input, int distance, int fromIndex, int toIndex, byte[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Bytes.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new byte[] {}, -1, new byte[] {});
+ testRotate(new byte[] {}, 0, new byte[] {});
+ testRotate(new byte[] {}, 1, new byte[] {});
+
+ testRotate(new byte[] {1}, -2, new byte[] {1});
+ testRotate(new byte[] {1}, -1, new byte[] {1});
+ testRotate(new byte[] {1}, 0, new byte[] {1});
+ testRotate(new byte[] {1}, 1, new byte[] {1});
+ testRotate(new byte[] {1}, 2, new byte[] {1});
+
+ testRotate(new byte[] {1, 2}, -3, new byte[] {2, 1});
+ testRotate(new byte[] {1, 2}, -1, new byte[] {2, 1});
+ testRotate(new byte[] {1, 2}, -2, new byte[] {1, 2});
+ testRotate(new byte[] {1, 2}, 0, new byte[] {1, 2});
+ testRotate(new byte[] {1, 2}, 1, new byte[] {2, 1});
+ testRotate(new byte[] {1, 2}, 2, new byte[] {1, 2});
+ testRotate(new byte[] {1, 2}, 3, new byte[] {2, 1});
+
+ testRotate(new byte[] {1, 2, 3}, -5, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, -4, new byte[] {2, 3, 1});
+ testRotate(new byte[] {1, 2, 3}, -3, new byte[] {1, 2, 3});
+ testRotate(new byte[] {1, 2, 3}, -2, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, -1, new byte[] {2, 3, 1});
+ testRotate(new byte[] {1, 2, 3}, 0, new byte[] {1, 2, 3});
+ testRotate(new byte[] {1, 2, 3}, 1, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, 2, new byte[] {2, 3, 1});
+ testRotate(new byte[] {1, 2, 3}, 3, new byte[] {1, 2, 3});
+ testRotate(new byte[] {1, 2, 3}, 4, new byte[] {3, 1, 2});
+ testRotate(new byte[] {1, 2, 3}, 5, new byte[] {2, 3, 1});
+
+ testRotate(new byte[] {1, 2, 3, 4}, -9, new byte[] {2, 3, 4, 1});
+ testRotate(new byte[] {1, 2, 3, 4}, -5, new byte[] {2, 3, 4, 1});
+ testRotate(new byte[] {1, 2, 3, 4}, -1, new byte[] {2, 3, 4, 1});
+ testRotate(new byte[] {1, 2, 3, 4}, 0, new byte[] {1, 2, 3, 4});
+ testRotate(new byte[] {1, 2, 3, 4}, 1, new byte[] {4, 1, 2, 3});
+ testRotate(new byte[] {1, 2, 3, 4}, 5, new byte[] {4, 1, 2, 3});
+ testRotate(new byte[] {1, 2, 3, 4}, 9, new byte[] {4, 1, 2, 3});
+
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -6, new byte[] {2, 3, 4, 5, 1});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -4, new byte[] {5, 1, 2, 3, 4});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -3, new byte[] {4, 5, 1, 2, 3});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, -1, new byte[] {2, 3, 4, 5, 1});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 0, new byte[] {1, 2, 3, 4, 5});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 1, new byte[] {5, 1, 2, 3, 4});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 3, new byte[] {3, 4, 5, 1, 2});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 4, new byte[] {2, 3, 4, 5, 1});
+ testRotate(new byte[] {1, 2, 3, 4, 5}, 6, new byte[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new byte[] {}, 0, 0, 0, new byte[] {});
+
+ testRotate(new byte[] {1}, 0, 0, 1, new byte[] {1});
+ testRotate(new byte[] {1}, 1, 0, 1, new byte[] {1});
+ testRotate(new byte[] {1}, 1, 1, 1, new byte[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new byte[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new byte[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new byte[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new byte[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new byte[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new byte[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new byte[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new byte[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new byte[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new byte[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new byte[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new byte[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new byte[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new byte[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new byte[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new byte[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new byte[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Bytes.class);
diff --git a/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java
index fa2a53dab..7e521f1a7 100644
--- a/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/CharArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class CharArrayAsListTest extends TestCase {
return Chars.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Character>> builders =
diff --git a/guava-tests/test/com/google/common/primitives/CharsTest.java b/guava-tests/test/com/google/common/primitives/CharsTest.java
index f1da7fd8e..7a6280f30 100644
--- a/guava-tests/test/com/google/common/primitives/CharsTest.java
+++ b/guava-tests/test/com/google/common/primitives/CharsTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -28,6 +32,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Chars}.
@@ -35,6 +40,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class CharsTest extends TestCase {
private static final char[] EMPTY = {};
@@ -48,13 +54,13 @@ public class CharsTest extends TestCase {
public void testHashCode() {
for (char value : VALUES) {
- assertEquals(((Character) value).hashCode(), Chars.hashCode(value));
+ assertThat(Chars.hashCode(value)).isEqualTo(((Character) value).hashCode());
}
}
public void testCheckedCast() {
for (char value : VALUES) {
- assertEquals(value, Chars.checkedCast((long) value));
+ assertThat(Chars.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -64,12 +70,12 @@ public class CharsTest extends TestCase {
public void testSaturatedCast() {
for (char value : VALUES) {
- assertEquals(value, Chars.saturatedCast((long) value));
+ assertThat(Chars.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, Chars.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, Chars.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, Chars.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, Chars.saturatedCast(Long.MIN_VALUE));
+ assertThat(Chars.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(Chars.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(Chars.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(Chars.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private void assertCastFails(long value) {
@@ -77,84 +83,90 @@ public class CharsTest extends TestCase {
Chars.checkedCast(value);
fail("Cast to char should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
+ @J2ktIncompatible // TODO(b/285538920): Fix and enable.
public void testCompare() {
for (char x : VALUES) {
for (char y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Character.valueOf(x).compareTo(y), Chars.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Chars.compare(x, y))
+ .isEqualTo(Character.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Chars.contains(EMPTY, (char) 1));
- assertFalse(Chars.contains(ARRAY1, (char) 2));
- assertFalse(Chars.contains(ARRAY234, (char) 1));
- assertTrue(Chars.contains(new char[] {(char) -1}, (char) -1));
- assertTrue(Chars.contains(ARRAY234, (char) 2));
- assertTrue(Chars.contains(ARRAY234, (char) 3));
- assertTrue(Chars.contains(ARRAY234, (char) 4));
+ assertThat(Chars.contains(EMPTY, (char) 1)).isFalse();
+ assertThat(Chars.contains(ARRAY1, (char) 2)).isFalse();
+ assertThat(Chars.contains(ARRAY234, (char) 1)).isFalse();
+ assertThat(Chars.contains(new char[] {(char) -1}, (char) -1)).isTrue();
+ assertThat(Chars.contains(ARRAY234, (char) 2)).isTrue();
+ assertThat(Chars.contains(ARRAY234, (char) 3)).isTrue();
+ assertThat(Chars.contains(ARRAY234, (char) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Chars.indexOf(EMPTY, (char) 1));
- assertEquals(-1, Chars.indexOf(ARRAY1, (char) 2));
- assertEquals(-1, Chars.indexOf(ARRAY234, (char) 1));
- assertEquals(0, Chars.indexOf(new char[] {(char) -1}, (char) -1));
- assertEquals(0, Chars.indexOf(ARRAY234, (char) 2));
- assertEquals(1, Chars.indexOf(ARRAY234, (char) 3));
- assertEquals(2, Chars.indexOf(ARRAY234, (char) 4));
- assertEquals(1, Chars.indexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3));
+ assertThat(Chars.indexOf(EMPTY, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY1, (char) 2)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY234, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.indexOf(new char[] {(char) -1}, (char) -1)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, (char) 2)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, (char) 3)).isEqualTo(1);
+ assertThat(Chars.indexOf(ARRAY234, (char) 4)).isEqualTo(2);
+ assertThat(Chars.indexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Chars.indexOf(EMPTY, EMPTY));
- assertEquals(0, Chars.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Chars.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Chars.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Chars.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Chars.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Chars.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Chars.indexOf(ARRAY234, new char[] {(char) 2, (char) 3}));
- assertEquals(1, Chars.indexOf(ARRAY234, new char[] {(char) 3, (char) 4}));
- assertEquals(1, Chars.indexOf(ARRAY234, new char[] {(char) 3}));
- assertEquals(2, Chars.indexOf(ARRAY234, new char[] {(char) 4}));
- assertEquals(
- 1,
- Chars.indexOf(
- new char[] {(char) 2, (char) 3, (char) 3, (char) 3, (char) 3}, new char[] {(char) 3}));
- assertEquals(
- 2,
- Chars.indexOf(
- new char[] {(char) 2, (char) 3, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3},
- new char[] {(char) 2, (char) 3, (char) 4}));
- assertEquals(
- 1,
- Chars.indexOf(
- new char[] {(char) 2, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3, (char) 4},
- new char[] {(char) 2, (char) 3, (char) 4}));
- assertEquals(
- -1,
- Chars.indexOf(
- new char[] {(char) 4, (char) 3, (char) 2}, new char[] {(char) 2, (char) 3, (char) 4}));
+ assertThat(Chars.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Chars.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Chars.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 2, (char) 3})).isEqualTo(0);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 3, (char) 4})).isEqualTo(1);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 3})).isEqualTo(1);
+ assertThat(Chars.indexOf(ARRAY234, new char[] {(char) 4})).isEqualTo(2);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 2, (char) 3, (char) 3, (char) 3, (char) 3},
+ new char[] {(char) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 2, (char) 3, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3},
+ new char[] {(char) 2, (char) 3, (char) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 2, (char) 2, (char) 3, (char) 4, (char) 2, (char) 3, (char) 4},
+ new char[] {(char) 2, (char) 3, (char) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Chars.indexOf(
+ new char[] {(char) 4, (char) 3, (char) 2},
+ new char[] {(char) 2, (char) 3, (char) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Chars.lastIndexOf(EMPTY, (char) 1));
- assertEquals(-1, Chars.lastIndexOf(ARRAY1, (char) 2));
- assertEquals(-1, Chars.lastIndexOf(ARRAY234, (char) 1));
- assertEquals(0, Chars.lastIndexOf(new char[] {(char) -1}, (char) -1));
- assertEquals(0, Chars.lastIndexOf(ARRAY234, (char) 2));
- assertEquals(1, Chars.lastIndexOf(ARRAY234, (char) 3));
- assertEquals(2, Chars.lastIndexOf(ARRAY234, (char) 4));
- assertEquals(
- 3, Chars.lastIndexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3));
+ assertThat(Chars.lastIndexOf(EMPTY, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.lastIndexOf(ARRAY1, (char) 2)).isEqualTo(-1);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 1)).isEqualTo(-1);
+ assertThat(Chars.lastIndexOf(new char[] {(char) -1}, (char) -1)).isEqualTo(0);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 2)).isEqualTo(0);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 3)).isEqualTo(1);
+ assertThat(Chars.lastIndexOf(ARRAY234, (char) 4)).isEqualTo(2);
+ assertThat(Chars.lastIndexOf(new char[] {(char) 2, (char) 3, (char) 2, (char) 3}, (char) 3))
+ .isEqualTo(3);
}
public void testMax_noArgs() {
@@ -166,10 +178,10 @@ public class CharsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Chars.max(LEAST));
- assertEquals(GREATEST, Chars.max(GREATEST));
- assertEquals(
- (char) 9, Chars.max((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9));
+ assertThat(Chars.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Chars.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Chars.max((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9))
+ .isEqualTo((char) 9);
}
public void testMin_noArgs() {
@@ -181,18 +193,18 @@ public class CharsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Chars.min(LEAST));
- assertEquals(GREATEST, Chars.min(GREATEST));
- assertEquals(
- (char) 0, Chars.min((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9));
+ assertThat(Chars.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Chars.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Chars.min((char) 8, (char) 6, (char) 7, (char) 5, (char) 3, (char) 0, (char) 9))
+ .isEqualTo((char) 0);
}
public void testConstrainToRange() {
- assertEquals((char) 1, Chars.constrainToRange((char) 1, (char) 0, (char) 5));
- assertEquals((char) 1, Chars.constrainToRange((char) 1, (char) 1, (char) 5));
- assertEquals((char) 3, Chars.constrainToRange((char) 1, (char) 3, (char) 5));
- assertEquals((char) 254, Chars.constrainToRange((char) 255, (char) 250, (char) 254));
- assertEquals((char) 2, Chars.constrainToRange((char) 5, (char) 2, (char) 2));
+ assertThat(Chars.constrainToRange((char) 1, (char) 0, (char) 5)).isEqualTo((char) 1);
+ assertThat(Chars.constrainToRange((char) 1, (char) 1, (char) 5)).isEqualTo((char) 1);
+ assertThat(Chars.constrainToRange((char) 1, (char) 3, (char) 5)).isEqualTo((char) 3);
+ assertThat(Chars.constrainToRange((char) 255, (char) 250, (char) 254)).isEqualTo((char) 254);
+ assertThat(Chars.constrainToRange((char) 5, (char) 2, (char) 2)).isEqualTo((char) 2);
try {
Chars.constrainToRange((char) 1, (char) 3, (char) 2);
fail();
@@ -201,26 +213,26 @@ public class CharsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Chars.concat()));
- assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Chars.concat(ARRAY1)));
- assertNotSame(ARRAY1, Chars.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Chars.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new char[] {(char) 1, (char) 1, (char) 1}, Chars.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new char[] {(char) 1, (char) 2, (char) 3, (char) 4}, Chars.concat(ARRAY1, ARRAY234)));
- }
-
+ assertThat(Chars.concat()).isEqualTo(EMPTY);
+ assertThat(Chars.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Chars.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Chars.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Chars.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Chars.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Chars.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new char[] {(char) 1, (char) 1, (char) 1});
+ assertThat(Chars.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new char[] {(char) 1, (char) 2, (char) 3, (char) 4});
+ }
+
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray
public void testFromByteArray() {
- assertEquals('\u2345', Chars.fromByteArray(new byte[] {0x23, 0x45, (byte) 0xDC}));
- assertEquals('\uFEDC', Chars.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC}));
+ assertThat(Chars.fromByteArray(new byte[] {0x23, 0x45, (byte) 0xDC})).isEqualTo('\u2345');
+ assertThat(Chars.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC})).isEqualTo('\uFEDC');
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray
public void testFromByteArrayFails() {
try {
@@ -230,34 +242,42 @@ public class CharsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromBytes
public void testFromBytes() {
- assertEquals('\u2345', Chars.fromBytes((byte) 0x23, (byte) 0x45));
- assertEquals('\uFEDC', Chars.fromBytes((byte) 0xFE, (byte) 0xDC));
+ assertThat(Chars.fromBytes((byte) 0x23, (byte) 0x45)).isEqualTo('\u2345');
+ assertThat(Chars.fromBytes((byte) 0xFE, (byte) 0xDC)).isEqualTo('\uFEDC');
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray, Chars.toByteArray
public void testByteArrayRoundTrips() {
char c = 0;
for (int hi = 0; hi < 256; hi++) {
for (int lo = 0; lo < 256; lo++) {
char result = Chars.fromByteArray(new byte[] {(byte) hi, (byte) lo});
- assertEquals(
- String.format(
- Locale.ROOT, "hi=%s, lo=%s, expected=%s, result=%s", hi, lo, (int) c, (int) result),
- c,
- result);
+ assertWithMessage(
+ String.format(
+ Locale.ROOT,
+ "hi=%s, lo=%s, expected=%s, result=%s",
+ hi,
+ lo,
+ (int) c,
+ (int) result))
+ .that(result)
+ .isEqualTo(c);
byte[] bytes = Chars.toByteArray(c);
- assertEquals((byte) hi, bytes[0]);
- assertEquals((byte) lo, bytes[1]);
+ assertThat(bytes[0]).isEqualTo((byte) hi);
+ assertThat(bytes[1]).isEqualTo((byte) lo);
c++;
}
}
- assertEquals((char) 0, c); // sanity check
+ assertThat(c).isEqualTo((char) 0); // sanity check
}
+ @J2ktIncompatible
@GwtIncompatible // Chars.fromByteArray, Chars.toByteArray
public void testByteArrayRoundTripsFails() {
try {
@@ -268,12 +288,11 @@ public class CharsTest extends TestCase {
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Chars.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new char[] {(char) 1, (char) 0, (char) 0}, Chars.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Chars.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Chars.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Chars.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Chars.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new char[] {(char) 1, (char) 0, (char) 0});
}
public void testEnsureCapacity_fail() {
@@ -291,10 +310,10 @@ public class CharsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Chars.join(",", EMPTY));
- assertEquals("1", Chars.join(",", '1'));
- assertEquals("1,2", Chars.join(",", '1', '2'));
- assertEquals("123", Chars.join("", '1', '2', '3'));
+ assertThat(Chars.join(",", EMPTY)).isEmpty();
+ assertThat(Chars.join(",", '1')).isEqualTo("1");
+ assertThat(Chars.join(",", '1', '2')).isEqualTo("1,2");
+ assertThat(Chars.join("", '1', '2', '3')).isEqualTo("123");
}
public void testLexicographicalComparator() {
@@ -314,10 +333,11 @@ public class CharsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<char[]> comparator = Chars.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -331,13 +351,13 @@ public class CharsTest extends TestCase {
private static void testReverse(char[] input, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(char[] input, int fromIndex, int toIndex, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -349,6 +369,203 @@ public class CharsTest extends TestCase {
testReverse(new char[] {'A', '1', 'B', '2'}, 1, 3, new char[] {'A', 'B', '1', '2'});
}
+ private static void testRotate(char[] input, int distance, char[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Chars.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ char[] input, int distance, int fromIndex, int toIndex, char[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Chars.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new char[] {}, -1, new char[] {});
+ testRotate(new char[] {}, 0, new char[] {});
+ testRotate(new char[] {}, 1, new char[] {});
+
+ testRotate(new char[] {'1'}, -2, new char[] {'1'});
+ testRotate(new char[] {'1'}, -1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 0, new char[] {'1'});
+ testRotate(new char[] {'1'}, 1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 2, new char[] {'1'});
+
+ testRotate(new char[] {'1', '2'}, -3, new char[] {'2', '1'});
+ testRotate(new char[] {'1', '2'}, -1, new char[] {'2', '1'});
+ testRotate(new char[] {'1', '2'}, -2, new char[] {'1', '2'});
+ testRotate(new char[] {'1', '2'}, 0, new char[] {'1', '2'});
+ testRotate(new char[] {'1', '2'}, 1, new char[] {'2', '1'});
+ testRotate(new char[] {'1', '2'}, 2, new char[] {'1', '2'});
+ testRotate(new char[] {'1', '2'}, 3, new char[] {'2', '1'});
+
+ testRotate(new char[] {'1', '2', '3'}, -5, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, -4, new char[] {'2', '3', '1'});
+ testRotate(new char[] {'1', '2', '3'}, -3, new char[] {'1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3'}, -2, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, -1, new char[] {'2', '3', '1'});
+ testRotate(new char[] {'1', '2', '3'}, 0, new char[] {'1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3'}, 1, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, 2, new char[] {'2', '3', '1'});
+ testRotate(new char[] {'1', '2', '3'}, 3, new char[] {'1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3'}, 4, new char[] {'3', '1', '2'});
+ testRotate(new char[] {'1', '2', '3'}, 5, new char[] {'2', '3', '1'});
+
+ testRotate(new char[] {'1', '2', '3', '4'}, -9, new char[] {'2', '3', '4', '1'});
+ testRotate(new char[] {'1', '2', '3', '4'}, -5, new char[] {'2', '3', '4', '1'});
+ testRotate(new char[] {'1', '2', '3', '4'}, -1, new char[] {'2', '3', '4', '1'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 0, new char[] {'1', '2', '3', '4'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 1, new char[] {'4', '1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 5, new char[] {'4', '1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3', '4'}, 9, new char[] {'4', '1', '2', '3'});
+
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -6, new char[] {'2', '3', '4', '5', '1'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -4, new char[] {'5', '1', '2', '3', '4'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -3, new char[] {'4', '5', '1', '2', '3'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, -1, new char[] {'2', '3', '4', '5', '1'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 0, new char[] {'1', '2', '3', '4', '5'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 1, new char[] {'5', '1', '2', '3', '4'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 3, new char[] {'3', '4', '5', '1', '2'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 4, new char[] {'2', '3', '4', '5', '1'});
+ testRotate(new char[] {'1', '2', '3', '4', '5'}, 6, new char[] {'5', '1', '2', '3', '4'});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new char[] {}, 0, 0, 0, new char[] {});
+
+ testRotate(new char[] {'1'}, 0, 0, 1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 1, 0, 1, new char[] {'1'});
+ testRotate(new char[] {'1'}, 1, 1, 1, new char[] {'1'});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -6,
+ 1,
+ 6,
+ new char[] {'0', '2', '3', '4', '5', '1', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -1,
+ 1,
+ 6,
+ new char[] {'0', '2', '3', '4', '5', '1', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 0,
+ 1,
+ 6,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 5,
+ 1,
+ 6,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 14,
+ 1,
+ 6,
+ new char[] {'0', '2', '3', '4', '5', '1', '6'});
+
+ // Rotate the first three elements
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -2,
+ 0,
+ 3,
+ new char[] {'2', '0', '1', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -1,
+ 0,
+ 3,
+ new char[] {'1', '2', '0', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 0,
+ 0,
+ 3,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 1,
+ 0,
+ 3,
+ new char[] {'2', '0', '1', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 2,
+ 0,
+ 3,
+ new char[] {'1', '2', '0', '3', '4', '5', '6'});
+
+ // Rotate the last four elements
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -6,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '5', '6', '3', '4'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -5,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '4', '5', '6', '3'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -4,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -3,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '6', '3', '4', '5'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -2,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '5', '6', '3', '4'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ -1,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '4', '5', '6', '3'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 0,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '3', '4', '5', '6'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 1,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '6', '3', '4', '5'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 2,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '5', '6', '3', '4'});
+ testRotate(
+ new char[] {'0', '1', '2', '3', '4', '5', '6'},
+ 3,
+ 3,
+ 7,
+ new char[] {'0', '1', '2', '4', '5', '6', '3'});
+ }
+
public void testSortDescending() {
testSortDescending(new char[] {}, new char[] {});
testSortDescending(new char[] {'1'}, new char[] {'1'});
@@ -360,14 +577,14 @@ public class CharsTest extends TestCase {
private static void testSortDescending(char[] input, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
char[] input, int fromIndex, int toIndex, char[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Chars.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -382,17 +599,17 @@ public class CharsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Character> none = Arrays.<Character>asList();
- assertTrue(Arrays.equals(EMPTY, Chars.toArray(none)));
+ assertThat(Chars.toArray(none)).isEqualTo(EMPTY);
List<Character> one = Arrays.asList((char) 1);
- assertTrue(Arrays.equals(ARRAY1, Chars.toArray(one)));
+ assertThat(Chars.toArray(one)).isEqualTo(ARRAY1);
char[] array = {(char) 0, (char) 1, 'A'};
List<Character> three = Arrays.asList((char) 0, (char) 1, 'A');
- assertTrue(Arrays.equals(array, Chars.toArray(three)));
+ assertThat(Chars.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Chars.toArray(Chars.asList(array))));
+ assertThat(Chars.toArray(Chars.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -402,16 +619,16 @@ public class CharsTest extends TestCase {
Collection<Character> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
char[] arr = Chars.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Character> list = Arrays.asList((char) 0, (char) 1, null);
+ List<@Nullable Character> list = Arrays.asList((char) 0, (char) 1, null);
try {
Chars.toArray(list);
fail();
@@ -419,13 +636,14 @@ public class CharsTest extends TestCase {
}
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
char[] array = {(char) 0, (char) 1};
List<Character> list = Chars.asList(array);
list.set(0, (char) 2);
- assertTrue(Arrays.equals(new char[] {(char) 2, (char) 1}, array));
+ assertThat(array).isEqualTo(new char[] {(char) 2, (char) 1});
array[1] = (char) 3;
- assertEquals(Arrays.asList((char) 2, (char) 3), list);
+ assertThat(list).containsExactly((char) 2, (char) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -435,23 +653,24 @@ public class CharsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (char) 4);
- assertTrue(Arrays.equals(new char[] {(char) 0, (char) 1, (char) 2}, newArray));
+ assertThat(newArray).isEqualTo(new char[] {(char) 0, (char) 1, (char) 2});
newArray[1] = (char) 5;
- assertEquals((char) 1, (char) list.get(1));
+ assertThat((char) list.get(1)).isEqualTo((char) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
char[] array = {(char) 0, (char) 1, (char) 2, (char) 3};
List<Character> list = Chars.asList(array);
- assertTrue(Arrays.equals(new char[] {(char) 1, (char) 2}, Chars.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new char[] {}, Chars.toArray(list.subList(2, 2))));
+ assertThat(Chars.toArray(list.subList(1, 3))).isEqualTo(new char[] {(char) 1, (char) 2});
+ assertThat(Chars.toArray(list.subList(2, 2))).isEqualTo(new char[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Chars.asList(EMPTY));
+ assertThat(Chars.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Chars.class);
diff --git a/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java
index 23a7ca140..e7cd4f38e 100644
--- a/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,12 +49,13 @@ public class DoubleArrayAsListTest extends TestCase {
return Doubles.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Double>> builders =
ImmutableList.of(
ListTestSuiteBuilder.using(new DoublesAsListGenerator()).named("Doubles.asList"),
- ListTestSuiteBuilder.using(new DoublsAsListHeadSubListGenerator())
+ ListTestSuiteBuilder.using(new DoublesAsListHeadSubListGenerator())
.named("Doubles.asList, head subList"),
ListTestSuiteBuilder.using(new DoublesAsListTailSubListGenerator())
.named("Doubles.asList, tail subList"),
@@ -84,7 +86,7 @@ public class DoubleArrayAsListTest extends TestCase {
}
}
- public static final class DoublsAsListHeadSubListGenerator extends TestDoubleListGenerator {
+ public static final class DoublesAsListHeadSubListGenerator extends TestDoubleListGenerator {
@Override
protected List<Double> create(Double[] elements) {
Double[] suffix = {Double.MIN_VALUE, Double.MAX_VALUE};
diff --git a/guava-tests/test/com/google/common/primitives/DoublesTest.java b/guava-tests/test/com/google/common/primitives/DoublesTest.java
index 871b84c28..2483f42bc 100644
--- a/guava-tests/test/com/google/common/primitives/DoublesTest.java
+++ b/guava-tests/test/com/google/common/primitives/DoublesTest.java
@@ -17,10 +17,12 @@
package com.google.common.primitives;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Double.NaN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.Helpers;
@@ -33,14 +35,15 @@ import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Doubles}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
-@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class DoublesTest extends TestCase {
private static final double[] EMPTY = {};
private static final double[] ARRAY1 = {(double) 1};
@@ -77,13 +80,14 @@ public class DoublesTest extends TestCase {
public void testHashCode() {
for (double value : VALUES) {
- assertEquals(((Double) value).hashCode(), Doubles.hashCode(value));
+ assertThat(Doubles.hashCode(value)).isEqualTo(((Double) value).hashCode());
}
}
public void testIsFinite() {
for (double value : NUMBERS) {
- assertEquals(!(Double.isNaN(value) || Double.isInfinite(value)), Doubles.isFinite(value));
+ assertThat(Doubles.isFinite(value))
+ .isEqualTo(!(Double.isNaN(value) || Double.isInfinite(value)));
}
}
@@ -91,109 +95,119 @@ public class DoublesTest extends TestCase {
for (double x : VALUES) {
for (double y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Double.valueOf(x).compareTo(y), Doubles.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Doubles.compare(x, y))
+ .isEqualTo(Double.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Doubles.contains(EMPTY, (double) 1));
- assertFalse(Doubles.contains(ARRAY1, (double) 2));
- assertFalse(Doubles.contains(ARRAY234, (double) 1));
- assertTrue(Doubles.contains(new double[] {(double) -1}, (double) -1));
- assertTrue(Doubles.contains(ARRAY234, (double) 2));
- assertTrue(Doubles.contains(ARRAY234, (double) 3));
- assertTrue(Doubles.contains(ARRAY234, (double) 4));
+ assertThat(Doubles.contains(EMPTY, (double) 1)).isFalse();
+ assertThat(Doubles.contains(ARRAY1, (double) 2)).isFalse();
+ assertThat(Doubles.contains(ARRAY234, (double) 1)).isFalse();
+ assertThat(Doubles.contains(new double[] {(double) -1}, (double) -1)).isTrue();
+ assertThat(Doubles.contains(ARRAY234, (double) 2)).isTrue();
+ assertThat(Doubles.contains(ARRAY234, (double) 3)).isTrue();
+ assertThat(Doubles.contains(ARRAY234, (double) 4)).isTrue();
for (double value : NUMBERS) {
- assertTrue("" + value, Doubles.contains(new double[] {5.0, value}, value));
+ assertWithMessage("" + value)
+ .that(Doubles.contains(new double[] {5.0, value}, value))
+ .isTrue();
}
- assertFalse(Doubles.contains(new double[] {5.0, NaN}, NaN));
+ assertThat(Doubles.contains(new double[] {5.0, NaN}, NaN)).isFalse();
}
public void testIndexOf() {
- assertEquals(-1, Doubles.indexOf(EMPTY, (double) 1));
- assertEquals(-1, Doubles.indexOf(ARRAY1, (double) 2));
- assertEquals(-1, Doubles.indexOf(ARRAY234, (double) 1));
- assertEquals(0, Doubles.indexOf(new double[] {(double) -1}, (double) -1));
- assertEquals(0, Doubles.indexOf(ARRAY234, (double) 2));
- assertEquals(1, Doubles.indexOf(ARRAY234, (double) 3));
- assertEquals(2, Doubles.indexOf(ARRAY234, (double) 4));
- assertEquals(
- 1,
- Doubles.indexOf(new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3));
+ assertThat(Doubles.indexOf(EMPTY, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY1, (double) 2)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(new double[] {(double) -1}, (double) -1)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 2)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 3)).isEqualTo(1);
+ assertThat(Doubles.indexOf(ARRAY234, (double) 4)).isEqualTo(2);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3))
+ .isEqualTo(1);
for (double value : NUMBERS) {
- assertEquals("" + value, 1, Doubles.indexOf(new double[] {5.0, value}, value));
+ assertWithMessage("" + value)
+ .that(Doubles.indexOf(new double[] {5.0, value}, value))
+ .isEqualTo(1);
}
- assertEquals(-1, Doubles.indexOf(new double[] {5.0, NaN}, NaN));
+ assertThat(Doubles.indexOf(new double[] {5.0, NaN}, NaN)).isEqualTo(-1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Doubles.indexOf(EMPTY, EMPTY));
- assertEquals(0, Doubles.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Doubles.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Doubles.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Doubles.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Doubles.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Doubles.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Doubles.indexOf(ARRAY234, new double[] {(double) 2, (double) 3}));
- assertEquals(1, Doubles.indexOf(ARRAY234, new double[] {(double) 3, (double) 4}));
- assertEquals(1, Doubles.indexOf(ARRAY234, new double[] {(double) 3}));
- assertEquals(2, Doubles.indexOf(ARRAY234, new double[] {(double) 4}));
- assertEquals(
- 1,
- Doubles.indexOf(
- new double[] {(double) 2, (double) 3, (double) 3, (double) 3, (double) 3},
- new double[] {(double) 3}));
- assertEquals(
- 2,
- Doubles.indexOf(
- new double[] {
- (double) 2, (double) 3, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3
- },
- new double[] {(double) 2, (double) 3, (double) 4}));
- assertEquals(
- 1,
- Doubles.indexOf(
- new double[] {
- (double) 2, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3, (double) 4
- },
- new double[] {(double) 2, (double) 3, (double) 4}));
- assertEquals(
- -1,
- Doubles.indexOf(
- new double[] {(double) 4, (double) 3, (double) 2},
- new double[] {(double) 2, (double) 3, (double) 4}));
+ assertThat(Doubles.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Doubles.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Doubles.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 2, (double) 3})).isEqualTo(0);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 3, (double) 4})).isEqualTo(1);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 3})).isEqualTo(1);
+ assertThat(Doubles.indexOf(ARRAY234, new double[] {(double) 4})).isEqualTo(2);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {(double) 2, (double) 3, (double) 3, (double) 3, (double) 3},
+ new double[] {(double) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {
+ (double) 2, (double) 3, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3
+ },
+ new double[] {(double) 2, (double) 3, (double) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {
+ (double) 2, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3, (double) 4
+ },
+ new double[] {(double) 2, (double) 3, (double) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Doubles.indexOf(
+ new double[] {(double) 4, (double) 3, (double) 2},
+ new double[] {(double) 2, (double) 3, (double) 4}))
+ .isEqualTo(-1);
for (double value : NUMBERS) {
- assertEquals(
- "" + value,
- 1,
- Doubles.indexOf(new double[] {5.0, value, value, 5.0}, new double[] {value, value}));
+ assertWithMessage("" + value)
+ .that(Doubles.indexOf(new double[] {5.0, value, value, 5.0}, new double[] {value, value}))
+ .isEqualTo(1);
}
- assertEquals(-1, Doubles.indexOf(new double[] {5.0, NaN, NaN, 5.0}, new double[] {NaN, NaN}));
+ assertThat(Doubles.indexOf(new double[] {5.0, NaN, NaN, 5.0}, new double[] {NaN, NaN}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Doubles.lastIndexOf(EMPTY, (double) 1));
- assertEquals(-1, Doubles.lastIndexOf(ARRAY1, (double) 2));
- assertEquals(-1, Doubles.lastIndexOf(ARRAY234, (double) 1));
- assertEquals(0, Doubles.lastIndexOf(new double[] {(double) -1}, (double) -1));
- assertEquals(0, Doubles.lastIndexOf(ARRAY234, (double) 2));
- assertEquals(1, Doubles.lastIndexOf(ARRAY234, (double) 3));
- assertEquals(2, Doubles.lastIndexOf(ARRAY234, (double) 4));
- assertEquals(
- 3,
- Doubles.lastIndexOf(
- new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3));
+ assertThat(Doubles.lastIndexOf(EMPTY, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.lastIndexOf(ARRAY1, (double) 2)).isEqualTo(-1);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 1)).isEqualTo(-1);
+ assertThat(Doubles.lastIndexOf(new double[] {(double) -1}, (double) -1)).isEqualTo(0);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 2)).isEqualTo(0);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 3)).isEqualTo(1);
+ assertThat(Doubles.lastIndexOf(ARRAY234, (double) 4)).isEqualTo(2);
+ assertThat(
+ Doubles.lastIndexOf(
+ new double[] {(double) 2, (double) 3, (double) 2, (double) 3}, (double) 3))
+ .isEqualTo(3);
for (double value : NUMBERS) {
- assertEquals("" + value, 0, Doubles.lastIndexOf(new double[] {value, 5.0}, value));
+ assertWithMessage("" + value)
+ .that(Doubles.lastIndexOf(new double[] {value, 5.0}, value))
+ .isEqualTo(0);
}
- assertEquals(-1, Doubles.lastIndexOf(new double[] {NaN, 5.0}, NaN));
+ assertThat(Doubles.lastIndexOf(new double[] {NaN, 5.0}, NaN)).isEqualTo(-1);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -204,19 +218,20 @@ public class DoublesTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Doubles.max(LEAST));
- assertEquals(GREATEST, Doubles.max(GREATEST));
- assertEquals(
- (double) 9,
- Doubles.max(
- (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9));
+ assertThat(Doubles.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Doubles.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Doubles.max(
+ (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9))
+ .isEqualTo((double) 9);
- assertEquals(0.0, Doubles.max(-0.0, 0.0));
- assertEquals(0.0, Doubles.max(0.0, -0.0));
- assertEquals(GREATEST, Doubles.max(NUMBERS));
- assertTrue(Double.isNaN(Doubles.max(VALUES)));
+ assertThat(Doubles.max(-0.0, 0.0)).isEqualTo(0.0);
+ assertThat(Doubles.max(0.0, -0.0)).isEqualTo(0.0);
+ assertThat(Doubles.max(NUMBERS)).isEqualTo(GREATEST);
+ assertThat(Double.isNaN(Doubles.max(VALUES))).isTrue();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -227,31 +242,26 @@ public class DoublesTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Doubles.min(LEAST));
- assertEquals(GREATEST, Doubles.min(GREATEST));
- assertEquals(
- (double) 0,
- Doubles.min(
- (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9));
+ assertThat(Doubles.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Doubles.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Doubles.min(
+ (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9))
+ .isEqualTo((double) 0);
- assertEquals(-0.0, Doubles.min(-0.0, 0.0));
- assertEquals(-0.0, Doubles.min(0.0, -0.0));
- assertEquals(LEAST, Doubles.min(NUMBERS));
- assertTrue(Double.isNaN(Doubles.min(VALUES)));
+ assertThat(Doubles.min(-0.0, 0.0)).isEqualTo(-0.0);
+ assertThat(Doubles.min(0.0, -0.0)).isEqualTo(-0.0);
+ assertThat(Doubles.min(NUMBERS)).isEqualTo(LEAST);
+ assertThat(Double.isNaN(Doubles.min(VALUES))).isTrue();
}
public void testConstrainToRange() {
- double tolerance = 1e-10;
- assertEquals(
- (double) 1, Doubles.constrainToRange((double) 1, (double) 0, (double) 5), tolerance);
- assertEquals(
- (double) 1, Doubles.constrainToRange((double) 1, (double) 1, (double) 5), tolerance);
- assertEquals(
- (double) 3, Doubles.constrainToRange((double) 1, (double) 3, (double) 5), tolerance);
- assertEquals(
- (double) -1, Doubles.constrainToRange((double) 0, (double) -5, (double) -1), tolerance);
- assertEquals(
- (double) 2, Doubles.constrainToRange((double) 5, (double) 2, (double) 2), tolerance);
+ assertThat(Doubles.constrainToRange((double) 1, (double) 0, (double) 5)).isEqualTo((double) 1);
+ assertThat(Doubles.constrainToRange((double) 1, (double) 1, (double) 5)).isEqualTo((double) 1);
+ assertThat(Doubles.constrainToRange((double) 1, (double) 3, (double) 5)).isEqualTo((double) 3);
+ assertThat(Doubles.constrainToRange((double) 0, (double) -5, (double) -1))
+ .isEqualTo((double) -1);
+ assertThat(Doubles.constrainToRange((double) 5, (double) 2, (double) 2)).isEqualTo((double) 2);
try {
Doubles.constrainToRange((double) 1, (double) 3, (double) 2);
fail();
@@ -260,30 +270,27 @@ public class DoublesTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Doubles.concat()));
- assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Doubles.concat(ARRAY1)));
- assertNotSame(ARRAY1, Doubles.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Doubles.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new double[] {(double) 1, (double) 1, (double) 1},
- Doubles.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new double[] {(double) 1, (double) 2, (double) 3, (double) 4},
- Doubles.concat(ARRAY1, ARRAY234)));
+ assertThat(Doubles.concat()).isEqualTo(EMPTY);
+ assertThat(Doubles.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Doubles.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Doubles.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Doubles.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Doubles.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Doubles.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new double[] {(double) 1, (double) 1, (double) 1});
+ assertThat(Doubles.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new double[] {(double) 1, (double) 2, (double) 3, (double) 4});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Doubles.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new double[] {(double) 1, (double) 0, (double) 0},
- Doubles.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Doubles.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Doubles.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Doubles.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(
+ Arrays.equals(
+ new double[] {(double) 1, (double) 0, (double) 0},
+ Doubles.ensureCapacity(ARRAY1, 2, 1)))
+ .isTrue();
}
public void testEnsureCapacity_fail() {
@@ -300,19 +307,20 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Double.toString returns different value in GWT.
public void testJoin() {
- assertEquals("", Doubles.join(",", EMPTY));
- assertEquals("1.0", Doubles.join(",", ARRAY1));
- assertEquals("1.0,2.0", Doubles.join(",", (double) 1, (double) 2));
- assertEquals("1.02.03.0", Doubles.join("", (double) 1, (double) 2, (double) 3));
+ assertThat(Doubles.join(",", EMPTY)).isEmpty();
+ assertThat(Doubles.join(",", ARRAY1)).isEqualTo("1.0");
+ assertThat(Doubles.join(",", (double) 1, (double) 2)).isEqualTo("1.0,2.0");
+ assertThat(Doubles.join("", (double) 1, (double) 2, (double) 3)).isEqualTo("1.02.03.0");
}
public void testJoinNonTrivialDoubles() {
- assertEquals("", Doubles.join(",", EMPTY));
- assertEquals("1.2", Doubles.join(",", 1.2));
- assertEquals("1.3,2.4", Doubles.join(",", 1.3, 2.4));
- assertEquals("1.42.53.6", Doubles.join("", 1.4, 2.5, 3.6));
+ assertThat(Doubles.join(",", EMPTY)).isEmpty();
+ assertThat(Doubles.join(",", 1.2)).isEqualTo("1.2");
+ assertThat(Doubles.join(",", 1.3, 2.4)).isEqualTo("1.3,2.4");
+ assertThat(Doubles.join("", 1.4, 2.5, 3.6)).isEqualTo("1.42.53.6");
}
public void testLexicographicalComparator() {
@@ -343,14 +351,14 @@ public class DoublesTest extends TestCase {
private static void testReverse(double[] input, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
double[] input, int fromIndex, int toIndex, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -362,6 +370,103 @@ public class DoublesTest extends TestCase {
testReverse(new double[] {-1, 1, -2, 2}, 1, 3, new double[] {-1, -2, 1, 2});
}
+ private static void testRotate(double[] input, int distance, double[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Doubles.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ double[] input, int distance, int fromIndex, int toIndex, double[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Doubles.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new double[] {}, -1, new double[] {});
+ testRotate(new double[] {}, 0, new double[] {});
+ testRotate(new double[] {}, 1, new double[] {});
+
+ testRotate(new double[] {1}, -2, new double[] {1});
+ testRotate(new double[] {1}, -1, new double[] {1});
+ testRotate(new double[] {1}, 0, new double[] {1});
+ testRotate(new double[] {1}, 1, new double[] {1});
+ testRotate(new double[] {1}, 2, new double[] {1});
+
+ testRotate(new double[] {1, 2}, -3, new double[] {2, 1});
+ testRotate(new double[] {1, 2}, -1, new double[] {2, 1});
+ testRotate(new double[] {1, 2}, -2, new double[] {1, 2});
+ testRotate(new double[] {1, 2}, 0, new double[] {1, 2});
+ testRotate(new double[] {1, 2}, 1, new double[] {2, 1});
+ testRotate(new double[] {1, 2}, 2, new double[] {1, 2});
+ testRotate(new double[] {1, 2}, 3, new double[] {2, 1});
+
+ testRotate(new double[] {1, 2, 3}, -5, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, -4, new double[] {2, 3, 1});
+ testRotate(new double[] {1, 2, 3}, -3, new double[] {1, 2, 3});
+ testRotate(new double[] {1, 2, 3}, -2, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, -1, new double[] {2, 3, 1});
+ testRotate(new double[] {1, 2, 3}, 0, new double[] {1, 2, 3});
+ testRotate(new double[] {1, 2, 3}, 1, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, 2, new double[] {2, 3, 1});
+ testRotate(new double[] {1, 2, 3}, 3, new double[] {1, 2, 3});
+ testRotate(new double[] {1, 2, 3}, 4, new double[] {3, 1, 2});
+ testRotate(new double[] {1, 2, 3}, 5, new double[] {2, 3, 1});
+
+ testRotate(new double[] {1, 2, 3, 4}, -9, new double[] {2, 3, 4, 1});
+ testRotate(new double[] {1, 2, 3, 4}, -5, new double[] {2, 3, 4, 1});
+ testRotate(new double[] {1, 2, 3, 4}, -1, new double[] {2, 3, 4, 1});
+ testRotate(new double[] {1, 2, 3, 4}, 0, new double[] {1, 2, 3, 4});
+ testRotate(new double[] {1, 2, 3, 4}, 1, new double[] {4, 1, 2, 3});
+ testRotate(new double[] {1, 2, 3, 4}, 5, new double[] {4, 1, 2, 3});
+ testRotate(new double[] {1, 2, 3, 4}, 9, new double[] {4, 1, 2, 3});
+
+ testRotate(new double[] {1, 2, 3, 4, 5}, -6, new double[] {2, 3, 4, 5, 1});
+ testRotate(new double[] {1, 2, 3, 4, 5}, -4, new double[] {5, 1, 2, 3, 4});
+ testRotate(new double[] {1, 2, 3, 4, 5}, -3, new double[] {4, 5, 1, 2, 3});
+ testRotate(new double[] {1, 2, 3, 4, 5}, -1, new double[] {2, 3, 4, 5, 1});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 0, new double[] {1, 2, 3, 4, 5});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 1, new double[] {5, 1, 2, 3, 4});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 3, new double[] {3, 4, 5, 1, 2});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 4, new double[] {2, 3, 4, 5, 1});
+ testRotate(new double[] {1, 2, 3, 4, 5}, 6, new double[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new double[] {}, 0, 0, 0, new double[] {});
+
+ testRotate(new double[] {1}, 0, 0, 1, new double[] {1});
+ testRotate(new double[] {1}, 1, 0, 1, new double[] {1});
+ testRotate(new double[] {1}, 1, 1, 1, new double[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new double[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new double[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new double[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new double[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new double[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new double[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new double[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new double[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new double[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new double[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new double[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new double[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new double[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new double[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new double[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new double[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new double[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new double[] {}, new double[] {});
testSortDescending(new double[] {1}, new double[] {1});
@@ -369,16 +474,15 @@ public class DoublesTest extends TestCase {
testSortDescending(new double[] {1, 3, 1}, new double[] {3, 1, 1});
testSortDescending(new double[] {-1, 1, -2, 2}, new double[] {2, 1, -1, -2});
testSortDescending(
- new double[] {-1, 1, Double.NaN, -2, -0, 0, 2},
- new double[] {Double.NaN, 2, 1, 0, -0, -1, -2});
+ new double[] {-1, 1, Double.NaN, -2, -0.0, 0, 2},
+ new double[] {Double.NaN, 2, 1, 0, -0.0, -1, -2});
}
private static void testSortDescending(double[] input, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.sortDescending(input);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Double.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -386,9 +490,8 @@ public class DoublesTest extends TestCase {
double[] input, int fromIndex, int toIndex, double[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Doubles.sortDescending(input, fromIndex, toIndex);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Double.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -403,12 +506,14 @@ public class DoublesTest extends TestCase {
new double[] {-1, 1, Double.NaN, -2, 2}, 1, 4, new double[] {-1, Double.NaN, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<double[]> comparator = Doubles.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Doubles.stringConverter());
@@ -417,17 +522,17 @@ public class DoublesTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Double> none = Arrays.<Double>asList();
- assertTrue(Arrays.equals(EMPTY, Doubles.toArray(none)));
+ assertThat(Doubles.toArray(none)).isEqualTo(EMPTY);
List<Double> one = Arrays.asList((double) 1);
- assertTrue(Arrays.equals(ARRAY1, Doubles.toArray(one)));
+ assertThat(Doubles.toArray(one)).isEqualTo(ARRAY1);
double[] array = {(double) 0, (double) 1, Math.PI};
List<Double> three = Arrays.asList((double) 0, (double) 1, Math.PI);
- assertTrue(Arrays.equals(array, Doubles.toArray(three)));
+ assertThat(Doubles.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Doubles.toArray(Doubles.asList(array))));
+ assertThat(Doubles.toArray(Doubles.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -437,16 +542,16 @@ public class DoublesTest extends TestCase {
Collection<Double> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
double[] arr = Doubles.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr.length).isEqualTo(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Double> list = Arrays.asList((double) 0, (double) 1, null);
+ List<@Nullable Double> list = Arrays.asList((double) 0, (double) 1, null);
try {
Doubles.toArray(list);
fail();
@@ -464,19 +569,20 @@ public class DoublesTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Doubles.toArray(bytes)));
- assertTrue(Arrays.equals(array, Doubles.toArray(shorts)));
- assertTrue(Arrays.equals(array, Doubles.toArray(ints)));
- assertTrue(Arrays.equals(array, Doubles.toArray(floats)));
- assertTrue(Arrays.equals(array, Doubles.toArray(longs)));
- assertTrue(Arrays.equals(array, Doubles.toArray(doubles)));
+ assertThat(Doubles.toArray(bytes)).isEqualTo(array);
+ assertThat(Doubles.toArray(shorts)).isEqualTo(array);
+ assertThat(Doubles.toArray(ints)).isEqualTo(array);
+ assertThat(Doubles.toArray(floats)).isEqualTo(array);
+ assertThat(Doubles.toArray(longs)).isEqualTo(array);
+ assertThat(Doubles.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
double[] array = {(double) 0, (double) 1};
List<Double> list = Doubles.asList(array);
list.set(0, (double) 2);
- assertTrue(Arrays.equals(new double[] {(double) 2, (double) 1}, array));
+ assertThat(array).isEqualTo(new double[] {(double) 2, (double) 1});
array[1] = (double) 3;
assertThat(list).containsExactly((double) 2, (double) 3).inOrder();
}
@@ -488,29 +594,29 @@ public class DoublesTest extends TestCase {
// Make sure it returned a copy
list.set(0, (double) 4);
- assertTrue(Arrays.equals(new double[] {(double) 0, (double) 1, (double) 2}, newArray));
+ assertThat(newArray).isEqualTo(new double[] {(double) 0, (double) 1, (double) 2});
newArray[1] = (double) 5;
- assertEquals((double) 1, (double) list.get(1));
+ assertThat((double) list.get(1)).isEqualTo((double) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
double[] array = {(double) 0, (double) 1, (double) 2, (double) 3};
List<Double> list = Doubles.asList(array);
- assertTrue(
- Arrays.equals(new double[] {(double) 1, (double) 2}, Doubles.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new double[] {}, Doubles.toArray(list.subList(2, 2))));
+ assertThat(Doubles.toArray(list.subList(1, 3)))
+ .isEqualTo(new double[] {(double) 1, (double) 2});
+ assertThat(Doubles.toArray(list.subList(2, 2))).isEmpty();
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Doubles.asList(EMPTY));
+ assertThat(Doubles.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
/**
* A reference implementation for {@code tryParse} that just catches the exception from {@link
* Double#valueOf}.
*/
- private static Double referenceTryParse(String input) {
+ private static @Nullable Double referenceTryParse(String input) {
if (input.trim().length() < input.length()) {
return null;
}
@@ -521,10 +627,11 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
private static void checkTryParse(String input) {
Double expected = referenceTryParse(input);
- assertEquals(expected, Doubles.tryParse(input));
+ assertThat(Doubles.tryParse(input)).isEqualTo(expected);
if (expected != null && !Doubles.FLOATING_POINT_PATTERN.matcher(input).matches()) {
// TODO(cpovirk): Use SourceCodeEscapers if it is added to Guava.
StringBuilder escapedInput = new StringBuilder();
@@ -539,15 +646,17 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
private static void checkTryParse(double expected, String input) {
- assertEquals(Double.valueOf(expected), Doubles.tryParse(input));
+ assertThat(Doubles.tryParse(input)).isEqualTo(Double.valueOf(expected));
assertThat(input)
.matches(
Pattern.compile(
Doubles.FLOATING_POINT_PATTERN.pattern(), Doubles.FLOATING_POINT_PATTERN.flags()));
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseHex() {
for (String signChar : ImmutableList.of("", "+", "-")) {
@@ -569,6 +678,7 @@ public class DoublesTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseAllCodePoints() {
// Exercise non-ASCII digit test cases and the like.
@@ -579,6 +689,7 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseOfToStringIsOriginal() {
for (double d : NUMBERS) {
@@ -586,6 +697,7 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseOfToHexStringIsOriginal() {
for (double d : NUMBERS) {
@@ -593,6 +705,7 @@ public class DoublesTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseNaN() {
checkTryParse("NaN");
@@ -600,6 +713,7 @@ public class DoublesTest extends TestCase {
checkTryParse("-NaN");
}
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseInfinity() {
checkTryParse(Double.POSITIVE_INFINITY, "Infinity");
@@ -624,6 +738,7 @@ public class DoublesTest extends TestCase {
"InfinityF"
};
+ @J2ktIncompatible
@GwtIncompatible // Doubles.tryParse
public void testTryParseFailures() {
for (String badInput : BAD_TRY_PARSE_INPUTS) {
@@ -632,11 +747,12 @@ public class DoublesTest extends TestCase {
Pattern.compile(
Doubles.FLOATING_POINT_PATTERN.pattern(),
Doubles.FLOATING_POINT_PATTERN.flags()));
- assertEquals(referenceTryParse(badInput), Doubles.tryParse(badInput));
- assertNull(Doubles.tryParse(badInput));
+ assertThat(Doubles.tryParse(badInput)).isEqualTo(referenceTryParse(badInput));
+ assertThat(Doubles.tryParse(badInput)).isNull();
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Doubles.class);
@@ -644,14 +760,14 @@ public class DoublesTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Double> converter = Doubles.stringConverter();
- assertEquals((Double) 1.0, converter.convert("1.0"));
- assertEquals((Double) 0.0, converter.convert("0.0"));
- assertEquals((Double) (-1.0), converter.convert("-1.0"));
- assertEquals((Double) 1.0, converter.convert("1"));
- assertEquals((Double) 0.0, converter.convert("0"));
- assertEquals((Double) (-1.0), converter.convert("-1"));
- assertEquals((Double) 1e6, converter.convert("1e6"));
- assertEquals((Double) 1e-6, converter.convert("1e-6"));
+ assertThat(converter.convert("1.0")).isEqualTo((Double) 1.0);
+ assertThat(converter.convert("0.0")).isEqualTo((Double) 0.0);
+ assertThat(converter.convert("-1.0")).isEqualTo((Double) (-1.0));
+ assertThat(converter.convert("1")).isEqualTo((Double) 1.0);
+ assertThat(converter.convert("0")).isEqualTo((Double) 0.0);
+ assertThat(converter.convert("-1")).isEqualTo((Double) (-1.0));
+ assertThat(converter.convert("1e6")).isEqualTo((Double) 1e6);
+ assertThat(converter.convert("1e-6")).isEqualTo((Double) 1e-6);
}
public void testStringConverter_convertError() {
@@ -663,29 +779,32 @@ public class DoublesTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Doubles.stringConverter().convert(null));
- assertNull(Doubles.stringConverter().reverse().convert(null));
+ assertThat(Doubles.stringConverter().convert(null)).isNull();
+ assertThat(Doubles.stringConverter().reverse().convert(null)).isNull();
}
+ @J2ktIncompatible
@GwtIncompatible // Double.toString returns different value in GWT.
public void testStringConverter_reverse() {
Converter<String, Double> converter = Doubles.stringConverter();
- assertEquals("1.0", converter.reverse().convert(1.0));
- assertEquals("0.0", converter.reverse().convert(0.0));
- assertEquals("-1.0", converter.reverse().convert(-1.0));
- assertEquals("1000000.0", converter.reverse().convert(1e6));
- assertEquals("1.0E-6", converter.reverse().convert(1e-6));
+ assertThat(converter.reverse().convert(1.0)).isEqualTo("1.0");
+ assertThat(converter.reverse().convert(0.0)).isEqualTo("0.0");
+ assertThat(converter.reverse().convert(-1.0)).isEqualTo("-1.0");
+ assertThat(converter.reverse().convert(1e6)).isEqualTo("1000000.0");
+ assertThat(converter.reverse().convert(1e-6)).isEqualTo("1.0E-6");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicInstanceMethods(Doubles.stringConverter());
}
+ @J2ktIncompatible
@GwtIncompatible
public void testTryParse_withNullNoGwt() {
- assertNull(Doubles.tryParse("null"));
+ assertThat(Doubles.tryParse("null")).isNull();
try {
Doubles.tryParse(null);
fail("Expected NPE");
diff --git a/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java
index 233a0211b..c70a8b5d0 100644
--- a/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class FloatArrayAsListTest extends TestCase {
return Floats.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Float>> builders =
diff --git a/guava-tests/test/com/google/common/primitives/FloatsTest.java b/guava-tests/test/com/google/common/primitives/FloatsTest.java
index fd59ad4d8..4a1e8fbc8 100644
--- a/guava-tests/test/com/google/common/primitives/FloatsTest.java
+++ b/guava-tests/test/com/google/common/primitives/FloatsTest.java
@@ -17,10 +17,12 @@
package com.google.common.primitives;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Float.NaN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.Helpers;
@@ -32,14 +34,15 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Floats}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
-@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class FloatsTest extends TestCase {
private static final float[] EMPTY = {};
private static final float[] ARRAY1 = {(float) 1};
@@ -72,13 +75,14 @@ public class FloatsTest extends TestCase {
public void testHashCode() {
for (float value : VALUES) {
- assertEquals(((Float) value).hashCode(), Floats.hashCode(value));
+ assertThat(Floats.hashCode(value)).isEqualTo(((Float) value).hashCode());
}
}
public void testIsFinite() {
for (float value : NUMBERS) {
- assertEquals(!(Float.isInfinite(value) || Float.isNaN(value)), Floats.isFinite(value));
+ assertThat(Floats.isFinite(value))
+ .isEqualTo(!(Float.isInfinite(value) || Float.isNaN(value)));
}
}
@@ -86,106 +90,114 @@ public class FloatsTest extends TestCase {
for (float x : VALUES) {
for (float y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Float.valueOf(x).compareTo(y), Floats.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Floats.compare(x, y))
+ .isEqualTo(Float.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Floats.contains(EMPTY, (float) 1));
- assertFalse(Floats.contains(ARRAY1, (float) 2));
- assertFalse(Floats.contains(ARRAY234, (float) 1));
- assertTrue(Floats.contains(new float[] {(float) -1}, (float) -1));
- assertTrue(Floats.contains(ARRAY234, (float) 2));
- assertTrue(Floats.contains(ARRAY234, (float) 3));
- assertTrue(Floats.contains(ARRAY234, (float) 4));
+ assertThat(Floats.contains(EMPTY, (float) 1)).isFalse();
+ assertThat(Floats.contains(ARRAY1, (float) 2)).isFalse();
+ assertThat(Floats.contains(ARRAY234, (float) 1)).isFalse();
+ assertThat(Floats.contains(new float[] {(float) -1}, (float) -1)).isTrue();
+ assertThat(Floats.contains(ARRAY234, (float) 2)).isTrue();
+ assertThat(Floats.contains(ARRAY234, (float) 3)).isTrue();
+ assertThat(Floats.contains(ARRAY234, (float) 4)).isTrue();
for (float value : NUMBERS) {
- assertTrue("" + value, Floats.contains(new float[] {5f, value}, value));
+ assertWithMessage("" + value).that(Floats.contains(new float[] {5f, value}, value)).isTrue();
}
- assertFalse(Floats.contains(new float[] {5f, NaN}, NaN));
+ assertThat(Floats.contains(new float[] {5f, NaN}, NaN)).isFalse();
}
public void testIndexOf() {
- assertEquals(-1, Floats.indexOf(EMPTY, (float) 1));
- assertEquals(-1, Floats.indexOf(ARRAY1, (float) 2));
- assertEquals(-1, Floats.indexOf(ARRAY234, (float) 1));
- assertEquals(0, Floats.indexOf(new float[] {(float) -1}, (float) -1));
- assertEquals(0, Floats.indexOf(ARRAY234, (float) 2));
- assertEquals(1, Floats.indexOf(ARRAY234, (float) 3));
- assertEquals(2, Floats.indexOf(ARRAY234, (float) 4));
- assertEquals(
- 1, Floats.indexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3));
+ assertThat(Floats.indexOf(EMPTY, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY1, (float) 2)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY234, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.indexOf(new float[] {(float) -1}, (float) -1)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, (float) 2)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, (float) 3)).isEqualTo(1);
+ assertThat(Floats.indexOf(ARRAY234, (float) 4)).isEqualTo(2);
+ assertThat(Floats.indexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3))
+ .isEqualTo(1);
for (float value : NUMBERS) {
- assertEquals("" + value, 1, Floats.indexOf(new float[] {5f, value}, value));
+ assertWithMessage("" + value)
+ .that(Floats.indexOf(new float[] {5f, value}, value))
+ .isEqualTo(1);
}
- assertEquals(-1, Floats.indexOf(new float[] {5f, NaN}, NaN));
+ assertThat(Floats.indexOf(new float[] {5f, NaN}, NaN)).isEqualTo(-1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Floats.indexOf(EMPTY, EMPTY));
- assertEquals(0, Floats.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Floats.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Floats.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Floats.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Floats.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Floats.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Floats.indexOf(ARRAY234, new float[] {(float) 2, (float) 3}));
- assertEquals(1, Floats.indexOf(ARRAY234, new float[] {(float) 3, (float) 4}));
- assertEquals(1, Floats.indexOf(ARRAY234, new float[] {(float) 3}));
- assertEquals(2, Floats.indexOf(ARRAY234, new float[] {(float) 4}));
- assertEquals(
- 1,
- Floats.indexOf(
- new float[] {(float) 2, (float) 3, (float) 3, (float) 3, (float) 3},
- new float[] {(float) 3}));
- assertEquals(
- 2,
- Floats.indexOf(
- new float[] {
- (float) 2, (float) 3, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3
- },
- new float[] {(float) 2, (float) 3, (float) 4}));
- assertEquals(
- 1,
- Floats.indexOf(
- new float[] {
- (float) 2, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3, (float) 4
- },
- new float[] {(float) 2, (float) 3, (float) 4}));
- assertEquals(
- -1,
- Floats.indexOf(
- new float[] {(float) 4, (float) 3, (float) 2},
- new float[] {(float) 2, (float) 3, (float) 4}));
+ assertThat(Floats.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Floats.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Floats.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 2, (float) 3})).isEqualTo(0);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 3, (float) 4})).isEqualTo(1);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 3})).isEqualTo(1);
+ assertThat(Floats.indexOf(ARRAY234, new float[] {(float) 4})).isEqualTo(2);
+ assertThat(
+ Floats.indexOf(
+ new float[] {(float) 2, (float) 3, (float) 3, (float) 3, (float) 3},
+ new float[] {(float) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Floats.indexOf(
+ new float[] {
+ (float) 2, (float) 3, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3
+ },
+ new float[] {(float) 2, (float) 3, (float) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Floats.indexOf(
+ new float[] {
+ (float) 2, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3, (float) 4
+ },
+ new float[] {(float) 2, (float) 3, (float) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Floats.indexOf(
+ new float[] {(float) 4, (float) 3, (float) 2},
+ new float[] {(float) 2, (float) 3, (float) 4}))
+ .isEqualTo(-1);
for (float value : NUMBERS) {
- assertEquals(
- "" + value,
- 1,
- Floats.indexOf(new float[] {5f, value, value, 5f}, new float[] {value, value}));
+ assertWithMessage("" + value)
+ .that(Floats.indexOf(new float[] {5f, value, value, 5f}, new float[] {value, value}))
+ .isEqualTo(1);
}
- assertEquals(-1, Floats.indexOf(new float[] {5f, NaN, NaN, 5f}, new float[] {NaN, NaN}));
+ assertThat(Floats.indexOf(new float[] {5f, NaN, NaN, 5f}, new float[] {NaN, NaN}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Floats.lastIndexOf(EMPTY, (float) 1));
- assertEquals(-1, Floats.lastIndexOf(ARRAY1, (float) 2));
- assertEquals(-1, Floats.lastIndexOf(ARRAY234, (float) 1));
- assertEquals(0, Floats.lastIndexOf(new float[] {(float) -1}, (float) -1));
- assertEquals(0, Floats.lastIndexOf(ARRAY234, (float) 2));
- assertEquals(1, Floats.lastIndexOf(ARRAY234, (float) 3));
- assertEquals(2, Floats.lastIndexOf(ARRAY234, (float) 4));
- assertEquals(
- 3, Floats.lastIndexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3));
+ assertThat(Floats.lastIndexOf(EMPTY, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.lastIndexOf(ARRAY1, (float) 2)).isEqualTo(-1);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 1)).isEqualTo(-1);
+ assertThat(Floats.lastIndexOf(new float[] {(float) -1}, (float) -1)).isEqualTo(0);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 2)).isEqualTo(0);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 3)).isEqualTo(1);
+ assertThat(Floats.lastIndexOf(ARRAY234, (float) 4)).isEqualTo(2);
+ assertThat(
+ Floats.lastIndexOf(new float[] {(float) 2, (float) 3, (float) 2, (float) 3}, (float) 3))
+ .isEqualTo(3);
for (float value : NUMBERS) {
- assertEquals("" + value, 0, Floats.lastIndexOf(new float[] {value, 5f}, value));
+ assertWithMessage("" + value)
+ .that(Floats.lastIndexOf(new float[] {value, 5f}, value))
+ .isEqualTo(0);
}
- assertEquals(-1, Floats.lastIndexOf(new float[] {NaN, 5f}, NaN));
+ assertThat(Floats.lastIndexOf(new float[] {NaN, 5f}, NaN)).isEqualTo(-1);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -196,18 +208,19 @@ public class FloatsTest extends TestCase {
}
public void testMax() {
- assertEquals(GREATEST, Floats.max(GREATEST));
- assertEquals(LEAST, Floats.max(LEAST));
- assertEquals(
- (float) 9,
- Floats.max((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9));
+ assertThat(Floats.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Floats.max(LEAST)).isEqualTo(LEAST);
+ assertThat(
+ Floats.max((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9))
+ .isEqualTo((float) 9);
- assertEquals(0f, Floats.max(-0f, 0f));
- assertEquals(0f, Floats.max(0f, -0f));
- assertEquals(GREATEST, Floats.max(NUMBERS));
- assertTrue(Float.isNaN(Floats.max(VALUES)));
+ assertThat(Floats.max(-0f, 0f)).isEqualTo(0f);
+ assertThat(Floats.max(0f, -0f)).isEqualTo(0f);
+ assertThat(Floats.max(NUMBERS)).isEqualTo(GREATEST);
+ assertThat(Float.isNaN(Floats.max(VALUES))).isTrue();
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -218,25 +231,24 @@ public class FloatsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Floats.min(LEAST));
- assertEquals(GREATEST, Floats.min(GREATEST));
- assertEquals(
- (float) 0,
- Floats.min((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9));
+ assertThat(Floats.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Floats.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Floats.min((float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9))
+ .isEqualTo((float) 0);
- assertEquals(-0f, Floats.min(-0f, 0f));
- assertEquals(-0f, Floats.min(0f, -0f));
- assertEquals(LEAST, Floats.min(NUMBERS));
- assertTrue(Float.isNaN(Floats.min(VALUES)));
+ assertThat(Floats.min(-0f, 0f)).isEqualTo(-0f);
+ assertThat(Floats.min(0f, -0f)).isEqualTo(-0f);
+ assertThat(Floats.min(NUMBERS)).isEqualTo(LEAST);
+ assertThat(Float.isNaN(Floats.min(VALUES))).isTrue();
}
public void testConstrainToRange() {
- float tolerance = 1e-10f;
- assertEquals((float) 1, Floats.constrainToRange((float) 1, (float) 0, (float) 5), tolerance);
- assertEquals((float) 1, Floats.constrainToRange((float) 1, (float) 1, (float) 5), tolerance);
- assertEquals((float) 3, Floats.constrainToRange((float) 1, (float) 3, (float) 5), tolerance);
- assertEquals((float) -1, Floats.constrainToRange((float) 0, (float) -5, (float) -1), tolerance);
- assertEquals((float) 2, Floats.constrainToRange((float) 5, (float) 2, (float) 2), tolerance);
+ assertThat(Floats.constrainToRange((float) 1, (float) 0, (float) 5)).isEqualTo((float) 1);
+ assertThat(Floats.constrainToRange((float) 1, (float) 1, (float) 5)).isEqualTo((float) 1);
+ assertThat(Floats.constrainToRange((float) 1, (float) 3, (float) 5)).isEqualTo((float) 3);
+ assertThat(Floats.constrainToRange((float) 0, (float) -5, (float) -1)).isEqualTo((float) -1);
+ assertThat(Floats.constrainToRange((float) 5, (float) 2, (float) 2)).isEqualTo((float) 2);
try {
Floats.constrainToRange((float) 1, (float) 3, (float) 2);
fail();
@@ -245,28 +257,26 @@ public class FloatsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Floats.concat()));
- assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Floats.concat(ARRAY1)));
- assertNotSame(ARRAY1, Floats.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Floats.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new float[] {(float) 1, (float) 1, (float) 1}, Floats.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new float[] {(float) 1, (float) 2, (float) 3, (float) 4},
- Floats.concat(ARRAY1, ARRAY234)));
+ assertThat(Floats.concat()).isEqualTo(EMPTY);
+ assertThat(Floats.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Floats.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Floats.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Floats.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Floats.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Floats.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new float[] {(float) 1, (float) 1, (float) 1});
+ assertThat(Floats.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new float[] {(float) 1, (float) 2, (float) 3, (float) 4});
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Floats.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new float[] {(float) 1, (float) 0, (float) 0}, Floats.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Floats.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Floats.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Floats.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(
+ Arrays.equals(
+ new float[] {(float) 1, (float) 0, (float) 0}, Floats.ensureCapacity(ARRAY1, 2, 1)))
+ .isTrue();
}
public void testEnsureCapacity_fail() {
@@ -283,12 +293,13 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Float.toString returns different value in GWT.
public void testJoin() {
- assertEquals("", Floats.join(",", EMPTY));
- assertEquals("1.0", Floats.join(",", ARRAY1));
- assertEquals("1.0,2.0", Floats.join(",", (float) 1, (float) 2));
- assertEquals("1.02.03.0", Floats.join("", (float) 1, (float) 2, (float) 3));
+ assertThat(Floats.join(",", EMPTY)).isEmpty();
+ assertThat(Floats.join(",", ARRAY1)).isEqualTo("1.0");
+ assertThat(Floats.join(",", (float) 1, (float) 2)).isEqualTo("1.0,2.0");
+ assertThat(Floats.join("", (float) 1, (float) 2, (float) 3)).isEqualTo("1.02.03.0");
}
public void testLexicographicalComparator() {
@@ -308,10 +319,11 @@ public class FloatsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<float[]> comparator = Floats.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -325,14 +337,14 @@ public class FloatsTest extends TestCase {
private static void testReverse(float[] input, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
float[] input, int fromIndex, int toIndex, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -344,6 +356,103 @@ public class FloatsTest extends TestCase {
testReverse(new float[] {-1, 1, -2, 2}, 1, 3, new float[] {-1, -2, 1, 2});
}
+ private static void testRotate(float[] input, int distance, float[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Floats.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ float[] input, int distance, int fromIndex, int toIndex, float[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Floats.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new float[] {}, -1, new float[] {});
+ testRotate(new float[] {}, 0, new float[] {});
+ testRotate(new float[] {}, 1, new float[] {});
+
+ testRotate(new float[] {1}, -2, new float[] {1});
+ testRotate(new float[] {1}, -1, new float[] {1});
+ testRotate(new float[] {1}, 0, new float[] {1});
+ testRotate(new float[] {1}, 1, new float[] {1});
+ testRotate(new float[] {1}, 2, new float[] {1});
+
+ testRotate(new float[] {1, 2}, -3, new float[] {2, 1});
+ testRotate(new float[] {1, 2}, -1, new float[] {2, 1});
+ testRotate(new float[] {1, 2}, -2, new float[] {1, 2});
+ testRotate(new float[] {1, 2}, 0, new float[] {1, 2});
+ testRotate(new float[] {1, 2}, 1, new float[] {2, 1});
+ testRotate(new float[] {1, 2}, 2, new float[] {1, 2});
+ testRotate(new float[] {1, 2}, 3, new float[] {2, 1});
+
+ testRotate(new float[] {1, 2, 3}, -5, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, -4, new float[] {2, 3, 1});
+ testRotate(new float[] {1, 2, 3}, -3, new float[] {1, 2, 3});
+ testRotate(new float[] {1, 2, 3}, -2, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, -1, new float[] {2, 3, 1});
+ testRotate(new float[] {1, 2, 3}, 0, new float[] {1, 2, 3});
+ testRotate(new float[] {1, 2, 3}, 1, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, 2, new float[] {2, 3, 1});
+ testRotate(new float[] {1, 2, 3}, 3, new float[] {1, 2, 3});
+ testRotate(new float[] {1, 2, 3}, 4, new float[] {3, 1, 2});
+ testRotate(new float[] {1, 2, 3}, 5, new float[] {2, 3, 1});
+
+ testRotate(new float[] {1, 2, 3, 4}, -9, new float[] {2, 3, 4, 1});
+ testRotate(new float[] {1, 2, 3, 4}, -5, new float[] {2, 3, 4, 1});
+ testRotate(new float[] {1, 2, 3, 4}, -1, new float[] {2, 3, 4, 1});
+ testRotate(new float[] {1, 2, 3, 4}, 0, new float[] {1, 2, 3, 4});
+ testRotate(new float[] {1, 2, 3, 4}, 1, new float[] {4, 1, 2, 3});
+ testRotate(new float[] {1, 2, 3, 4}, 5, new float[] {4, 1, 2, 3});
+ testRotate(new float[] {1, 2, 3, 4}, 9, new float[] {4, 1, 2, 3});
+
+ testRotate(new float[] {1, 2, 3, 4, 5}, -6, new float[] {2, 3, 4, 5, 1});
+ testRotate(new float[] {1, 2, 3, 4, 5}, -4, new float[] {5, 1, 2, 3, 4});
+ testRotate(new float[] {1, 2, 3, 4, 5}, -3, new float[] {4, 5, 1, 2, 3});
+ testRotate(new float[] {1, 2, 3, 4, 5}, -1, new float[] {2, 3, 4, 5, 1});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 0, new float[] {1, 2, 3, 4, 5});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 1, new float[] {5, 1, 2, 3, 4});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 3, new float[] {3, 4, 5, 1, 2});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 4, new float[] {2, 3, 4, 5, 1});
+ testRotate(new float[] {1, 2, 3, 4, 5}, 6, new float[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new float[] {}, 0, 0, 0, new float[] {});
+
+ testRotate(new float[] {1}, 0, 0, 1, new float[] {1});
+ testRotate(new float[] {1}, 1, 0, 1, new float[] {1});
+ testRotate(new float[] {1}, 1, 1, 1, new float[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new float[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new float[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new float[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new float[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new float[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new float[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new float[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new float[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new float[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new float[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new float[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new float[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new float[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new float[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new float[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new float[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new float[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new float[] {}, new float[] {});
testSortDescending(new float[] {1}, new float[] {1});
@@ -351,15 +460,15 @@ public class FloatsTest extends TestCase {
testSortDescending(new float[] {1, 3, 1}, new float[] {3, 1, 1});
testSortDescending(new float[] {-1, 1, -2, 2}, new float[] {2, 1, -1, -2});
testSortDescending(
- new float[] {-1, 1, Float.NaN, -2, -0, 0, 2}, new float[] {Float.NaN, 2, 1, 0, -0, -1, -2});
+ new float[] {-1, 1, Float.NaN, -2, -0f, 0, 2},
+ new float[] {Float.NaN, 2, 1, 0, -0f, -1, -2});
}
private static void testSortDescending(float[] input, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.sortDescending(input);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Float.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -367,9 +476,8 @@ public class FloatsTest extends TestCase {
float[] input, int fromIndex, int toIndex, float[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Floats.sortDescending(input, fromIndex, toIndex);
- // GWT's Arrays.equals doesn't appear to handle NaN correctly, so test each element individually
for (int i = 0; i < input.length; i++) {
- assertEquals(0, Float.compare(expectedOutput[i], input[i]));
+ assertThat(input[i]).isEqualTo(expectedOutput[i]);
}
}
@@ -384,6 +492,7 @@ public class FloatsTest extends TestCase {
new float[] {-1, 1, Float.NaN, -2, 2}, 1, 4, new float[] {-1, Float.NaN, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Floats.stringConverter());
@@ -392,17 +501,17 @@ public class FloatsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Float> none = Arrays.<Float>asList();
- assertTrue(Arrays.equals(EMPTY, Floats.toArray(none)));
+ assertThat(Floats.toArray(none)).isEqualTo(EMPTY);
List<Float> one = Arrays.asList((float) 1);
- assertTrue(Arrays.equals(ARRAY1, Floats.toArray(one)));
+ assertThat(Floats.toArray(one)).isEqualTo(ARRAY1);
float[] array = {(float) 0, (float) 1, (float) 3};
List<Float> three = Arrays.asList((float) 0, (float) 1, (float) 3);
- assertTrue(Arrays.equals(array, Floats.toArray(three)));
+ assertThat(Floats.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Floats.toArray(Floats.asList(array))));
+ assertThat(Floats.toArray(Floats.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -412,16 +521,16 @@ public class FloatsTest extends TestCase {
Collection<Float> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
float[] arr = Floats.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr.length).isEqualTo(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Float> list = Arrays.asList((float) 0, (float) 1, null);
+ List<@Nullable Float> list = Arrays.asList((float) 0, (float) 1, null);
try {
Floats.toArray(list);
fail();
@@ -439,19 +548,20 @@ public class FloatsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Floats.toArray(bytes)));
- assertTrue(Arrays.equals(array, Floats.toArray(shorts)));
- assertTrue(Arrays.equals(array, Floats.toArray(ints)));
- assertTrue(Arrays.equals(array, Floats.toArray(floats)));
- assertTrue(Arrays.equals(array, Floats.toArray(longs)));
- assertTrue(Arrays.equals(array, Floats.toArray(doubles)));
+ assertThat(Floats.toArray(bytes)).isEqualTo(array);
+ assertThat(Floats.toArray(shorts)).isEqualTo(array);
+ assertThat(Floats.toArray(ints)).isEqualTo(array);
+ assertThat(Floats.toArray(floats)).isEqualTo(array);
+ assertThat(Floats.toArray(longs)).isEqualTo(array);
+ assertThat(Floats.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
float[] array = {(float) 0, (float) 1};
List<Float> list = Floats.asList(array);
list.set(0, (float) 2);
- assertTrue(Arrays.equals(new float[] {(float) 2, (float) 1}, array));
+ assertThat(array).isEqualTo(new float[] {(float) 2, (float) 1});
array[1] = (float) 3;
assertThat(list).containsExactly((float) 2, (float) 3).inOrder();
}
@@ -463,29 +573,28 @@ public class FloatsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (float) 4);
- assertTrue(Arrays.equals(new float[] {(float) 0, (float) 1, (float) 2}, newArray));
+ assertThat(newArray).isEqualTo(new float[] {(float) 0, (float) 1, (float) 2});
newArray[1] = (float) 5;
- assertEquals((float) 1, (float) list.get(1));
+ assertThat((float) list.get(1)).isEqualTo((float) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
float[] array = {(float) 0, (float) 1, (float) 2, (float) 3};
List<Float> list = Floats.asList(array);
- assertTrue(
- Arrays.equals(new float[] {(float) 1, (float) 2}, Floats.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new float[] {}, Floats.toArray(list.subList(2, 2))));
+ assertThat(Floats.toArray(list.subList(1, 3))).isEqualTo(new float[] {(float) 1, (float) 2});
+ assertThat(Floats.toArray(list.subList(2, 2))).isEmpty();
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Floats.asList(EMPTY));
+ assertThat(Floats.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
/**
* A reference implementation for {@code tryParse} that just catches the exception from {@link
* Float#valueOf}.
*/
- private static Float referenceTryParse(String input) {
+ private static @Nullable Float referenceTryParse(String input) {
if (input.trim().length() < input.length()) {
return null;
}
@@ -496,16 +605,19 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
private static void checkTryParse(String input) {
- assertEquals(referenceTryParse(input), Floats.tryParse(input));
+ assertThat(Floats.tryParse(input)).isEqualTo(referenceTryParse(input));
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
private static void checkTryParse(float expected, String input) {
- assertEquals(Float.valueOf(expected), Floats.tryParse(input));
+ assertThat(Floats.tryParse(input)).isEqualTo(Float.valueOf(expected));
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseHex() {
for (String signChar : ImmutableList.of("", "+", "-")) {
@@ -527,6 +639,7 @@ public class FloatsTest extends TestCase {
}
@AndroidIncompatible // slow
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseAllCodePoints() {
// Exercise non-ASCII digit test cases and the like.
@@ -537,6 +650,7 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseOfToStringIsOriginal() {
for (float f : NUMBERS) {
@@ -544,6 +658,7 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseOfToHexStringIsOriginal() {
for (float f : NUMBERS) {
@@ -551,6 +666,7 @@ public class FloatsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseNaN() {
checkTryParse("NaN");
@@ -558,6 +674,7 @@ public class FloatsTest extends TestCase {
checkTryParse("-NaN");
}
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseInfinity() {
checkTryParse(Float.POSITIVE_INFINITY, "Infinity");
@@ -582,30 +699,33 @@ public class FloatsTest extends TestCase {
"InfinityF"
};
+ @J2ktIncompatible
@GwtIncompatible // Floats.tryParse
public void testTryParseFailures() {
for (String badInput : BAD_TRY_PARSE_INPUTS) {
- assertEquals(referenceTryParse(badInput), Floats.tryParse(badInput));
- assertNull(Floats.tryParse(badInput));
+ assertThat(Floats.tryParse(badInput)).isEqualTo(referenceTryParse(badInput));
+ assertThat(Floats.tryParse(badInput)).isNull();
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Floats.class);
}
+ @J2ktIncompatible
@GwtIncompatible // Float.toString returns different value in GWT.
public void testStringConverter_convert() {
Converter<String, Float> converter = Floats.stringConverter();
- assertEquals((Float) 1.0f, converter.convert("1.0"));
- assertEquals((Float) 0.0f, converter.convert("0.0"));
- assertEquals((Float) (-1.0f), converter.convert("-1.0"));
- assertEquals((Float) 1.0f, converter.convert("1"));
- assertEquals((Float) 0.0f, converter.convert("0"));
- assertEquals((Float) (-1.0f), converter.convert("-1"));
- assertEquals((Float) 1e6f, converter.convert("1e6"));
- assertEquals((Float) 1e-6f, converter.convert("1e-6"));
+ assertThat(converter.convert("1.0")).isEqualTo((Float) 1.0f);
+ assertThat(converter.convert("0.0")).isEqualTo((Float) 0.0f);
+ assertThat(converter.convert("-1.0")).isEqualTo((Float) (-1.0f));
+ assertThat(converter.convert("1")).isEqualTo((Float) 1.0f);
+ assertThat(converter.convert("0")).isEqualTo((Float) 0.0f);
+ assertThat(converter.convert("-1")).isEqualTo((Float) (-1.0f));
+ assertThat(converter.convert("1e6")).isEqualTo((Float) 1e6f);
+ assertThat(converter.convert("1e-6")).isEqualTo((Float) 1e-6f);
}
public void testStringConverter_convertError() {
@@ -617,29 +737,32 @@ public class FloatsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Floats.stringConverter().convert(null));
- assertNull(Floats.stringConverter().reverse().convert(null));
+ assertThat(Floats.stringConverter().convert(null)).isNull();
+ assertThat(Floats.stringConverter().reverse().convert(null)).isNull();
}
+ @J2ktIncompatible
@GwtIncompatible // Float.toString returns different value in GWT.
public void testStringConverter_reverse() {
Converter<String, Float> converter = Floats.stringConverter();
- assertEquals("1.0", converter.reverse().convert(1.0f));
- assertEquals("0.0", converter.reverse().convert(0.0f));
- assertEquals("-1.0", converter.reverse().convert(-1.0f));
- assertEquals("1000000.0", converter.reverse().convert(1e6f));
- assertEquals("1.0E-6", converter.reverse().convert(1e-6f));
+ assertThat(converter.reverse().convert(1.0f)).isEqualTo("1.0");
+ assertThat(converter.reverse().convert(0.0f)).isEqualTo("0.0");
+ assertThat(converter.reverse().convert(-1.0f)).isEqualTo("-1.0");
+ assertThat(converter.reverse().convert(1e6f)).isEqualTo("1000000.0");
+ assertThat(converter.reverse().convert(1e-6f)).isEqualTo("1.0E-6");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicInstanceMethods(Floats.stringConverter());
}
+ @J2ktIncompatible
@GwtIncompatible
public void testTryParse_withNullNoGwt() {
- assertNull(Floats.tryParse("null"));
+ assertThat(Floats.tryParse("null")).isNull();
try {
Floats.tryParse(null);
fail("Expected NPE");
diff --git a/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java b/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
index 82bc49f3c..e7f5c97bb 100644
--- a/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
+++ b/guava-tests/test/com/google/common/primitives/ImmutableDoubleArrayTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.testing.ListTestSuiteBuilder;
@@ -353,7 +354,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
AtomicInteger count = new AtomicInteger(0);
ImmutableDoubleArray.of(0, 1, 2, 3)
.forEach(i -> assertThat(i).isEqualTo((double) count.getAndIncrement()));
- assertEquals(4, count.get());
+ assertThat(count.get()).isEqualTo(4);
}
public void testStream() {
@@ -435,6 +436,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
assertActuallyTrims(underSized);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
assertThat(reserialize(ImmutableDoubleArray.of())).isSameInstanceAs(ImmutableDoubleArray.of());
@@ -459,6 +461,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
assertThat(iia.trimmed()).isSameInstanceAs(iia);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Double>> builders =
@@ -490,6 +493,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
return suite;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static ImmutableDoubleArray makeArray(Double[] values) {
return ImmutableDoubleArray.copyOf(Arrays.asList(values));
@@ -498,6 +502,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
// Test generators. To let the GWT test suite generator access them, they need to be public named
// classes with a public default constructor (not that we run these suites under GWT yet).
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayAsListGenerator extends TestDoubleListGenerator {
@Override
@@ -506,6 +511,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayHeadSubListAsListGenerator
extends TestDoubleListGenerator {
@@ -517,6 +523,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayTailSubListAsListGenerator
extends TestDoubleListGenerator {
@@ -528,6 +535,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableDoubleArrayMiddleSubListAsListGenerator
extends TestDoubleListGenerator {
@@ -540,11 +548,13 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static Double[] concat(Double[] a, Double[] b) {
return ObjectArrays.concat(a, b, Double.class);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public abstract static class TestDoubleListGenerator implements TestListGenerator<Double> {
@Override
@@ -580,6 +590,7 @@ public class ImmutableDoubleArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static class SampleDoubles extends SampleElements<Double> {
public SampleDoubles() {
diff --git a/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java b/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java
index 6a9eeade5..7e1173047 100644
--- a/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java
+++ b/guava-tests/test/com/google/common/primitives/ImmutableIntArrayTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.testing.ListTestSuiteBuilder;
@@ -339,7 +340,7 @@ public class ImmutableIntArrayTest extends TestCase {
AtomicInteger count = new AtomicInteger(0);
ImmutableIntArray.of(0, 1, 2, 3).forEach(i -> assertThat(i).isEqualTo(count.getAndIncrement()));
- assertEquals(4, count.get());
+ assertThat(count.get()).isEqualTo(4);
}
public void testStream() {
@@ -420,6 +421,7 @@ public class ImmutableIntArrayTest extends TestCase {
assertActuallyTrims(underSized);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
assertThat(reserialize(ImmutableIntArray.of())).isSameInstanceAs(ImmutableIntArray.of());
@@ -444,6 +446,7 @@ public class ImmutableIntArrayTest extends TestCase {
assertThat(iia.trimmed()).isSameInstanceAs(iia);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Integer>> builders =
@@ -475,6 +478,7 @@ public class ImmutableIntArrayTest extends TestCase {
return suite;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static ImmutableIntArray makeArray(Integer[] values) {
return ImmutableIntArray.copyOf(Arrays.asList(values));
@@ -483,6 +487,7 @@ public class ImmutableIntArrayTest extends TestCase {
// Test generators. To let the GWT test suite generator access them, they need to be public named
// classes with a public default constructor (not that we run these suites under GWT yet).
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayAsListGenerator extends TestIntegerListGenerator {
@Override
@@ -491,6 +496,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayHeadSubListAsListGenerator
extends TestIntegerListGenerator {
@@ -502,6 +508,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayTailSubListAsListGenerator
extends TestIntegerListGenerator {
@@ -513,6 +520,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableIntArrayMiddleSubListAsListGenerator
extends TestIntegerListGenerator {
@@ -525,11 +533,13 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static Integer[] concat(Integer[] a, Integer[] b) {
return ObjectArrays.concat(a, b, Integer.class);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public abstract static class TestIntegerListGenerator implements TestListGenerator<Integer> {
@Override
@@ -565,6 +575,7 @@ public class ImmutableIntArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static class SampleIntegers extends SampleElements<Integer> {
public SampleIntegers() {
diff --git a/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java b/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java
index e4621fcbe..0584195f1 100644
--- a/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java
+++ b/guava-tests/test/com/google/common/primitives/ImmutableLongArrayTest.java
@@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.testing.ListTestSuiteBuilder;
@@ -342,7 +343,7 @@ public class ImmutableLongArrayTest extends TestCase {
AtomicLong count = new AtomicLong(0);
ImmutableLongArray.of(0, 1, 2, 3)
.forEach(i -> assertThat(i).isEqualTo(count.getAndIncrement()));
- assertEquals(4, count.get());
+ assertThat(count.get()).isEqualTo(4);
}
public void testStream() {
@@ -423,6 +424,7 @@ public class ImmutableLongArrayTest extends TestCase {
assertActuallyTrims(underSized);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testSerialization() {
assertThat(reserialize(ImmutableLongArray.of())).isSameInstanceAs(ImmutableLongArray.of());
@@ -447,6 +449,7 @@ public class ImmutableLongArrayTest extends TestCase {
assertThat(iia.trimmed()).isSameInstanceAs(iia);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Long>> builders =
@@ -478,6 +481,7 @@ public class ImmutableLongArrayTest extends TestCase {
return suite;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static ImmutableLongArray makeArray(Long[] values) {
return ImmutableLongArray.copyOf(Arrays.asList(values));
@@ -486,6 +490,7 @@ public class ImmutableLongArrayTest extends TestCase {
// Test generators. To let the GWT test suite generator access them, they need to be public named
// classes with a public default constructor (not that we run these suites under GWT yet).
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayAsListGenerator extends TestLongListGenerator {
@Override
@@ -494,6 +499,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayHeadSubListAsListGenerator
extends TestLongListGenerator {
@@ -505,6 +511,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayTailSubListAsListGenerator
extends TestLongListGenerator {
@@ -516,6 +523,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static final class ImmutableLongArrayMiddleSubListAsListGenerator
extends TestLongListGenerator {
@@ -528,11 +536,13 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
private static Long[] concat(Long[] a, Long[] b) {
return ObjectArrays.concat(a, b, Long.class);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public abstract static class TestLongListGenerator implements TestListGenerator<Long> {
@Override
@@ -568,6 +578,7 @@ public class ImmutableLongArrayTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // used only from suite
public static class SampleLongs extends SampleElements<Long> {
public SampleLongs() {
diff --git a/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java
index e02d1aa5a..46611f388 100644
--- a/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/IntArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -49,6 +50,7 @@ public class IntArrayAsListTest extends TestCase {
return Ints.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Integer>> builders =
diff --git a/guava-tests/test/com/google/common/primitives/IntsTest.java b/guava-tests/test/com/google/common/primitives/IntsTest.java
index 72154224c..1a60b7f0e 100644
--- a/guava-tests/test/com/google/common/primitives/IntsTest.java
+++ b/guava-tests/test/com/google/common/primitives/IntsTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
@@ -29,6 +33,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Ints}.
@@ -36,6 +41,7 @@ import junit.framework.TestCase;
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
+@ElementTypesAreNonnullByDefault
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class IntsTest extends TestCase {
private static final int[] EMPTY = {};
@@ -49,13 +55,13 @@ public class IntsTest extends TestCase {
public void testHashCode() {
for (int value : VALUES) {
- assertEquals(((Integer) value).hashCode(), Ints.hashCode(value));
+ assertThat(Ints.hashCode(value)).isEqualTo(((Integer) value).hashCode());
}
}
public void testCheckedCast() {
for (int value : VALUES) {
- assertEquals(value, Ints.checkedCast((long) value));
+ assertThat(Ints.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -65,12 +71,12 @@ public class IntsTest extends TestCase {
public void testSaturatedCast() {
for (int value : VALUES) {
- assertEquals(value, Ints.saturatedCast((long) value));
+ assertThat(Ints.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, Ints.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, Ints.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, Ints.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, Ints.saturatedCast(Long.MIN_VALUE));
+ assertThat(Ints.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(Ints.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(Ints.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(Ints.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -78,9 +84,9 @@ public class IntsTest extends TestCase {
Ints.checkedCast(value);
fail("Cast to int should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -88,73 +94,79 @@ public class IntsTest extends TestCase {
for (int x : VALUES) {
for (int y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Integer.valueOf(x).compareTo(y), Ints.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Ints.compare(x, y))
+ .isEqualTo(Integer.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Ints.contains(EMPTY, (int) 1));
- assertFalse(Ints.contains(ARRAY1, (int) 2));
- assertFalse(Ints.contains(ARRAY234, (int) 1));
- assertTrue(Ints.contains(new int[] {(int) -1}, (int) -1));
- assertTrue(Ints.contains(ARRAY234, (int) 2));
- assertTrue(Ints.contains(ARRAY234, (int) 3));
- assertTrue(Ints.contains(ARRAY234, (int) 4));
+ assertThat(Ints.contains(EMPTY, (int) 1)).isFalse();
+ assertThat(Ints.contains(ARRAY1, (int) 2)).isFalse();
+ assertThat(Ints.contains(ARRAY234, (int) 1)).isFalse();
+ assertThat(Ints.contains(new int[] {(int) -1}, (int) -1)).isTrue();
+ assertThat(Ints.contains(ARRAY234, (int) 2)).isTrue();
+ assertThat(Ints.contains(ARRAY234, (int) 3)).isTrue();
+ assertThat(Ints.contains(ARRAY234, (int) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Ints.indexOf(EMPTY, (int) 1));
- assertEquals(-1, Ints.indexOf(ARRAY1, (int) 2));
- assertEquals(-1, Ints.indexOf(ARRAY234, (int) 1));
- assertEquals(0, Ints.indexOf(new int[] {(int) -1}, (int) -1));
- assertEquals(0, Ints.indexOf(ARRAY234, (int) 2));
- assertEquals(1, Ints.indexOf(ARRAY234, (int) 3));
- assertEquals(2, Ints.indexOf(ARRAY234, (int) 4));
- assertEquals(1, Ints.indexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3));
+ assertThat(Ints.indexOf(EMPTY, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY1, (int) 2)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY234, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.indexOf(new int[] {(int) -1}, (int) -1)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, (int) 2)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, (int) 3)).isEqualTo(1);
+ assertThat(Ints.indexOf(ARRAY234, (int) 4)).isEqualTo(2);
+ assertThat(Ints.indexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3)).isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Ints.indexOf(EMPTY, EMPTY));
- assertEquals(0, Ints.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Ints.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Ints.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Ints.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Ints.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Ints.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Ints.indexOf(ARRAY234, new int[] {(int) 2, (int) 3}));
- assertEquals(1, Ints.indexOf(ARRAY234, new int[] {(int) 3, (int) 4}));
- assertEquals(1, Ints.indexOf(ARRAY234, new int[] {(int) 3}));
- assertEquals(2, Ints.indexOf(ARRAY234, new int[] {(int) 4}));
- assertEquals(
- 1,
- Ints.indexOf(new int[] {(int) 2, (int) 3, (int) 3, (int) 3, (int) 3}, new int[] {(int) 3}));
- assertEquals(
- 2,
- Ints.indexOf(
- new int[] {(int) 2, (int) 3, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3},
- new int[] {(int) 2, (int) 3, (int) 4}));
- assertEquals(
- 1,
- Ints.indexOf(
- new int[] {(int) 2, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3, (int) 4},
- new int[] {(int) 2, (int) 3, (int) 4}));
- assertEquals(
- -1,
- Ints.indexOf(new int[] {(int) 4, (int) 3, (int) 2}, new int[] {(int) 2, (int) 3, (int) 4}));
+ assertThat(Ints.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Ints.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Ints.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 2, (int) 3})).isEqualTo(0);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 3, (int) 4})).isEqualTo(1);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 3})).isEqualTo(1);
+ assertThat(Ints.indexOf(ARRAY234, new int[] {(int) 4})).isEqualTo(2);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 2, (int) 3, (int) 3, (int) 3, (int) 3}, new int[] {(int) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 2, (int) 3, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3},
+ new int[] {(int) 2, (int) 3, (int) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 2, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3, (int) 4},
+ new int[] {(int) 2, (int) 3, (int) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Ints.indexOf(
+ new int[] {(int) 4, (int) 3, (int) 2}, new int[] {(int) 2, (int) 3, (int) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Ints.lastIndexOf(EMPTY, (int) 1));
- assertEquals(-1, Ints.lastIndexOf(ARRAY1, (int) 2));
- assertEquals(-1, Ints.lastIndexOf(ARRAY234, (int) 1));
- assertEquals(0, Ints.lastIndexOf(new int[] {(int) -1}, (int) -1));
- assertEquals(0, Ints.lastIndexOf(ARRAY234, (int) 2));
- assertEquals(1, Ints.lastIndexOf(ARRAY234, (int) 3));
- assertEquals(2, Ints.lastIndexOf(ARRAY234, (int) 4));
- assertEquals(3, Ints.lastIndexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3));
- }
-
+ assertThat(Ints.lastIndexOf(EMPTY, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.lastIndexOf(ARRAY1, (int) 2)).isEqualTo(-1);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 1)).isEqualTo(-1);
+ assertThat(Ints.lastIndexOf(new int[] {(int) -1}, (int) -1)).isEqualTo(0);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 2)).isEqualTo(0);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 3)).isEqualTo(1);
+ assertThat(Ints.lastIndexOf(ARRAY234, (int) 4)).isEqualTo(2);
+ assertThat(Ints.lastIndexOf(new int[] {(int) 2, (int) 3, (int) 2, (int) 3}, (int) 3))
+ .isEqualTo(3);
+ }
+
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -165,11 +177,13 @@ public class IntsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Ints.max(LEAST));
- assertEquals(GREATEST, Ints.max(GREATEST));
- assertEquals((int) 9, Ints.max((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9));
+ assertThat(Ints.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Ints.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Ints.max((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9))
+ .isEqualTo((int) 9);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -180,17 +194,18 @@ public class IntsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Ints.min(LEAST));
- assertEquals(GREATEST, Ints.min(GREATEST));
- assertEquals((int) 0, Ints.min((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9));
+ assertThat(Ints.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Ints.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(Ints.min((int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9))
+ .isEqualTo((int) 0);
}
public void testConstrainToRange() {
- assertEquals((int) 1, Ints.constrainToRange((int) 1, (int) 0, (int) 5));
- assertEquals((int) 1, Ints.constrainToRange((int) 1, (int) 1, (int) 5));
- assertEquals((int) 3, Ints.constrainToRange((int) 1, (int) 3, (int) 5));
- assertEquals((int) -1, Ints.constrainToRange((int) 0, (int) -5, (int) -1));
- assertEquals((int) 2, Ints.constrainToRange((int) 5, (int) 2, (int) 2));
+ assertThat(Ints.constrainToRange((int) 1, (int) 0, (int) 5)).isEqualTo((int) 1);
+ assertThat(Ints.constrainToRange((int) 1, (int) 1, (int) 5)).isEqualTo((int) 1);
+ assertThat(Ints.constrainToRange((int) 1, (int) 3, (int) 5)).isEqualTo((int) 3);
+ assertThat(Ints.constrainToRange((int) 0, (int) -5, (int) -1)).isEqualTo((int) -1);
+ assertThat(Ints.constrainToRange((int) 5, (int) 2, (int) 2)).isEqualTo((int) 2);
try {
Ints.constrainToRange((int) 1, (int) 3, (int) 2);
fail();
@@ -199,32 +214,28 @@ public class IntsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Ints.concat()));
- assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Ints.concat(ARRAY1)));
- assertNotSame(ARRAY1, Ints.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Ints.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(new int[] {(int) 1, (int) 1, (int) 1}, Ints.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new int[] {(int) 1, (int) 2, (int) 3, (int) 4}, Ints.concat(ARRAY1, ARRAY234)));
+ assertThat(Ints.concat()).isEqualTo(EMPTY);
+ assertThat(Ints.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Ints.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Ints.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Ints.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Ints.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Ints.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new int[] {(int) 1, (int) 1, (int) 1});
+ assertThat(Ints.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new int[] {(int) 1, (int) 2, (int) 3, (int) 4});
}
public void testToByteArray() {
- assertTrue(Arrays.equals(new byte[] {0x12, 0x13, 0x14, 0x15}, Ints.toByteArray(0x12131415)));
- assertTrue(
- Arrays.equals(
- new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC},
- Ints.toByteArray(0xFFEEDDCC)));
+ assertThat(Ints.toByteArray(0x12131415)).isEqualTo(new byte[] {0x12, 0x13, 0x14, 0x15});
+ assertThat(Ints.toByteArray(0xFFEEDDCC))
+ .isEqualTo(new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC});
}
public void testFromByteArray() {
- assertEquals(0x12131415, Ints.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x33}));
- assertEquals(
- 0xFFEEDDCC,
- Ints.fromByteArray(new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC}));
+ assertThat(Ints.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x33})).isEqualTo(0x12131415);
+ assertThat(Ints.fromByteArray(new byte[] {(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC}))
+ .isEqualTo(0xFFEEDDCC);
}
public void testFromByteArrayFails() {
@@ -236,8 +247,10 @@ public class IntsTest extends TestCase {
}
public void testFromBytes() {
- assertEquals(0x12131415, Ints.fromBytes((byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15));
- assertEquals(0xFFEEDDCC, Ints.fromBytes((byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC));
+ assertThat(Ints.fromBytes((byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15))
+ .isEqualTo(0x12131415);
+ assertThat(Ints.fromBytes((byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC))
+ .isEqualTo(0xFFEEDDCC);
}
public void testByteArrayRoundTrips() {
@@ -247,19 +260,18 @@ public class IntsTest extends TestCase {
// total overkill, but, it takes 0.1 sec so why not...
for (int i = 0; i < 10000; i++) {
int num = r.nextInt();
- assertEquals(num, Ints.fromByteArray(Ints.toByteArray(num)));
+ assertThat(Ints.fromByteArray(Ints.toByteArray(num))).isEqualTo(num);
r.nextBytes(b);
- assertTrue(Arrays.equals(b, Ints.toByteArray(Ints.fromByteArray(b))));
+ assertThat(Ints.toByteArray(Ints.fromByteArray(b))).isEqualTo(b);
}
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Ints.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(new int[] {(int) 1, (int) 0, (int) 0}, Ints.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Ints.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Ints.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Ints.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Ints.ensureCapacity(ARRAY1, 2, 1)).isEqualTo(new int[] {(int) 1, (int) 0, (int) 0});
}
public void testEnsureCapacity_fail() {
@@ -277,10 +289,10 @@ public class IntsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Ints.join(",", EMPTY));
- assertEquals("1", Ints.join(",", ARRAY1));
- assertEquals("1,2", Ints.join(",", (int) 1, (int) 2));
- assertEquals("123", Ints.join("", (int) 1, (int) 2, (int) 3));
+ assertThat(Ints.join(",", EMPTY)).isEmpty();
+ assertThat(Ints.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(Ints.join(",", (int) 1, (int) 2)).isEqualTo("1,2");
+ assertThat(Ints.join("", (int) 1, (int) 2, (int) 3)).isEqualTo("123");
}
public void testLexicographicalComparator() {
@@ -300,10 +312,11 @@ public class IntsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<int[]> comparator = Ints.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -317,13 +330,13 @@ public class IntsTest extends TestCase {
private static void testReverse(int[] input, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(int[] input, int fromIndex, int toIndex, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -335,6 +348,103 @@ public class IntsTest extends TestCase {
testReverse(new int[] {-1, 1, -2, 2}, 1, 3, new int[] {-1, -2, 1, 2});
}
+ private static void testRotate(int[] input, int distance, int[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Ints.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ int[] input, int distance, int fromIndex, int toIndex, int[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Ints.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new int[] {}, -1, new int[] {});
+ testRotate(new int[] {}, 0, new int[] {});
+ testRotate(new int[] {}, 1, new int[] {});
+
+ testRotate(new int[] {1}, -2, new int[] {1});
+ testRotate(new int[] {1}, -1, new int[] {1});
+ testRotate(new int[] {1}, 0, new int[] {1});
+ testRotate(new int[] {1}, 1, new int[] {1});
+ testRotate(new int[] {1}, 2, new int[] {1});
+
+ testRotate(new int[] {1, 2}, -3, new int[] {2, 1});
+ testRotate(new int[] {1, 2}, -1, new int[] {2, 1});
+ testRotate(new int[] {1, 2}, -2, new int[] {1, 2});
+ testRotate(new int[] {1, 2}, 0, new int[] {1, 2});
+ testRotate(new int[] {1, 2}, 1, new int[] {2, 1});
+ testRotate(new int[] {1, 2}, 2, new int[] {1, 2});
+ testRotate(new int[] {1, 2}, 3, new int[] {2, 1});
+
+ testRotate(new int[] {1, 2, 3}, -5, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, -4, new int[] {2, 3, 1});
+ testRotate(new int[] {1, 2, 3}, -3, new int[] {1, 2, 3});
+ testRotate(new int[] {1, 2, 3}, -2, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, -1, new int[] {2, 3, 1});
+ testRotate(new int[] {1, 2, 3}, 0, new int[] {1, 2, 3});
+ testRotate(new int[] {1, 2, 3}, 1, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, 2, new int[] {2, 3, 1});
+ testRotate(new int[] {1, 2, 3}, 3, new int[] {1, 2, 3});
+ testRotate(new int[] {1, 2, 3}, 4, new int[] {3, 1, 2});
+ testRotate(new int[] {1, 2, 3}, 5, new int[] {2, 3, 1});
+
+ testRotate(new int[] {1, 2, 3, 4}, -9, new int[] {2, 3, 4, 1});
+ testRotate(new int[] {1, 2, 3, 4}, -5, new int[] {2, 3, 4, 1});
+ testRotate(new int[] {1, 2, 3, 4}, -1, new int[] {2, 3, 4, 1});
+ testRotate(new int[] {1, 2, 3, 4}, 0, new int[] {1, 2, 3, 4});
+ testRotate(new int[] {1, 2, 3, 4}, 1, new int[] {4, 1, 2, 3});
+ testRotate(new int[] {1, 2, 3, 4}, 5, new int[] {4, 1, 2, 3});
+ testRotate(new int[] {1, 2, 3, 4}, 9, new int[] {4, 1, 2, 3});
+
+ testRotate(new int[] {1, 2, 3, 4, 5}, -6, new int[] {2, 3, 4, 5, 1});
+ testRotate(new int[] {1, 2, 3, 4, 5}, -4, new int[] {5, 1, 2, 3, 4});
+ testRotate(new int[] {1, 2, 3, 4, 5}, -3, new int[] {4, 5, 1, 2, 3});
+ testRotate(new int[] {1, 2, 3, 4, 5}, -1, new int[] {2, 3, 4, 5, 1});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 0, new int[] {1, 2, 3, 4, 5});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 1, new int[] {5, 1, 2, 3, 4});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 3, new int[] {3, 4, 5, 1, 2});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 4, new int[] {2, 3, 4, 5, 1});
+ testRotate(new int[] {1, 2, 3, 4, 5}, 6, new int[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new int[] {}, 0, 0, 0, new int[] {});
+
+ testRotate(new int[] {1}, 0, 0, 1, new int[] {1});
+ testRotate(new int[] {1}, 1, 0, 1, new int[] {1});
+ testRotate(new int[] {1}, 1, 1, 1, new int[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new int[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new int[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new int[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new int[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new int[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new int[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new int[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new int[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new int[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new int[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new int[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new int[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new int[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new int[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new int[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new int[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new int[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new int[] {}, new int[] {});
testSortDescending(new int[] {1}, new int[] {1});
@@ -346,14 +456,14 @@ public class IntsTest extends TestCase {
private static void testSortDescending(int[] input, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
int[] input, int fromIndex, int toIndex, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Ints.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -365,6 +475,7 @@ public class IntsTest extends TestCase {
testSortDescending(new int[] {-1, -2, 1, 2}, 1, 3, new int[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Ints.stringConverter());
@@ -373,17 +484,17 @@ public class IntsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Integer> none = Arrays.<Integer>asList();
- assertTrue(Arrays.equals(EMPTY, Ints.toArray(none)));
+ assertThat(Ints.toArray(none)).isEqualTo(EMPTY);
List<Integer> one = Arrays.asList((int) 1);
- assertTrue(Arrays.equals(ARRAY1, Ints.toArray(one)));
+ assertThat(Ints.toArray(one)).isEqualTo(ARRAY1);
int[] array = {(int) 0, (int) 1, (int) 0xdeadbeef};
List<Integer> three = Arrays.asList((int) 0, (int) 1, (int) 0xdeadbeef);
- assertTrue(Arrays.equals(array, Ints.toArray(three)));
+ assertThat(Ints.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Ints.toArray(Ints.asList(array))));
+ assertThat(Ints.toArray(Ints.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -393,16 +504,16 @@ public class IntsTest extends TestCase {
Collection<Integer> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
int[] arr = Ints.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Integer> list = Arrays.asList((int) 0, (int) 1, null);
+ List<@Nullable Integer> list = Arrays.asList((int) 0, (int) 1, null);
try {
Ints.toArray(list);
fail();
@@ -420,21 +531,22 @@ public class IntsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Ints.toArray(bytes)));
- assertTrue(Arrays.equals(array, Ints.toArray(shorts)));
- assertTrue(Arrays.equals(array, Ints.toArray(ints)));
- assertTrue(Arrays.equals(array, Ints.toArray(floats)));
- assertTrue(Arrays.equals(array, Ints.toArray(longs)));
- assertTrue(Arrays.equals(array, Ints.toArray(doubles)));
+ assertThat(Ints.toArray(bytes)).isEqualTo(array);
+ assertThat(Ints.toArray(shorts)).isEqualTo(array);
+ assertThat(Ints.toArray(ints)).isEqualTo(array);
+ assertThat(Ints.toArray(floats)).isEqualTo(array);
+ assertThat(Ints.toArray(longs)).isEqualTo(array);
+ assertThat(Ints.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
int[] array = {(int) 0, (int) 1};
List<Integer> list = Ints.asList(array);
list.set(0, (int) 2);
- assertTrue(Arrays.equals(new int[] {(int) 2, (int) 1}, array));
+ assertThat(array).isEqualTo(new int[] {(int) 2, (int) 1});
array[1] = (int) 3;
- assertEquals(Arrays.asList((int) 2, (int) 3), list);
+ assertThat(list).containsExactly((int) 2, (int) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -444,23 +556,24 @@ public class IntsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (int) 4);
- assertTrue(Arrays.equals(new int[] {(int) 0, (int) 1, (int) 2}, newArray));
+ assertThat(newArray).isEqualTo(new int[] {(int) 0, (int) 1, (int) 2});
newArray[1] = (int) 5;
- assertEquals((int) 1, (int) list.get(1));
+ assertThat((int) list.get(1)).isEqualTo((int) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
int[] array = {(int) 0, (int) 1, (int) 2, (int) 3};
List<Integer> list = Ints.asList(array);
- assertTrue(Arrays.equals(new int[] {(int) 1, (int) 2}, Ints.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new int[] {}, Ints.toArray(list.subList(2, 2))));
+ assertThat(Ints.toArray(list.subList(1, 3))).isEqualTo(new int[] {(int) 1, (int) 2});
+ assertThat(Ints.toArray(list.subList(2, 2))).isEqualTo(new int[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Ints.asList(EMPTY));
+ assertThat(Ints.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Ints.class);
@@ -468,14 +581,14 @@ public class IntsTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Integer> converter = Ints.stringConverter();
- assertEquals((Integer) 1, converter.convert("1"));
- assertEquals((Integer) 0, converter.convert("0"));
- assertEquals((Integer) (-1), converter.convert("-1"));
- assertEquals((Integer) 255, converter.convert("0xff"));
- assertEquals((Integer) 255, converter.convert("0xFF"));
- assertEquals((Integer) (-255), converter.convert("-0xFF"));
- assertEquals((Integer) 255, converter.convert("#0000FF"));
- assertEquals((Integer) 438, converter.convert("0666"));
+ assertThat(converter.convert("1")).isEqualTo((Integer) 1);
+ assertThat(converter.convert("0")).isEqualTo((Integer) 0);
+ assertThat(converter.convert("-1")).isEqualTo((Integer) (-1));
+ assertThat(converter.convert("0xff")).isEqualTo((Integer) 255);
+ assertThat(converter.convert("0xFF")).isEqualTo((Integer) 255);
+ assertThat(converter.convert("-0xFF")).isEqualTo((Integer) (-255));
+ assertThat(converter.convert("#0000FF")).isEqualTo((Integer) 255);
+ assertThat(converter.convert("0666")).isEqualTo((Integer) 438);
}
public void testStringConverter_convertError() {
@@ -487,21 +600,22 @@ public class IntsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Ints.stringConverter().convert(null));
- assertNull(Ints.stringConverter().reverse().convert(null));
+ assertThat(Ints.stringConverter().convert(null)).isNull();
+ assertThat(Ints.stringConverter().reverse().convert(null)).isNull();
}
public void testStringConverter_reverse() {
Converter<String, Integer> converter = Ints.stringConverter();
- assertEquals("1", converter.reverse().convert(1));
- assertEquals("0", converter.reverse().convert(0));
- assertEquals("-1", converter.reverse().convert(-1));
- assertEquals("255", converter.reverse().convert(0xff));
- assertEquals("255", converter.reverse().convert(0xFF));
- assertEquals("-255", converter.reverse().convert(-0xFF));
- assertEquals("438", converter.reverse().convert(0666));
+ assertThat(converter.reverse().convert(1)).isEqualTo("1");
+ assertThat(converter.reverse().convert(0)).isEqualTo("0");
+ assertThat(converter.reverse().convert(-1)).isEqualTo("-1");
+ assertThat(converter.reverse().convert(0xff)).isEqualTo("255");
+ assertThat(converter.reverse().convert(0xFF)).isEqualTo("255");
+ assertThat(converter.reverse().convert(-0xFF)).isEqualTo("-255");
+ assertThat(converter.reverse().convert(0666)).isEqualTo("438");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -517,17 +631,25 @@ public class IntsTest extends TestCase {
tryParseAndAssertEquals(-8900, "-8900");
tryParseAndAssertEquals(GREATEST, Integer.toString(GREATEST));
tryParseAndAssertEquals(LEAST, Integer.toString(LEAST));
- assertNull(Ints.tryParse(""));
- assertNull(Ints.tryParse("-"));
- assertNull(Ints.tryParse("+1"));
- assertNull(Ints.tryParse("9999999999999999"));
- assertNull("Max integer + 1", Ints.tryParse(Long.toString(((long) GREATEST) + 1)));
- assertNull("Max integer * 10", Ints.tryParse(Long.toString(((long) GREATEST) * 10)));
- assertNull("Min integer - 1", Ints.tryParse(Long.toString(((long) LEAST) - 1)));
- assertNull("Min integer * 10", Ints.tryParse(Long.toString(((long) LEAST) * 10)));
- assertNull("Max long", Ints.tryParse(Long.toString(Long.MAX_VALUE)));
- assertNull("Min long", Ints.tryParse(Long.toString(Long.MIN_VALUE)));
- assertNull(Ints.tryParse("\u0662\u06f3"));
+ assertThat(Ints.tryParse("")).isNull();
+ assertThat(Ints.tryParse("-")).isNull();
+ assertThat(Ints.tryParse("+1")).isNull();
+ assertThat(Ints.tryParse("9999999999999999")).isNull();
+ assertWithMessage("Max integer + 1")
+ .that(Ints.tryParse(Long.toString(((long) GREATEST) + 1)))
+ .isNull();
+ assertWithMessage("Max integer * 10")
+ .that(Ints.tryParse(Long.toString(((long) GREATEST) * 10)))
+ .isNull();
+ assertWithMessage("Min integer - 1")
+ .that(Ints.tryParse(Long.toString(((long) LEAST) - 1)))
+ .isNull();
+ assertWithMessage("Min integer * 10")
+ .that(Ints.tryParse(Long.toString(((long) LEAST) * 10)))
+ .isNull();
+ assertWithMessage("Max long").that(Ints.tryParse(Long.toString(Long.MAX_VALUE))).isNull();
+ assertWithMessage("Min long").that(Ints.tryParse(Long.toString(Long.MIN_VALUE))).isNull();
+ assertThat(Ints.tryParse("\u0662\u06f3")).isNull();
}
/**
@@ -535,7 +657,7 @@ public class IntsTest extends TestCase {
* expected.
*/
private static void tryParseAndAssertEquals(Integer expected, String value) {
- assertEquals(expected, Ints.tryParse(value));
+ assertThat(Ints.tryParse(value)).isEqualTo(expected);
}
public void testTryParse_radix() {
@@ -545,21 +667,26 @@ public class IntsTest extends TestCase {
radixEncodeParseAndAssertEquals(-8000, radix);
radixEncodeParseAndAssertEquals(GREATEST, radix);
radixEncodeParseAndAssertEquals(LEAST, radix);
- assertNull("Radix: " + radix, Ints.tryParse("9999999999999999", radix));
- assertNull(
- "Radix: " + radix, Ints.tryParse(Long.toString((long) GREATEST + 1, radix), radix));
- assertNull("Radix: " + radix, Ints.tryParse(Long.toString((long) LEAST - 1, radix), radix));
+ assertWithMessage("Radix: " + radix).that(Ints.tryParse("9999999999999999", radix)).isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(Ints.tryParse(Long.toString((long) GREATEST + 1, radix), radix))
+ .isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(Ints.tryParse(Long.toString((long) LEAST - 1, radix), radix))
+ .isNull();
}
- assertNull("Hex string and dec parm", Ints.tryParse("FFFF", 10));
- assertEquals("Mixed hex case", 65535, (int) Ints.tryParse("ffFF", 16));
+ assertWithMessage("Hex string and dec parm").that(Ints.tryParse("FFFF", 10)).isNull();
+ assertWithMessage("Mixed hex case").that((int) Ints.tryParse("ffFF", 16)).isEqualTo(65535);
}
/**
- * Encodes the an integer as a string with given radix, then uses {@link Ints#tryParse(String,
- * int)} to parse the result. Asserts the result is the same as what we started with.
+ * Encodes an integer as a string with given radix, then uses {@link Ints#tryParse(String, int)}
+ * to parse the result. Asserts the result is the same as what we started with.
*/
private static void radixEncodeParseAndAssertEquals(Integer value, int radix) {
- assertEquals("Radix: " + radix, value, Ints.tryParse(Integer.toString(value, radix), radix));
+ assertWithMessage("Radix: " + radix)
+ .that(Ints.tryParse(Integer.toString(value, radix), radix))
+ .isEqualTo(value);
}
public void testTryParse_radixTooBig() {
@@ -579,7 +706,7 @@ public class IntsTest extends TestCase {
}
public void testTryParse_withNullGwt() {
- assertNull(Ints.tryParse("null"));
+ assertThat(Ints.tryParse("null")).isNull();
try {
Ints.tryParse(null);
fail("Expected NPE");
diff --git a/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java
index 1c51e7ea0..4a6325153 100644
--- a/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/LongArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class LongArrayAsListTest extends TestCase {
return Longs.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Long>> builders =
diff --git a/guava-tests/test/com/google/common/primitives/LongsTest.java b/guava-tests/test/com/google/common/primitives/LongsTest.java
index 236d46165..83363c411 100644
--- a/guava-tests/test/com/google/common/primitives/LongsTest.java
+++ b/guava-tests/test/com/google/common/primitives/LongsTest.java
@@ -16,11 +16,14 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static java.lang.Long.MAX_VALUE;
import static java.lang.Long.MIN_VALUE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
@@ -33,12 +36,14 @@ import java.util.Comparator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Longs}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class LongsTest extends TestCase {
@@ -48,10 +53,13 @@ public class LongsTest extends TestCase {
private static final long[] VALUES = {MIN_VALUE, (long) -1, (long) 0, (long) 1, MAX_VALUE};
+ @J2ktIncompatible
@GwtIncompatible // Long.hashCode returns different values in GWT.
public void testHashCode() {
for (long value : VALUES) {
- assertEquals("hashCode for " + value, ((Long) value).hashCode(), Longs.hashCode(value));
+ assertWithMessage("hashCode for " + value)
+ .that(Longs.hashCode(value))
+ .isEqualTo(((Long) value).hashCode());
}
}
@@ -59,74 +67,79 @@ public class LongsTest extends TestCase {
for (long x : VALUES) {
for (long y : VALUES) {
// note: spec requires only that the sign is the same
- assertEquals(x + ", " + y, Long.valueOf(x).compareTo(y), Longs.compare(x, y));
+ assertWithMessage(x + ", " + y)
+ .that(Longs.compare(x, y))
+ .isEqualTo(Long.valueOf(x).compareTo(y));
}
}
}
public void testContains() {
- assertFalse(Longs.contains(EMPTY, (long) 1));
- assertFalse(Longs.contains(ARRAY1, (long) 2));
- assertFalse(Longs.contains(ARRAY234, (long) 1));
- assertTrue(Longs.contains(new long[] {(long) -1}, (long) -1));
- assertTrue(Longs.contains(ARRAY234, (long) 2));
- assertTrue(Longs.contains(ARRAY234, (long) 3));
- assertTrue(Longs.contains(ARRAY234, (long) 4));
+ assertThat(Longs.contains(EMPTY, (long) 1)).isFalse();
+ assertThat(Longs.contains(ARRAY1, (long) 2)).isFalse();
+ assertThat(Longs.contains(ARRAY234, (long) 1)).isFalse();
+ assertThat(Longs.contains(new long[] {(long) -1}, (long) -1)).isTrue();
+ assertThat(Longs.contains(ARRAY234, (long) 2)).isTrue();
+ assertThat(Longs.contains(ARRAY234, (long) 3)).isTrue();
+ assertThat(Longs.contains(ARRAY234, (long) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Longs.indexOf(EMPTY, (long) 1));
- assertEquals(-1, Longs.indexOf(ARRAY1, (long) 2));
- assertEquals(-1, Longs.indexOf(ARRAY234, (long) 1));
- assertEquals(0, Longs.indexOf(new long[] {(long) -1}, (long) -1));
- assertEquals(0, Longs.indexOf(ARRAY234, (long) 2));
- assertEquals(1, Longs.indexOf(ARRAY234, (long) 3));
- assertEquals(2, Longs.indexOf(ARRAY234, (long) 4));
- assertEquals(1, Longs.indexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3));
+ assertThat(Longs.indexOf(EMPTY, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY1, (long) 2)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY234, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.indexOf(new long[] {(long) -1}, (long) -1)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, (long) 2)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, (long) 3)).isEqualTo(1);
+ assertThat(Longs.indexOf(ARRAY234, (long) 4)).isEqualTo(2);
+ assertThat(Longs.indexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Longs.indexOf(EMPTY, EMPTY));
- assertEquals(0, Longs.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Longs.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Longs.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Longs.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Longs.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Longs.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Longs.indexOf(ARRAY234, new long[] {(long) 2, (long) 3}));
- assertEquals(1, Longs.indexOf(ARRAY234, new long[] {(long) 3, (long) 4}));
- assertEquals(1, Longs.indexOf(ARRAY234, new long[] {(long) 3}));
- assertEquals(2, Longs.indexOf(ARRAY234, new long[] {(long) 4}));
- assertEquals(
- 1,
- Longs.indexOf(
- new long[] {(long) 2, (long) 3, (long) 3, (long) 3, (long) 3}, new long[] {(long) 3}));
- assertEquals(
- 2,
- Longs.indexOf(
- new long[] {(long) 2, (long) 3, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3},
- new long[] {(long) 2, (long) 3, (long) 4}));
- assertEquals(
- 1,
- Longs.indexOf(
- new long[] {(long) 2, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3, (long) 4},
- new long[] {(long) 2, (long) 3, (long) 4}));
- assertEquals(
- -1,
- Longs.indexOf(
- new long[] {(long) 4, (long) 3, (long) 2}, new long[] {(long) 2, (long) 3, (long) 4}));
+ assertThat(Longs.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Longs.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Longs.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 2, (long) 3})).isEqualTo(0);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 3, (long) 4})).isEqualTo(1);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 3})).isEqualTo(1);
+ assertThat(Longs.indexOf(ARRAY234, new long[] {(long) 4})).isEqualTo(2);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 2, (long) 3, (long) 3, (long) 3, (long) 3},
+ new long[] {(long) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 2, (long) 3, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3},
+ new long[] {(long) 2, (long) 3, (long) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 2, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3, (long) 4},
+ new long[] {(long) 2, (long) 3, (long) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Longs.indexOf(
+ new long[] {(long) 4, (long) 3, (long) 2},
+ new long[] {(long) 2, (long) 3, (long) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Longs.lastIndexOf(EMPTY, (long) 1));
- assertEquals(-1, Longs.lastIndexOf(ARRAY1, (long) 2));
- assertEquals(-1, Longs.lastIndexOf(ARRAY234, (long) 1));
- assertEquals(0, Longs.lastIndexOf(new long[] {(long) -1}, (long) -1));
- assertEquals(0, Longs.lastIndexOf(ARRAY234, (long) 2));
- assertEquals(1, Longs.lastIndexOf(ARRAY234, (long) 3));
- assertEquals(2, Longs.lastIndexOf(ARRAY234, (long) 4));
- assertEquals(
- 3, Longs.lastIndexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3));
+ assertThat(Longs.lastIndexOf(EMPTY, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.lastIndexOf(ARRAY1, (long) 2)).isEqualTo(-1);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 1)).isEqualTo(-1);
+ assertThat(Longs.lastIndexOf(new long[] {(long) -1}, (long) -1)).isEqualTo(0);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 2)).isEqualTo(0);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 3)).isEqualTo(1);
+ assertThat(Longs.lastIndexOf(ARRAY234, (long) 4)).isEqualTo(2);
+ assertThat(Longs.lastIndexOf(new long[] {(long) 2, (long) 3, (long) 2, (long) 3}, (long) 3))
+ .isEqualTo(3);
}
public void testMax_noArgs() {
@@ -138,10 +151,10 @@ public class LongsTest extends TestCase {
}
public void testMax() {
- assertEquals(MIN_VALUE, Longs.max(MIN_VALUE));
- assertEquals(MAX_VALUE, Longs.max(MAX_VALUE));
- assertEquals(
- (long) 9, Longs.max((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9));
+ assertThat(Longs.max(MIN_VALUE)).isEqualTo(MIN_VALUE);
+ assertThat(Longs.max(MAX_VALUE)).isEqualTo(MAX_VALUE);
+ assertThat(Longs.max((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9))
+ .isEqualTo((long) 9);
}
public void testMin_noArgs() {
@@ -153,18 +166,18 @@ public class LongsTest extends TestCase {
}
public void testMin() {
- assertEquals(MIN_VALUE, Longs.min(MIN_VALUE));
- assertEquals(MAX_VALUE, Longs.min(MAX_VALUE));
- assertEquals(
- (long) 0, Longs.min((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9));
+ assertThat(Longs.min(MIN_VALUE)).isEqualTo(MIN_VALUE);
+ assertThat(Longs.min(MAX_VALUE)).isEqualTo(MAX_VALUE);
+ assertThat(Longs.min((long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9))
+ .isEqualTo((long) 0);
}
public void testConstrainToRange() {
- assertEquals((long) 1, Longs.constrainToRange((long) 1, (long) 0, (long) 5));
- assertEquals((long) 1, Longs.constrainToRange((long) 1, (long) 1, (long) 5));
- assertEquals((long) 3, Longs.constrainToRange((long) 1, (long) 3, (long) 5));
- assertEquals((long) -1, Longs.constrainToRange((long) 0, (long) -5, (long) -1));
- assertEquals((long) 2, Longs.constrainToRange((long) 5, (long) 2, (long) 2));
+ assertThat(Longs.constrainToRange((long) 1, (long) 0, (long) 5)).isEqualTo((long) 1);
+ assertThat(Longs.constrainToRange((long) 1, (long) 1, (long) 5)).isEqualTo((long) 1);
+ assertThat(Longs.constrainToRange((long) 1, (long) 3, (long) 5)).isEqualTo((long) 3);
+ assertThat(Longs.constrainToRange((long) 0, (long) -5, (long) -1)).isEqualTo((long) -1);
+ assertThat(Longs.constrainToRange((long) 5, (long) 2, (long) 2)).isEqualTo((long) 2);
try {
Longs.constrainToRange((long) 1, (long) 3, (long) 2);
fail();
@@ -173,24 +186,54 @@ public class LongsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Longs.concat()));
- assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Longs.concat(ARRAY1)));
- assertNotSame(ARRAY1, Longs.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Longs.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new long[] {(long) 1, (long) 1, (long) 1}, Longs.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new long[] {(long) 1, (long) 2, (long) 3, (long) 4}, Longs.concat(ARRAY1, ARRAY234)));
+ assertThat(Longs.concat()).isEqualTo(EMPTY);
+ assertThat(Longs.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Longs.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Longs.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Longs.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Longs.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Longs.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new long[] {(long) 1, (long) 1, (long) 1});
+ assertThat(Longs.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new long[] {(long) 1, (long) 2, (long) 3, (long) 4});
+ }
+
+ @GwtIncompatible // different overflow behavior; could probably be made to work by using ~~
+ public void testConcat_overflow_negative() {
+ int dim1 = 1 << 16;
+ int dim2 = 1 << 15;
+ assertThat(dim1 * dim2).isLessThan(0);
+ testConcat_overflow(dim1, dim2);
+ }
+
+ @GwtIncompatible // different overflow behavior; could probably be made to work by using ~~
+ public void testConcat_overflow_nonNegative() {
+ int dim1 = 1 << 16;
+ int dim2 = 1 << 16;
+ assertThat(dim1 * dim2).isAtLeast(0);
+ testConcat_overflow(dim1, dim2);
+ }
+
+ private static void testConcat_overflow(int arraysDim1, int arraysDim2) {
+ assertThat((long) arraysDim1 * arraysDim2).isNotEqualTo((long) (arraysDim1 * arraysDim2));
+
+ long[][] arrays = new long[arraysDim1][];
+ // it's shared to avoid using too much memory in tests
+ long[] sharedArray = new long[arraysDim2];
+ Arrays.fill(arrays, sharedArray);
+
+ try {
+ Longs.concat(arrays);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
}
private static void assertByteArrayEquals(byte[] expected, byte[] actual) {
- assertTrue(
- "Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual),
- Arrays.equals(expected, actual));
+ assertWithMessage(
+ "Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual))
+ .that(Arrays.equals(expected, actual))
+ .isTrue();
}
public void testToByteArray() {
@@ -206,16 +249,16 @@ public class LongsTest extends TestCase {
}
public void testFromByteArray() {
- assertEquals(
- 0x1213141516171819L,
- Longs.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33}));
- assertEquals(
- 0xFFEEDDCCBBAA9988L,
- Longs.fromByteArray(
- new byte[] {
- (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
- (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88
- }));
+ assertThat(
+ Longs.fromByteArray(new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33}))
+ .isEqualTo(0x1213141516171819L);
+ assertThat(
+ Longs.fromByteArray(
+ new byte[] {
+ (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
+ (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88
+ }))
+ .isEqualTo(0xFFEEDDCCBBAA9988L);
}
public void testFromByteArrayFails() {
@@ -227,28 +270,28 @@ public class LongsTest extends TestCase {
}
public void testFromBytes() {
- assertEquals(
- 0x1213141516171819L,
- Longs.fromBytes(
- (byte) 0x12,
- (byte) 0x13,
- (byte) 0x14,
- (byte) 0x15,
- (byte) 0x16,
- (byte) 0x17,
- (byte) 0x18,
- (byte) 0x19));
- assertEquals(
- 0xFFEEDDCCBBAA9988L,
- Longs.fromBytes(
- (byte) 0xFF,
- (byte) 0xEE,
- (byte) 0xDD,
- (byte) 0xCC,
- (byte) 0xBB,
- (byte) 0xAA,
- (byte) 0x99,
- (byte) 0x88));
+ assertThat(
+ Longs.fromBytes(
+ (byte) 0x12,
+ (byte) 0x13,
+ (byte) 0x14,
+ (byte) 0x15,
+ (byte) 0x16,
+ (byte) 0x17,
+ (byte) 0x18,
+ (byte) 0x19))
+ .isEqualTo(0x1213141516171819L);
+ assertThat(
+ Longs.fromBytes(
+ (byte) 0xFF,
+ (byte) 0xEE,
+ (byte) 0xDD,
+ (byte) 0xCC,
+ (byte) 0xBB,
+ (byte) 0xAA,
+ (byte) 0x99,
+ (byte) 0x88))
+ .isEqualTo(0xFFEEDDCCBBAA9988L);
}
public void testByteArrayRoundTrips() {
@@ -257,21 +300,20 @@ public class LongsTest extends TestCase {
for (int i = 0; i < 1000; i++) {
long num = r.nextLong();
- assertEquals(num, Longs.fromByteArray(Longs.toByteArray(num)));
+ assertThat(Longs.fromByteArray(Longs.toByteArray(num))).isEqualTo(num);
r.nextBytes(b);
long value = Longs.fromByteArray(b);
- assertTrue("" + value, Arrays.equals(b, Longs.toByteArray(value)));
+ assertWithMessage("" + value).that(Arrays.equals(b, Longs.toByteArray(value))).isTrue();
}
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Longs.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new long[] {(long) 1, (long) 0, (long) 0}, Longs.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Longs.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Longs.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Longs.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Longs.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new long[] {(long) 1, (long) 0, (long) 0});
}
public void testEnsureCapacity_fail() {
@@ -289,10 +331,10 @@ public class LongsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Longs.join(",", EMPTY));
- assertEquals("1", Longs.join(",", ARRAY1));
- assertEquals("1,2", Longs.join(",", (long) 1, (long) 2));
- assertEquals("123", Longs.join("", (long) 1, (long) 2, (long) 3));
+ assertThat(Longs.join(",", EMPTY)).isEmpty();
+ assertThat(Longs.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(Longs.join(",", (long) 1, (long) 2)).isEqualTo("1,2");
+ assertThat(Longs.join("", (long) 1, (long) 2, (long) 3)).isEqualTo("123");
}
public void testLexicographicalComparator() {
@@ -312,10 +354,11 @@ public class LongsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<long[]> comparator = Longs.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -329,13 +372,13 @@ public class LongsTest extends TestCase {
private static void testReverse(long[] input, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(long[] input, int fromIndex, int toIndex, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -347,6 +390,103 @@ public class LongsTest extends TestCase {
testReverse(new long[] {-1, 1, -2, 2}, 1, 3, new long[] {-1, -2, 1, 2});
}
+ private static void testRotate(long[] input, int distance, long[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Longs.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ long[] input, int distance, int fromIndex, int toIndex, long[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Longs.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new long[] {}, -1, new long[] {});
+ testRotate(new long[] {}, 0, new long[] {});
+ testRotate(new long[] {}, 1, new long[] {});
+
+ testRotate(new long[] {1}, -2, new long[] {1});
+ testRotate(new long[] {1}, -1, new long[] {1});
+ testRotate(new long[] {1}, 0, new long[] {1});
+ testRotate(new long[] {1}, 1, new long[] {1});
+ testRotate(new long[] {1}, 2, new long[] {1});
+
+ testRotate(new long[] {1, 2}, -3, new long[] {2, 1});
+ testRotate(new long[] {1, 2}, -1, new long[] {2, 1});
+ testRotate(new long[] {1, 2}, -2, new long[] {1, 2});
+ testRotate(new long[] {1, 2}, 0, new long[] {1, 2});
+ testRotate(new long[] {1, 2}, 1, new long[] {2, 1});
+ testRotate(new long[] {1, 2}, 2, new long[] {1, 2});
+ testRotate(new long[] {1, 2}, 3, new long[] {2, 1});
+
+ testRotate(new long[] {1, 2, 3}, -5, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, -4, new long[] {2, 3, 1});
+ testRotate(new long[] {1, 2, 3}, -3, new long[] {1, 2, 3});
+ testRotate(new long[] {1, 2, 3}, -2, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, -1, new long[] {2, 3, 1});
+ testRotate(new long[] {1, 2, 3}, 0, new long[] {1, 2, 3});
+ testRotate(new long[] {1, 2, 3}, 1, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, 2, new long[] {2, 3, 1});
+ testRotate(new long[] {1, 2, 3}, 3, new long[] {1, 2, 3});
+ testRotate(new long[] {1, 2, 3}, 4, new long[] {3, 1, 2});
+ testRotate(new long[] {1, 2, 3}, 5, new long[] {2, 3, 1});
+
+ testRotate(new long[] {1, 2, 3, 4}, -9, new long[] {2, 3, 4, 1});
+ testRotate(new long[] {1, 2, 3, 4}, -5, new long[] {2, 3, 4, 1});
+ testRotate(new long[] {1, 2, 3, 4}, -1, new long[] {2, 3, 4, 1});
+ testRotate(new long[] {1, 2, 3, 4}, 0, new long[] {1, 2, 3, 4});
+ testRotate(new long[] {1, 2, 3, 4}, 1, new long[] {4, 1, 2, 3});
+ testRotate(new long[] {1, 2, 3, 4}, 5, new long[] {4, 1, 2, 3});
+ testRotate(new long[] {1, 2, 3, 4}, 9, new long[] {4, 1, 2, 3});
+
+ testRotate(new long[] {1, 2, 3, 4, 5}, -6, new long[] {2, 3, 4, 5, 1});
+ testRotate(new long[] {1, 2, 3, 4, 5}, -4, new long[] {5, 1, 2, 3, 4});
+ testRotate(new long[] {1, 2, 3, 4, 5}, -3, new long[] {4, 5, 1, 2, 3});
+ testRotate(new long[] {1, 2, 3, 4, 5}, -1, new long[] {2, 3, 4, 5, 1});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 0, new long[] {1, 2, 3, 4, 5});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 1, new long[] {5, 1, 2, 3, 4});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 3, new long[] {3, 4, 5, 1, 2});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 4, new long[] {2, 3, 4, 5, 1});
+ testRotate(new long[] {1, 2, 3, 4, 5}, 6, new long[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new long[] {}, 0, 0, 0, new long[] {});
+
+ testRotate(new long[] {1}, 0, 0, 1, new long[] {1});
+ testRotate(new long[] {1}, 1, 0, 1, new long[] {1});
+ testRotate(new long[] {1}, 1, 1, 1, new long[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new long[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new long[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new long[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new long[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new long[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new long[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new long[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new long[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new long[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new long[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new long[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new long[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new long[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new long[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new long[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new long[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new long[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new long[] {}, new long[] {});
testSortDescending(new long[] {1}, new long[] {1});
@@ -358,14 +498,14 @@ public class LongsTest extends TestCase {
private static void testSortDescending(long[] input, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
long[] input, int fromIndex, int toIndex, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Longs.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -377,6 +517,7 @@ public class LongsTest extends TestCase {
testSortDescending(new long[] {-1, -2, 1, 2}, 1, 3, new long[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Longs.stringConverter());
@@ -385,17 +526,17 @@ public class LongsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Long> none = Arrays.<Long>asList();
- assertTrue(Arrays.equals(EMPTY, Longs.toArray(none)));
+ assertThat(Longs.toArray(none)).isEqualTo(EMPTY);
List<Long> one = Arrays.asList((long) 1);
- assertTrue(Arrays.equals(ARRAY1, Longs.toArray(one)));
+ assertThat(Longs.toArray(one)).isEqualTo(ARRAY1);
long[] array = {(long) 0, (long) 1, 0x0FF1C1AL};
List<Long> three = Arrays.asList((long) 0, (long) 1, 0x0FF1C1AL);
- assertTrue(Arrays.equals(array, Longs.toArray(three)));
+ assertThat(Longs.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Longs.toArray(Longs.asList(array))));
+ assertThat(Longs.toArray(Longs.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -405,16 +546,16 @@ public class LongsTest extends TestCase {
Collection<Long> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
long[] arr = Longs.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Long> list = Arrays.asList((long) 0, (long) 1, null);
+ List<@Nullable Long> list = Arrays.asList((long) 0, (long) 1, null);
try {
Longs.toArray(list);
fail();
@@ -432,21 +573,22 @@ public class LongsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Longs.toArray(bytes)));
- assertTrue(Arrays.equals(array, Longs.toArray(shorts)));
- assertTrue(Arrays.equals(array, Longs.toArray(ints)));
- assertTrue(Arrays.equals(array, Longs.toArray(floats)));
- assertTrue(Arrays.equals(array, Longs.toArray(longs)));
- assertTrue(Arrays.equals(array, Longs.toArray(doubles)));
+ assertThat(Longs.toArray(bytes)).isEqualTo(array);
+ assertThat(Longs.toArray(shorts)).isEqualTo(array);
+ assertThat(Longs.toArray(ints)).isEqualTo(array);
+ assertThat(Longs.toArray(floats)).isEqualTo(array);
+ assertThat(Longs.toArray(longs)).isEqualTo(array);
+ assertThat(Longs.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
long[] array = {(long) 0, (long) 1};
List<Long> list = Longs.asList(array);
list.set(0, (long) 2);
- assertTrue(Arrays.equals(new long[] {(long) 2, (long) 1}, array));
+ assertThat(array).isEqualTo(new long[] {(long) 2, (long) 1});
array[1] = (long) 3;
- assertEquals(Arrays.asList((long) 2, (long) 3), list);
+ assertThat(list).containsExactly((long) 2, (long) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -456,23 +598,24 @@ public class LongsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (long) 4);
- assertTrue(Arrays.equals(new long[] {(long) 0, (long) 1, (long) 2}, newArray));
+ assertThat(newArray).isEqualTo(new long[] {(long) 0, (long) 1, (long) 2});
newArray[1] = (long) 5;
- assertEquals((long) 1, (long) list.get(1));
+ assertThat((long) list.get(1)).isEqualTo((long) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
long[] array = {(long) 0, (long) 1, (long) 2, (long) 3};
List<Long> list = Longs.asList(array);
- assertTrue(Arrays.equals(new long[] {(long) 1, (long) 2}, Longs.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new long[] {}, Longs.toArray(list.subList(2, 2))));
+ assertThat(Longs.toArray(list.subList(1, 3))).isEqualTo(new long[] {(long) 1, (long) 2});
+ assertThat(Longs.toArray(list.subList(2, 2))).isEqualTo(new long[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Longs.asList(EMPTY));
+ assertThat(Longs.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Longs.class);
@@ -480,14 +623,14 @@ public class LongsTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Long> converter = Longs.stringConverter();
- assertEquals((Long) 1L, converter.convert("1"));
- assertEquals((Long) 0L, converter.convert("0"));
- assertEquals((Long) (-1L), converter.convert("-1"));
- assertEquals((Long) 255L, converter.convert("0xff"));
- assertEquals((Long) 255L, converter.convert("0xFF"));
- assertEquals((Long) (-255L), converter.convert("-0xFF"));
- assertEquals((Long) 255L, converter.convert("#0000FF"));
- assertEquals((Long) 438L, converter.convert("0666"));
+ assertThat(converter.convert("1")).isEqualTo((Long) 1L);
+ assertThat(converter.convert("0")).isEqualTo((Long) 0L);
+ assertThat(converter.convert("-1")).isEqualTo((Long) (-1L));
+ assertThat(converter.convert("0xff")).isEqualTo((Long) 255L);
+ assertThat(converter.convert("0xFF")).isEqualTo((Long) 255L);
+ assertThat(converter.convert("-0xFF")).isEqualTo((Long) (-255L));
+ assertThat(converter.convert("#0000FF")).isEqualTo((Long) 255L);
+ assertThat(converter.convert("0666")).isEqualTo((Long) 438L);
}
public void testStringConverter_convertError() {
@@ -499,21 +642,22 @@ public class LongsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Longs.stringConverter().convert(null));
- assertNull(Longs.stringConverter().reverse().convert(null));
+ assertThat(Longs.stringConverter().convert(null)).isNull();
+ assertThat(Longs.stringConverter().reverse().convert(null)).isNull();
}
public void testStringConverter_reverse() {
Converter<String, Long> converter = Longs.stringConverter();
- assertEquals("1", converter.reverse().convert(1L));
- assertEquals("0", converter.reverse().convert(0L));
- assertEquals("-1", converter.reverse().convert(-1L));
- assertEquals("255", converter.reverse().convert(0xffL));
- assertEquals("255", converter.reverse().convert(0xFFL));
- assertEquals("-255", converter.reverse().convert(-0xFFL));
- assertEquals("438", converter.reverse().convert(0666L));
+ assertThat(converter.reverse().convert(1L)).isEqualTo("1");
+ assertThat(converter.reverse().convert(0L)).isEqualTo("0");
+ assertThat(converter.reverse().convert(-1L)).isEqualTo("-1");
+ assertThat(converter.reverse().convert(0xffL)).isEqualTo("255");
+ assertThat(converter.reverse().convert(0xFFL)).isEqualTo("255");
+ assertThat(converter.reverse().convert(-0xFFL)).isEqualTo("-255");
+ assertThat(converter.reverse().convert(0666L)).isEqualTo("438");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
@@ -529,23 +673,23 @@ public class LongsTest extends TestCase {
tryParseAndAssertEquals(-8900L, "-8900");
tryParseAndAssertEquals(MAX_VALUE, Long.toString(MAX_VALUE));
tryParseAndAssertEquals(MIN_VALUE, Long.toString(MIN_VALUE));
- assertNull(Longs.tryParse(""));
- assertNull(Longs.tryParse("-"));
- assertNull(Longs.tryParse("+1"));
- assertNull(Longs.tryParse("999999999999999999999999"));
- assertNull(
- "Max long + 1",
- Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString()));
- assertNull(
- "Max long * 10",
- Longs.tryParse(BigInteger.valueOf(MAX_VALUE).multiply(BigInteger.TEN).toString()));
- assertNull(
- "Min long - 1",
- Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString()));
- assertNull(
- "Min long * 10",
- Longs.tryParse(BigInteger.valueOf(MIN_VALUE).multiply(BigInteger.TEN).toString()));
- assertNull(Longs.tryParse("\u0662\u06f3"));
+ assertThat(Longs.tryParse("")).isNull();
+ assertThat(Longs.tryParse("-")).isNull();
+ assertThat(Longs.tryParse("+1")).isNull();
+ assertThat(Longs.tryParse("999999999999999999999999")).isNull();
+ assertWithMessage("Max long + 1")
+ .that(Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString()))
+ .isNull();
+ assertWithMessage("Max long * 10")
+ .that(Longs.tryParse(BigInteger.valueOf(MAX_VALUE).multiply(BigInteger.TEN).toString()))
+ .isNull();
+ assertWithMessage("Min long - 1")
+ .that(Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString()))
+ .isNull();
+ assertWithMessage("Min long * 10")
+ .that(Longs.tryParse(BigInteger.valueOf(MIN_VALUE).multiply(BigInteger.TEN).toString()))
+ .isNull();
+ assertThat(Longs.tryParse("\u0662\u06f3")).isNull();
}
/**
@@ -553,7 +697,7 @@ public class LongsTest extends TestCase {
* expected.
*/
private static void tryParseAndAssertEquals(Long expected, String value) {
- assertEquals(expected, Longs.tryParse(value));
+ assertThat(Longs.tryParse(value)).isEqualTo(expected);
}
public void testTryParse_radix() {
@@ -563,16 +707,22 @@ public class LongsTest extends TestCase {
radixEncodeParseAndAssertEquals((long) -8000, radix);
radixEncodeParseAndAssertEquals(MAX_VALUE, radix);
radixEncodeParseAndAssertEquals(MIN_VALUE, radix);
- assertNull("Radix: " + radix, Longs.tryParse("999999999999999999999999", radix));
- assertNull(
- "Radix: " + radix,
- Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString(), radix));
- assertNull(
- "Radix: " + radix,
- Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString(), radix));
+ assertWithMessage("Radix: " + radix)
+ .that(Longs.tryParse("999999999999999999999999", radix))
+ .isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString(), radix))
+ .isNull();
+ assertWithMessage("Radix: " + radix)
+ .that(
+ Longs.tryParse(
+ BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString(), radix))
+ .isNull();
}
- assertNull("Hex string and dec parm", Longs.tryParse("FFFF", 10));
- assertEquals("Mixed hex case", 65535, Longs.tryParse("ffFF", 16).longValue());
+ assertWithMessage("Hex string and dec parm").that(Longs.tryParse("FFFF", 10)).isNull();
+ assertWithMessage("Mixed hex case")
+ .that(Longs.tryParse("ffFF", 16).longValue())
+ .isEqualTo(65535);
}
/**
@@ -580,7 +730,9 @@ public class LongsTest extends TestCase {
* parse the result. Asserts the result is the same as what we started with.
*/
private static void radixEncodeParseAndAssertEquals(Long value, int radix) {
- assertEquals("Radix: " + radix, value, Longs.tryParse(Long.toString(value, radix), radix));
+ assertWithMessage("Radix: " + radix)
+ .that(Longs.tryParse(Long.toString(value, radix), radix))
+ .isEqualTo(value);
}
public void testTryParse_radixTooBig() {
@@ -600,7 +752,7 @@ public class LongsTest extends TestCase {
}
public void testTryParse_withNullGwt() {
- assertNull(Longs.tryParse("null"));
+ assertThat(Longs.tryParse("null")).isNull();
try {
Longs.tryParse(null);
fail("Expected NPE");
diff --git a/guava-tests/test/com/google/common/primitives/PrimitivesTest.java b/guava-tests/test/com/google/common/primitives/PrimitivesTest.java
index 1e0974365..05cdc953a 100644
--- a/guava-tests/test/com/google/common/primitives/PrimitivesTest.java
+++ b/guava-tests/test/com/google/common/primitives/PrimitivesTest.java
@@ -16,7 +16,11 @@
package com.google.common.primitives;
-import com.google.common.collect.ImmutableSet;
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.testing.NullPointerTester;
import java.util.Set;
import junit.framework.TestCase;
@@ -26,28 +30,29 @@ import junit.framework.TestCase;
*
* @author Kevin Bourrillion
*/
+@GwtCompatible(emulated = true)
public class PrimitivesTest extends TestCase {
public void testIsWrapperType() {
- assertTrue(Primitives.isWrapperType(Void.class));
- assertFalse(Primitives.isWrapperType(void.class));
+ assertThat(Primitives.isWrapperType(Void.class)).isTrue();
+ assertThat(Primitives.isWrapperType(void.class)).isFalse();
}
public void testWrap() {
- assertSame(Integer.class, Primitives.wrap(int.class));
- assertSame(Integer.class, Primitives.wrap(Integer.class));
- assertSame(String.class, Primitives.wrap(String.class));
+ assertThat(Primitives.wrap(int.class)).isSameInstanceAs(Integer.class);
+ assertThat(Primitives.wrap(Integer.class)).isSameInstanceAs(Integer.class);
+ assertThat(Primitives.wrap(String.class)).isSameInstanceAs(String.class);
}
public void testUnwrap() {
- assertSame(int.class, Primitives.unwrap(Integer.class));
- assertSame(int.class, Primitives.unwrap(int.class));
- assertSame(String.class, Primitives.unwrap(String.class));
+ assertThat(Primitives.unwrap(Integer.class)).isSameInstanceAs(int.class);
+ assertThat(Primitives.unwrap(int.class)).isSameInstanceAs(int.class);
+ assertThat(Primitives.unwrap(String.class)).isSameInstanceAs(String.class);
}
public void testAllPrimitiveTypes() {
Set<Class<?>> primitives = Primitives.allPrimitiveTypes();
- assertEquals(
- ImmutableSet.<Object>of(
+ assertThat(primitives)
+ .containsExactly(
boolean.class,
byte.class,
char.class,
@@ -56,8 +61,7 @@ public class PrimitivesTest extends TestCase {
int.class,
long.class,
short.class,
- void.class),
- primitives);
+ void.class);
try {
primitives.remove(boolean.class);
@@ -68,8 +72,8 @@ public class PrimitivesTest extends TestCase {
public void testAllWrapperTypes() {
Set<Class<?>> wrappers = Primitives.allWrapperTypes();
- assertEquals(
- ImmutableSet.<Object>of(
+ assertThat(wrappers)
+ .containsExactly(
Boolean.class,
Byte.class,
Character.class,
@@ -78,8 +82,7 @@ public class PrimitivesTest extends TestCase {
Integer.class,
Long.class,
Short.class,
- Void.class),
- wrappers);
+ Void.class);
try {
wrappers.remove(Boolean.class);
@@ -88,6 +91,8 @@ public class PrimitivesTest extends TestCase {
}
}
+ @GwtIncompatible
+ @J2ktIncompatible
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicStaticMethods(Primitives.class);
diff --git a/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java b/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java
index 9a1fada72..a79211a31 100644
--- a/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java
+++ b/guava-tests/test/com/google/common/primitives/ShortArrayAsListTest.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
@@ -48,6 +49,7 @@ public class ShortArrayAsListTest extends TestCase {
return Shorts.asList(temp);
}
+ @J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
List<ListTestSuiteBuilder<Short>> builders =
diff --git a/guava-tests/test/com/google/common/primitives/ShortsTest.java b/guava-tests/test/com/google/common/primitives/ShortsTest.java
index 0816c6973..26eb04779 100644
--- a/guava-tests/test/com/google/common/primitives/ShortsTest.java
+++ b/guava-tests/test/com/google/common/primitives/ShortsTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
@@ -29,12 +33,14 @@ import java.util.Comparator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link Shorts}.
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class ShortsTest extends TestCase {
@@ -49,13 +55,13 @@ public class ShortsTest extends TestCase {
public void testHashCode() {
for (short value : VALUES) {
- assertEquals(((Short) value).hashCode(), Shorts.hashCode(value));
+ assertThat(Shorts.hashCode(value)).isEqualTo(((Short) value).hashCode());
}
}
public void testCheckedCast() {
for (short value : VALUES) {
- assertEquals(value, Shorts.checkedCast((long) value));
+ assertThat(Shorts.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -65,12 +71,12 @@ public class ShortsTest extends TestCase {
public void testSaturatedCast() {
for (short value : VALUES) {
- assertEquals(value, Shorts.saturatedCast((long) value));
+ assertThat(Shorts.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, Shorts.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, Shorts.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, Shorts.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, Shorts.saturatedCast(Long.MIN_VALUE));
+ assertThat(Shorts.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(Shorts.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(Shorts.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(Shorts.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -78,9 +84,9 @@ public class ShortsTest extends TestCase {
Shorts.checkedCast(value);
fail("Cast to short should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -91,90 +97,94 @@ public class ShortsTest extends TestCase {
int expected = Short.valueOf(x).compareTo(y);
int actual = Shorts.compare(x, y);
if (expected == 0) {
- assertEquals(x + ", " + y, expected, actual);
+ assertWithMessage(x + ", " + y).that(actual).isEqualTo(expected);
} else if (expected < 0) {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual < 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual < 0)
+ .isTrue();
} else {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual > 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual > 0)
+ .isTrue();
}
}
}
}
public void testContains() {
- assertFalse(Shorts.contains(EMPTY, (short) 1));
- assertFalse(Shorts.contains(ARRAY1, (short) 2));
- assertFalse(Shorts.contains(ARRAY234, (short) 1));
- assertTrue(Shorts.contains(new short[] {(short) -1}, (short) -1));
- assertTrue(Shorts.contains(ARRAY234, (short) 2));
- assertTrue(Shorts.contains(ARRAY234, (short) 3));
- assertTrue(Shorts.contains(ARRAY234, (short) 4));
+ assertThat(Shorts.contains(EMPTY, (short) 1)).isFalse();
+ assertThat(Shorts.contains(ARRAY1, (short) 2)).isFalse();
+ assertThat(Shorts.contains(ARRAY234, (short) 1)).isFalse();
+ assertThat(Shorts.contains(new short[] {(short) -1}, (short) -1)).isTrue();
+ assertThat(Shorts.contains(ARRAY234, (short) 2)).isTrue();
+ assertThat(Shorts.contains(ARRAY234, (short) 3)).isTrue();
+ assertThat(Shorts.contains(ARRAY234, (short) 4)).isTrue();
}
public void testIndexOf() {
- assertEquals(-1, Shorts.indexOf(EMPTY, (short) 1));
- assertEquals(-1, Shorts.indexOf(ARRAY1, (short) 2));
- assertEquals(-1, Shorts.indexOf(ARRAY234, (short) 1));
- assertEquals(0, Shorts.indexOf(new short[] {(short) -1}, (short) -1));
- assertEquals(0, Shorts.indexOf(ARRAY234, (short) 2));
- assertEquals(1, Shorts.indexOf(ARRAY234, (short) 3));
- assertEquals(2, Shorts.indexOf(ARRAY234, (short) 4));
- assertEquals(
- 1, Shorts.indexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3));
+ assertThat(Shorts.indexOf(EMPTY, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY1, (short) 2)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(new short[] {(short) -1}, (short) -1)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 2)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 3)).isEqualTo(1);
+ assertThat(Shorts.indexOf(ARRAY234, (short) 4)).isEqualTo(2);
+ assertThat(Shorts.indexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3))
+ .isEqualTo(1);
}
public void testIndexOf_arrayTarget() {
- assertEquals(0, Shorts.indexOf(EMPTY, EMPTY));
- assertEquals(0, Shorts.indexOf(ARRAY234, EMPTY));
- assertEquals(-1, Shorts.indexOf(EMPTY, ARRAY234));
- assertEquals(-1, Shorts.indexOf(ARRAY234, ARRAY1));
- assertEquals(-1, Shorts.indexOf(ARRAY1, ARRAY234));
- assertEquals(0, Shorts.indexOf(ARRAY1, ARRAY1));
- assertEquals(0, Shorts.indexOf(ARRAY234, ARRAY234));
- assertEquals(0, Shorts.indexOf(ARRAY234, new short[] {(short) 2, (short) 3}));
- assertEquals(1, Shorts.indexOf(ARRAY234, new short[] {(short) 3, (short) 4}));
- assertEquals(1, Shorts.indexOf(ARRAY234, new short[] {(short) 3}));
- assertEquals(2, Shorts.indexOf(ARRAY234, new short[] {(short) 4}));
- assertEquals(
- 1,
- Shorts.indexOf(
- new short[] {(short) 2, (short) 3, (short) 3, (short) 3, (short) 3},
- new short[] {(short) 3}));
- assertEquals(
- 2,
- Shorts.indexOf(
- new short[] {
- (short) 2, (short) 3, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3
- },
- new short[] {(short) 2, (short) 3, (short) 4}));
- assertEquals(
- 1,
- Shorts.indexOf(
- new short[] {
- (short) 2, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3, (short) 4
- },
- new short[] {(short) 2, (short) 3, (short) 4}));
- assertEquals(
- -1,
- Shorts.indexOf(
- new short[] {(short) 4, (short) 3, (short) 2},
- new short[] {(short) 2, (short) 3, (short) 4}));
+ assertThat(Shorts.indexOf(EMPTY, EMPTY)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, EMPTY)).isEqualTo(0);
+ assertThat(Shorts.indexOf(EMPTY, ARRAY234)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY234, ARRAY1)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY1, ARRAY234)).isEqualTo(-1);
+ assertThat(Shorts.indexOf(ARRAY1, ARRAY1)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, ARRAY234)).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 2, (short) 3})).isEqualTo(0);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 3, (short) 4})).isEqualTo(1);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 3})).isEqualTo(1);
+ assertThat(Shorts.indexOf(ARRAY234, new short[] {(short) 4})).isEqualTo(2);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {(short) 2, (short) 3, (short) 3, (short) 3, (short) 3},
+ new short[] {(short) 3}))
+ .isEqualTo(1);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {
+ (short) 2, (short) 3, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3
+ },
+ new short[] {(short) 2, (short) 3, (short) 4}))
+ .isEqualTo(2);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {
+ (short) 2, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3, (short) 4
+ },
+ new short[] {(short) 2, (short) 3, (short) 4}))
+ .isEqualTo(1);
+ assertThat(
+ Shorts.indexOf(
+ new short[] {(short) 4, (short) 3, (short) 2},
+ new short[] {(short) 2, (short) 3, (short) 4}))
+ .isEqualTo(-1);
}
public void testLastIndexOf() {
- assertEquals(-1, Shorts.lastIndexOf(EMPTY, (short) 1));
- assertEquals(-1, Shorts.lastIndexOf(ARRAY1, (short) 2));
- assertEquals(-1, Shorts.lastIndexOf(ARRAY234, (short) 1));
- assertEquals(0, Shorts.lastIndexOf(new short[] {(short) -1}, (short) -1));
- assertEquals(0, Shorts.lastIndexOf(ARRAY234, (short) 2));
- assertEquals(1, Shorts.lastIndexOf(ARRAY234, (short) 3));
- assertEquals(2, Shorts.lastIndexOf(ARRAY234, (short) 4));
- assertEquals(
- 3, Shorts.lastIndexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3));
- }
-
+ assertThat(Shorts.lastIndexOf(EMPTY, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.lastIndexOf(ARRAY1, (short) 2)).isEqualTo(-1);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 1)).isEqualTo(-1);
+ assertThat(Shorts.lastIndexOf(new short[] {(short) -1}, (short) -1)).isEqualTo(0);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 2)).isEqualTo(0);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 3)).isEqualTo(1);
+ assertThat(Shorts.lastIndexOf(ARRAY234, (short) 4)).isEqualTo(2);
+ assertThat(
+ Shorts.lastIndexOf(new short[] {(short) 2, (short) 3, (short) 2, (short) 3}, (short) 3))
+ .isEqualTo(3);
+ }
+
+ @J2ktIncompatible
@GwtIncompatible
public void testMax_noArgs() {
try {
@@ -185,13 +195,14 @@ public class ShortsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, Shorts.max(LEAST));
- assertEquals(GREATEST, Shorts.max(GREATEST));
- assertEquals(
- (short) 9,
- Shorts.max((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9));
+ assertThat(Shorts.max(LEAST)).isEqualTo(LEAST);
+ assertThat(Shorts.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Shorts.max((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9))
+ .isEqualTo((short) 9);
}
+ @J2ktIncompatible
@GwtIncompatible
public void testMin_noArgs() {
try {
@@ -202,19 +213,19 @@ public class ShortsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, Shorts.min(LEAST));
- assertEquals(GREATEST, Shorts.min(GREATEST));
- assertEquals(
- (short) 0,
- Shorts.min((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9));
+ assertThat(Shorts.min(LEAST)).isEqualTo(LEAST);
+ assertThat(Shorts.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ Shorts.min((short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9))
+ .isEqualTo((short) 0);
}
public void testConstrainToRange() {
- assertEquals((short) 1, Shorts.constrainToRange((short) 1, (short) 0, (short) 5));
- assertEquals((short) 1, Shorts.constrainToRange((short) 1, (short) 1, (short) 5));
- assertEquals((short) 3, Shorts.constrainToRange((short) 1, (short) 3, (short) 5));
- assertEquals((short) -1, Shorts.constrainToRange((short) 0, (short) -5, (short) -1));
- assertEquals((short) 2, Shorts.constrainToRange((short) 5, (short) 2, (short) 2));
+ assertThat(Shorts.constrainToRange((short) 1, (short) 0, (short) 5)).isEqualTo((short) 1);
+ assertThat(Shorts.constrainToRange((short) 1, (short) 1, (short) 5)).isEqualTo((short) 1);
+ assertThat(Shorts.constrainToRange((short) 1, (short) 3, (short) 5)).isEqualTo((short) 3);
+ assertThat(Shorts.constrainToRange((short) 0, (short) -5, (short) -1)).isEqualTo((short) -1);
+ assertThat(Shorts.constrainToRange((short) 5, (short) 2, (short) 2)).isEqualTo((short) 2);
try {
Shorts.constrainToRange((short) 1, (short) 3, (short) 2);
fail();
@@ -223,34 +234,34 @@ public class ShortsTest extends TestCase {
}
public void testConcat() {
- assertTrue(Arrays.equals(EMPTY, Shorts.concat()));
- assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY)));
- assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY, EMPTY, EMPTY)));
- assertTrue(Arrays.equals(ARRAY1, Shorts.concat(ARRAY1)));
- assertNotSame(ARRAY1, Shorts.concat(ARRAY1));
- assertTrue(Arrays.equals(ARRAY1, Shorts.concat(EMPTY, ARRAY1, EMPTY)));
- assertTrue(
- Arrays.equals(
- new short[] {(short) 1, (short) 1, (short) 1}, Shorts.concat(ARRAY1, ARRAY1, ARRAY1)));
- assertTrue(
- Arrays.equals(
- new short[] {(short) 1, (short) 2, (short) 3, (short) 4},
- Shorts.concat(ARRAY1, ARRAY234)));
- }
-
+ assertThat(Shorts.concat()).isEqualTo(EMPTY);
+ assertThat(Shorts.concat(EMPTY)).isEqualTo(EMPTY);
+ assertThat(Shorts.concat(EMPTY, EMPTY, EMPTY)).isEqualTo(EMPTY);
+ assertThat(Shorts.concat(ARRAY1)).isEqualTo(ARRAY1);
+ assertThat(Shorts.concat(ARRAY1)).isNotSameInstanceAs(ARRAY1);
+ assertThat(Shorts.concat(EMPTY, ARRAY1, EMPTY)).isEqualTo(ARRAY1);
+ assertThat(Shorts.concat(ARRAY1, ARRAY1, ARRAY1))
+ .isEqualTo(new short[] {(short) 1, (short) 1, (short) 1});
+ assertThat(Shorts.concat(ARRAY1, ARRAY234))
+ .isEqualTo(new short[] {(short) 1, (short) 2, (short) 3, (short) 4});
+ }
+
+ @J2ktIncompatible
@GwtIncompatible // Shorts.toByteArray
public void testToByteArray() {
- assertTrue(Arrays.equals(new byte[] {0x23, 0x45}, Shorts.toByteArray((short) 0x2345)));
- assertTrue(
- Arrays.equals(new byte[] {(byte) 0xFE, (byte) 0xDC}, Shorts.toByteArray((short) 0xFEDC)));
+ assertThat(Shorts.toByteArray((short) 0x2345)).isEqualTo(new byte[] {0x23, 0x45});
+ assertThat(Shorts.toByteArray((short) 0xFEDC)).isEqualTo(new byte[] {(byte) 0xFE, (byte) 0xDC});
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromByteArray
public void testFromByteArray() {
- assertEquals((short) 0x2345, Shorts.fromByteArray(new byte[] {0x23, 0x45}));
- assertEquals((short) 0xFEDC, Shorts.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC}));
+ assertThat(Shorts.fromByteArray(new byte[] {0x23, 0x45})).isEqualTo((short) 0x2345);
+ assertThat(Shorts.fromByteArray(new byte[] {(byte) 0xFE, (byte) 0xDC}))
+ .isEqualTo((short) 0xFEDC);
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromByteArray
public void testFromByteArrayFails() {
try {
@@ -260,12 +271,14 @@ public class ShortsTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromBytes
public void testFromBytes() {
- assertEquals((short) 0x2345, Shorts.fromBytes((byte) 0x23, (byte) 0x45));
- assertEquals((short) 0xFEDC, Shorts.fromBytes((byte) 0xFE, (byte) 0xDC));
+ assertThat(Shorts.fromBytes((byte) 0x23, (byte) 0x45)).isEqualTo((short) 0x2345);
+ assertThat(Shorts.fromBytes((byte) 0xFE, (byte) 0xDC)).isEqualTo((short) 0xFEDC);
}
+ @J2ktIncompatible
@GwtIncompatible // Shorts.fromByteArray, Shorts.toByteArray
public void testByteArrayRoundTrips() {
Random r = new Random(5);
@@ -274,20 +287,19 @@ public class ShortsTest extends TestCase {
// total overkill, but, it takes 0.1 sec so why not...
for (int i = 0; i < 10000; i++) {
short num = (short) r.nextInt();
- assertEquals(num, Shorts.fromByteArray(Shorts.toByteArray(num)));
+ assertThat(Shorts.fromByteArray(Shorts.toByteArray(num))).isEqualTo(num);
r.nextBytes(b);
- assertTrue(Arrays.equals(b, Shorts.toByteArray(Shorts.fromByteArray(b))));
+ assertThat(Shorts.toByteArray(Shorts.fromByteArray(b))).isEqualTo(b);
}
}
public void testEnsureCapacity() {
- assertSame(EMPTY, Shorts.ensureCapacity(EMPTY, 0, 1));
- assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 0, 1));
- assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 1, 1));
- assertTrue(
- Arrays.equals(
- new short[] {(short) 1, (short) 0, (short) 0}, Shorts.ensureCapacity(ARRAY1, 2, 1)));
+ assertThat(Shorts.ensureCapacity(EMPTY, 0, 1)).isSameInstanceAs(EMPTY);
+ assertThat(Shorts.ensureCapacity(ARRAY1, 0, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Shorts.ensureCapacity(ARRAY1, 1, 1)).isSameInstanceAs(ARRAY1);
+ assertThat(Shorts.ensureCapacity(ARRAY1, 2, 1))
+ .isEqualTo(new short[] {(short) 1, (short) 0, (short) 0});
}
public void testEnsureCapacity_fail() {
@@ -305,12 +317,13 @@ public class ShortsTest extends TestCase {
}
public void testJoin() {
- assertEquals("", Shorts.join(",", EMPTY));
- assertEquals("1", Shorts.join(",", ARRAY1));
- assertEquals("1,2", Shorts.join(",", (short) 1, (short) 2));
- assertEquals("123", Shorts.join("", (short) 1, (short) 2, (short) 3));
+ assertThat(Shorts.join(",", EMPTY)).isEmpty();
+ assertThat(Shorts.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(Shorts.join(",", (short) 1, (short) 2)).isEqualTo("1,2");
+ assertThat(Shorts.join("", (short) 1, (short) 2, (short) 3)).isEqualTo("123");
}
+ @J2ktIncompatible // TODO(b/285297472): Enable
public void testLexicographicalComparator() {
List<short[]> ordered =
Arrays.asList(
@@ -328,10 +341,11 @@ public class ShortsTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<short[]> comparator = Shorts.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testReverse() {
@@ -345,14 +359,14 @@ public class ShortsTest extends TestCase {
private static void testReverse(short[] input, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.reverse(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testReverse(
short[] input, int fromIndex, int toIndex, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.reverse(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testReverseIndexed() {
@@ -364,6 +378,103 @@ public class ShortsTest extends TestCase {
testReverse(new short[] {-1, 1, -2, 2}, 1, 3, new short[] {-1, -2, 1, 2});
}
+ private static void testRotate(short[] input, int distance, short[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Shorts.rotate(input, distance);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ private static void testRotate(
+ short[] input, int distance, int fromIndex, int toIndex, short[] expectedOutput) {
+ input = Arrays.copyOf(input, input.length);
+ Shorts.rotate(input, distance, fromIndex, toIndex);
+ assertThat(input).isEqualTo(expectedOutput);
+ }
+
+ public void testRotate() {
+ testRotate(new short[] {}, -1, new short[] {});
+ testRotate(new short[] {}, 0, new short[] {});
+ testRotate(new short[] {}, 1, new short[] {});
+
+ testRotate(new short[] {1}, -2, new short[] {1});
+ testRotate(new short[] {1}, -1, new short[] {1});
+ testRotate(new short[] {1}, 0, new short[] {1});
+ testRotate(new short[] {1}, 1, new short[] {1});
+ testRotate(new short[] {1}, 2, new short[] {1});
+
+ testRotate(new short[] {1, 2}, -3, new short[] {2, 1});
+ testRotate(new short[] {1, 2}, -1, new short[] {2, 1});
+ testRotate(new short[] {1, 2}, -2, new short[] {1, 2});
+ testRotate(new short[] {1, 2}, 0, new short[] {1, 2});
+ testRotate(new short[] {1, 2}, 1, new short[] {2, 1});
+ testRotate(new short[] {1, 2}, 2, new short[] {1, 2});
+ testRotate(new short[] {1, 2}, 3, new short[] {2, 1});
+
+ testRotate(new short[] {1, 2, 3}, -5, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, -4, new short[] {2, 3, 1});
+ testRotate(new short[] {1, 2, 3}, -3, new short[] {1, 2, 3});
+ testRotate(new short[] {1, 2, 3}, -2, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, -1, new short[] {2, 3, 1});
+ testRotate(new short[] {1, 2, 3}, 0, new short[] {1, 2, 3});
+ testRotate(new short[] {1, 2, 3}, 1, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, 2, new short[] {2, 3, 1});
+ testRotate(new short[] {1, 2, 3}, 3, new short[] {1, 2, 3});
+ testRotate(new short[] {1, 2, 3}, 4, new short[] {3, 1, 2});
+ testRotate(new short[] {1, 2, 3}, 5, new short[] {2, 3, 1});
+
+ testRotate(new short[] {1, 2, 3, 4}, -9, new short[] {2, 3, 4, 1});
+ testRotate(new short[] {1, 2, 3, 4}, -5, new short[] {2, 3, 4, 1});
+ testRotate(new short[] {1, 2, 3, 4}, -1, new short[] {2, 3, 4, 1});
+ testRotate(new short[] {1, 2, 3, 4}, 0, new short[] {1, 2, 3, 4});
+ testRotate(new short[] {1, 2, 3, 4}, 1, new short[] {4, 1, 2, 3});
+ testRotate(new short[] {1, 2, 3, 4}, 5, new short[] {4, 1, 2, 3});
+ testRotate(new short[] {1, 2, 3, 4}, 9, new short[] {4, 1, 2, 3});
+
+ testRotate(new short[] {1, 2, 3, 4, 5}, -6, new short[] {2, 3, 4, 5, 1});
+ testRotate(new short[] {1, 2, 3, 4, 5}, -4, new short[] {5, 1, 2, 3, 4});
+ testRotate(new short[] {1, 2, 3, 4, 5}, -3, new short[] {4, 5, 1, 2, 3});
+ testRotate(new short[] {1, 2, 3, 4, 5}, -1, new short[] {2, 3, 4, 5, 1});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 0, new short[] {1, 2, 3, 4, 5});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 1, new short[] {5, 1, 2, 3, 4});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 3, new short[] {3, 4, 5, 1, 2});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 4, new short[] {2, 3, 4, 5, 1});
+ testRotate(new short[] {1, 2, 3, 4, 5}, 6, new short[] {5, 1, 2, 3, 4});
+ }
+
+ public void testRotateIndexed() {
+ testRotate(new short[] {}, 0, 0, 0, new short[] {});
+
+ testRotate(new short[] {1}, 0, 0, 1, new short[] {1});
+ testRotate(new short[] {1}, 1, 0, 1, new short[] {1});
+ testRotate(new short[] {1}, 1, 1, 1, new short[] {1});
+
+ // Rotate the central 5 elements, leaving the ends as-is
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -6, 1, 6, new short[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -1, 1, 6, new short[] {0, 2, 3, 4, 5, 1, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 0, 1, 6, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 5, 1, 6, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 14, 1, 6, new short[] {0, 2, 3, 4, 5, 1, 6});
+
+ // Rotate the first three elements
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -2, 0, 3, new short[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -1, 0, 3, new short[] {1, 2, 0, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 0, 0, 3, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 1, 0, 3, new short[] {2, 0, 1, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 2, 0, 3, new short[] {1, 2, 0, 3, 4, 5, 6});
+
+ // Rotate the last four elements
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -6, 3, 7, new short[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -5, 3, 7, new short[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -4, 3, 7, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -3, 3, 7, new short[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -2, 3, 7, new short[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, -1, 3, 7, new short[] {0, 1, 2, 4, 5, 6, 3});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 0, 3, 7, new short[] {0, 1, 2, 3, 4, 5, 6});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 1, 3, 7, new short[] {0, 1, 2, 6, 3, 4, 5});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 2, 3, 7, new short[] {0, 1, 2, 5, 6, 3, 4});
+ testRotate(new short[] {0, 1, 2, 3, 4, 5, 6}, 3, 3, 7, new short[] {0, 1, 2, 4, 5, 6, 3});
+ }
+
public void testSortDescending() {
testSortDescending(new short[] {}, new short[] {});
testSortDescending(new short[] {1}, new short[] {1});
@@ -375,14 +486,14 @@ public class ShortsTest extends TestCase {
private static void testSortDescending(short[] input, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
short[] input, int fromIndex, int toIndex, short[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
Shorts.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -394,6 +505,7 @@ public class ShortsTest extends TestCase {
testSortDescending(new short[] {-1, -2, 1, 2}, 1, 3, new short[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testStringConverterSerialization() {
SerializableTester.reserializeAndAssert(Shorts.stringConverter());
@@ -402,17 +514,17 @@ public class ShortsTest extends TestCase {
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Short> none = Arrays.<Short>asList();
- assertTrue(Arrays.equals(EMPTY, Shorts.toArray(none)));
+ assertThat(Shorts.toArray(none)).isEqualTo(EMPTY);
List<Short> one = Arrays.asList((short) 1);
- assertTrue(Arrays.equals(ARRAY1, Shorts.toArray(one)));
+ assertThat(Shorts.toArray(one)).isEqualTo(ARRAY1);
short[] array = {(short) 0, (short) 1, (short) 3};
List<Short> three = Arrays.asList((short) 0, (short) 1, (short) 3);
- assertTrue(Arrays.equals(array, Shorts.toArray(three)));
+ assertThat(Shorts.toArray(three)).isEqualTo(array);
- assertTrue(Arrays.equals(array, Shorts.toArray(Shorts.asList(array))));
+ assertThat(Shorts.toArray(Shorts.asList(array))).isEqualTo(array);
}
public void testToArray_threadSafe() {
@@ -422,16 +534,16 @@ public class ShortsTest extends TestCase {
Collection<Short> misleadingSize = Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
short[] arr = Shorts.toArray(misleadingSize);
- assertEquals(i, arr.length);
+ assertThat(arr).hasLength(i);
for (int j = 0; j < i; j++) {
- assertEquals(VALUES[j], arr[j]);
+ assertThat(arr[j]).isEqualTo(VALUES[j]);
}
}
}
}
public void testToArray_withNull() {
- List<Short> list = Arrays.asList((short) 0, (short) 1, null);
+ List<@Nullable Short> list = Arrays.asList((short) 0, (short) 1, null);
try {
Shorts.toArray(list);
fail();
@@ -449,21 +561,22 @@ public class ShortsTest extends TestCase {
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
- assertTrue(Arrays.equals(array, Shorts.toArray(bytes)));
- assertTrue(Arrays.equals(array, Shorts.toArray(shorts)));
- assertTrue(Arrays.equals(array, Shorts.toArray(ints)));
- assertTrue(Arrays.equals(array, Shorts.toArray(floats)));
- assertTrue(Arrays.equals(array, Shorts.toArray(longs)));
- assertTrue(Arrays.equals(array, Shorts.toArray(doubles)));
+ assertThat(Shorts.toArray(bytes)).isEqualTo(array);
+ assertThat(Shorts.toArray(shorts)).isEqualTo(array);
+ assertThat(Shorts.toArray(ints)).isEqualTo(array);
+ assertThat(Shorts.toArray(floats)).isEqualTo(array);
+ assertThat(Shorts.toArray(longs)).isEqualTo(array);
+ assertThat(Shorts.toArray(doubles)).isEqualTo(array);
}
+ @J2ktIncompatible // b/285319375
public void testAsList_isAView() {
short[] array = {(short) 0, (short) 1};
List<Short> list = Shorts.asList(array);
list.set(0, (short) 2);
- assertTrue(Arrays.equals(new short[] {(short) 2, (short) 1}, array));
+ assertThat(array).isEqualTo(new short[] {(short) 2, (short) 1});
array[1] = (short) 3;
- assertEquals(Arrays.asList((short) 2, (short) 3), list);
+ assertThat(list).containsExactly((short) 2, (short) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
@@ -473,24 +586,24 @@ public class ShortsTest extends TestCase {
// Make sure it returned a copy
list.set(0, (short) 4);
- assertTrue(Arrays.equals(new short[] {(short) 0, (short) 1, (short) 2}, newArray));
+ assertThat(newArray).isEqualTo(new short[] {(short) 0, (short) 1, (short) 2});
newArray[1] = (short) 5;
- assertEquals((short) 1, (short) list.get(1));
+ assertThat((short) list.get(1)).isEqualTo((short) 1);
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
short[] array = {(short) 0, (short) 1, (short) 2, (short) 3};
List<Short> list = Shorts.asList(array);
- assertTrue(
- Arrays.equals(new short[] {(short) 1, (short) 2}, Shorts.toArray(list.subList(1, 3))));
- assertTrue(Arrays.equals(new short[] {}, Shorts.toArray(list.subList(2, 2))));
+ assertThat(Shorts.toArray(list.subList(1, 3))).isEqualTo(new short[] {(short) 1, (short) 2});
+ assertThat(Shorts.toArray(list.subList(2, 2))).isEqualTo(new short[] {});
}
public void testAsListEmpty() {
- assertSame(Collections.emptyList(), Shorts.asList(EMPTY));
+ assertThat(Shorts.asList(EMPTY)).isSameInstanceAs(Collections.emptyList());
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(Shorts.class);
@@ -498,14 +611,14 @@ public class ShortsTest extends TestCase {
public void testStringConverter_convert() {
Converter<String, Short> converter = Shorts.stringConverter();
- assertEquals((Short) (short) 1, converter.convert("1"));
- assertEquals((Short) (short) 0, converter.convert("0"));
- assertEquals((Short) (short) (-1), converter.convert("-1"));
- assertEquals((Short) (short) 255, converter.convert("0xff"));
- assertEquals((Short) (short) 255, converter.convert("0xFF"));
- assertEquals((Short) (short) (-255), converter.convert("-0xFF"));
- assertEquals((Short) (short) 255, converter.convert("#0000FF"));
- assertEquals((Short) (short) 438, converter.convert("0666"));
+ assertThat(converter.convert("1")).isEqualTo((Short) (short) 1);
+ assertThat(converter.convert("0")).isEqualTo((Short) (short) 0);
+ assertThat(converter.convert("-1")).isEqualTo((Short) (short) (-1));
+ assertThat(converter.convert("0xff")).isEqualTo((Short) (short) 255);
+ assertThat(converter.convert("0xFF")).isEqualTo((Short) (short) 255);
+ assertThat(converter.convert("-0xFF")).isEqualTo((Short) (short) (-255));
+ assertThat(converter.convert("#0000FF")).isEqualTo((Short) (short) 255);
+ assertThat(converter.convert("0666")).isEqualTo((Short) (short) 438);
}
public void testStringConverter_convertError() {
@@ -517,21 +630,22 @@ public class ShortsTest extends TestCase {
}
public void testStringConverter_nullConversions() {
- assertNull(Shorts.stringConverter().convert(null));
- assertNull(Shorts.stringConverter().reverse().convert(null));
+ assertThat(Shorts.stringConverter().convert(null)).isNull();
+ assertThat(Shorts.stringConverter().reverse().convert(null)).isNull();
}
public void testStringConverter_reverse() {
Converter<String, Short> converter = Shorts.stringConverter();
- assertEquals("1", converter.reverse().convert((short) 1));
- assertEquals("0", converter.reverse().convert((short) 0));
- assertEquals("-1", converter.reverse().convert((short) -1));
- assertEquals("255", converter.reverse().convert((short) 0xff));
- assertEquals("255", converter.reverse().convert((short) 0xFF));
- assertEquals("-255", converter.reverse().convert((short) -0xFF));
- assertEquals("438", converter.reverse().convert((short) 0666));
+ assertThat(converter.reverse().convert((short) 1)).isEqualTo("1");
+ assertThat(converter.reverse().convert((short) 0)).isEqualTo("0");
+ assertThat(converter.reverse().convert((short) -1)).isEqualTo("-1");
+ assertThat(converter.reverse().convert((short) 0xff)).isEqualTo("255");
+ assertThat(converter.reverse().convert((short) 0xFF)).isEqualTo("255");
+ assertThat(converter.reverse().convert((short) -0xFF)).isEqualTo("-255");
+ assertThat(converter.reverse().convert((short) 0666)).isEqualTo("438");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testStringConverter_nullPointerTester() throws Exception {
NullPointerTester tester = new NullPointerTester();
diff --git a/guava-tests/test/com/google/common/primitives/SignedBytesTest.java b/guava-tests/test/com/google/common/primitives/SignedBytesTest.java
index 86c2ce612..a141d72bb 100644
--- a/guava-tests/test/com/google/common/primitives/SignedBytesTest.java
+++ b/guava-tests/test/com/google/common/primitives/SignedBytesTest.java
@@ -16,8 +16,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -31,6 +35,7 @@ import junit.framework.TestCase;
*
* @author Kevin Bourrillion
*/
+@ElementTypesAreNonnullByDefault
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class SignedBytesTest extends TestCase {
@@ -44,7 +49,7 @@ public class SignedBytesTest extends TestCase {
public void testCheckedCast() {
for (byte value : VALUES) {
- assertEquals(value, SignedBytes.checkedCast((long) value));
+ assertThat(SignedBytes.checkedCast((long) value)).isEqualTo(value);
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
@@ -54,12 +59,12 @@ public class SignedBytesTest extends TestCase {
public void testSaturatedCast() {
for (byte value : VALUES) {
- assertEquals(value, SignedBytes.saturatedCast((long) value));
+ assertThat(SignedBytes.saturatedCast((long) value)).isEqualTo(value);
}
- assertEquals(GREATEST, SignedBytes.saturatedCast(GREATEST + 1L));
- assertEquals(LEAST, SignedBytes.saturatedCast(LEAST - 1L));
- assertEquals(GREATEST, SignedBytes.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, SignedBytes.saturatedCast(Long.MIN_VALUE));
+ assertThat(SignedBytes.saturatedCast(GREATEST + 1L)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.saturatedCast(LEAST - 1L)).isEqualTo(LEAST);
+ assertThat(SignedBytes.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -67,9 +72,9 @@ public class SignedBytesTest extends TestCase {
SignedBytes.checkedCast(value);
fail("Cast to byte should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -80,13 +85,15 @@ public class SignedBytesTest extends TestCase {
int expected = Byte.valueOf(x).compareTo(y);
int actual = SignedBytes.compare(x, y);
if (expected == 0) {
- assertEquals(x + ", " + y, expected, actual);
+ assertWithMessage(x + ", " + y).that(actual).isEqualTo(expected);
} else if (expected < 0) {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual < 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual < 0)
+ .isTrue();
} else {
- assertTrue(
- x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual > 0);
+ assertWithMessage(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")")
+ .that(actual > 0)
+ .isTrue();
}
}
}
@@ -101,10 +108,10 @@ public class SignedBytesTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, SignedBytes.max(LEAST));
- assertEquals(GREATEST, SignedBytes.max(GREATEST));
- assertEquals(
- (byte) 127, SignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
+ assertThat(SignedBytes.max(LEAST)).isEqualTo(LEAST);
+ assertThat(SignedBytes.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) 127);
}
public void testMin_noArgs() {
@@ -116,20 +123,21 @@ public class SignedBytesTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, SignedBytes.min(LEAST));
- assertEquals(GREATEST, SignedBytes.min(GREATEST));
- assertEquals(
- (byte) -128, SignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
+ assertThat(SignedBytes.min(LEAST)).isEqualTo(LEAST);
+ assertThat(SignedBytes.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(SignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) -128);
}
public void testJoin() {
- assertEquals("", SignedBytes.join(",", EMPTY));
- assertEquals("1", SignedBytes.join(",", ARRAY1));
- assertEquals("1,2", SignedBytes.join(",", (byte) 1, (byte) 2));
- assertEquals("123", SignedBytes.join("", (byte) 1, (byte) 2, (byte) 3));
- assertEquals("-128,-1", SignedBytes.join(",", (byte) -128, (byte) -1));
+ assertThat(SignedBytes.join(",", EMPTY)).isEmpty();
+ assertThat(SignedBytes.join(",", ARRAY1)).isEqualTo("1");
+ assertThat(SignedBytes.join(",", (byte) 1, (byte) 2)).isEqualTo("1,2");
+ assertThat(SignedBytes.join("", (byte) 1, (byte) 2, (byte) 3)).isEqualTo("123");
+ assertThat(SignedBytes.join(",", (byte) -128, (byte) -1)).isEqualTo("-128,-1");
}
+ @J2ktIncompatible // b/285319375
public void testLexicographicalComparator() {
List<byte[]> ordered =
Arrays.asList(
@@ -147,10 +155,11 @@ public class SignedBytesTest extends TestCase {
Helpers.testComparator(comparator, ordered);
}
+ @J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testLexicographicalComparatorSerializable() {
Comparator<byte[]> comparator = SignedBytes.lexicographicalComparator();
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
}
public void testSortDescending() {
@@ -164,14 +173,14 @@ public class SignedBytesTest extends TestCase {
private static void testSortDescending(byte[] input, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
SignedBytes.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
byte[] input, int fromIndex, int toIndex, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
SignedBytes.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -183,6 +192,7 @@ public class SignedBytesTest extends TestCase {
testSortDescending(new byte[] {-1, -2, 1, 2}, 1, 3, new byte[] {-1, 1, -2, 2});
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(SignedBytes.class);
diff --git a/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java b/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java
index 352c8f439..840ae97c3 100644
--- a/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java
+++ b/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java
@@ -16,6 +16,9 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;
@@ -39,17 +42,17 @@ public class UnsignedBytesTest extends TestCase {
private static final byte[] VALUES = {LEAST, 127, (byte) 128, (byte) 129, GREATEST};
public void testToInt() {
- assertEquals(0, UnsignedBytes.toInt((byte) 0));
- assertEquals(1, UnsignedBytes.toInt((byte) 1));
- assertEquals(127, UnsignedBytes.toInt((byte) 127));
- assertEquals(128, UnsignedBytes.toInt((byte) -128));
- assertEquals(129, UnsignedBytes.toInt((byte) -127));
- assertEquals(255, UnsignedBytes.toInt((byte) -1));
+ assertThat(UnsignedBytes.toInt((byte) 0)).isEqualTo(0);
+ assertThat(UnsignedBytes.toInt((byte) 1)).isEqualTo(1);
+ assertThat(UnsignedBytes.toInt((byte) 127)).isEqualTo(127);
+ assertThat(UnsignedBytes.toInt((byte) -128)).isEqualTo(128);
+ assertThat(UnsignedBytes.toInt((byte) -127)).isEqualTo(129);
+ assertThat(UnsignedBytes.toInt((byte) -1)).isEqualTo(255);
}
public void testCheckedCast() {
for (byte value : VALUES) {
- assertEquals(value, UnsignedBytes.checkedCast(UnsignedBytes.toInt(value)));
+ assertThat(UnsignedBytes.checkedCast(UnsignedBytes.toInt(value))).isEqualTo(value);
}
assertCastFails(256L);
assertCastFails(-1L);
@@ -59,12 +62,12 @@ public class UnsignedBytesTest extends TestCase {
public void testSaturatedCast() {
for (byte value : VALUES) {
- assertEquals(value, UnsignedBytes.saturatedCast(UnsignedBytes.toInt(value)));
+ assertThat(UnsignedBytes.saturatedCast(UnsignedBytes.toInt(value))).isEqualTo(value);
}
- assertEquals(GREATEST, UnsignedBytes.saturatedCast(256L));
- assertEquals(LEAST, UnsignedBytes.saturatedCast(-1L));
- assertEquals(GREATEST, UnsignedBytes.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, UnsignedBytes.saturatedCast(Long.MIN_VALUE));
+ assertThat(UnsignedBytes.saturatedCast(256L)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.saturatedCast(-1L)).isEqualTo(LEAST);
+ assertThat(UnsignedBytes.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
private static void assertCastFails(long value) {
@@ -72,9 +75,9 @@ public class UnsignedBytesTest extends TestCase {
UnsignedBytes.checkedCast(value);
fail("Cast to byte should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertTrue(
- value + " not found in exception text: " + ex.getMessage(),
- ex.getMessage().contains(String.valueOf(value)));
+ assertWithMessage(value + " not found in exception text: " + ex.getMessage())
+ .that(ex.getMessage().contains(String.valueOf(value)))
+ .isTrue();
}
}
@@ -86,10 +89,9 @@ public class UnsignedBytesTest extends TestCase {
byte x = VALUES[i];
byte y = VALUES[j];
// note: spec requires only that the sign is the same
- assertEquals(
- x + ", " + y,
- Math.signum(UnsignedBytes.compare(x, y)),
- Math.signum(Ints.compare(i, j)));
+ assertWithMessage(x + ", " + y)
+ .that(Math.signum(Ints.compare(i, j)))
+ .isEqualTo(Math.signum(UnsignedBytes.compare(x, y)));
}
}
}
@@ -103,10 +105,10 @@ public class UnsignedBytesTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, UnsignedBytes.max(LEAST));
- assertEquals(GREATEST, UnsignedBytes.max(GREATEST));
- assertEquals(
- (byte) 255, UnsignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
+ assertThat(UnsignedBytes.max(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedBytes.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.max((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) 255);
}
public void testMin_noArgs() {
@@ -118,12 +120,12 @@ public class UnsignedBytesTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, UnsignedBytes.min(LEAST));
- assertEquals(GREATEST, UnsignedBytes.min(GREATEST));
- assertEquals(
- (byte) 0, UnsignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
- assertEquals(
- (byte) 0, UnsignedBytes.min((byte) -1, (byte) 127, (byte) 1, (byte) -128, (byte) 0));
+ assertThat(UnsignedBytes.min(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedBytes.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(UnsignedBytes.min((byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1))
+ .isEqualTo((byte) 0);
+ assertThat(UnsignedBytes.min((byte) -1, (byte) 127, (byte) 1, (byte) -128, (byte) 0))
+ .isEqualTo((byte) 0);
}
private static void assertParseFails(String value) {
@@ -145,7 +147,7 @@ public class UnsignedBytesTest extends TestCase {
public void testParseUnsignedByte() {
// We can easily afford to test this exhaustively.
for (int i = 0; i <= 0xff; i++) {
- assertEquals((byte) i, UnsignedBytes.parseUnsignedByte(Integer.toString(i)));
+ assertThat(UnsignedBytes.parseUnsignedByte(Integer.toString(i))).isEqualTo((byte) i);
}
assertParseFails("1000");
assertParseFails("-1");
@@ -154,15 +156,16 @@ public class UnsignedBytesTest extends TestCase {
}
public void testMaxValue() {
- assertTrue(
- UnsignedBytes.compare(UnsignedBytes.MAX_VALUE, (byte) (UnsignedBytes.MAX_VALUE + 1)) > 0);
+ assertThat(UnsignedBytes.compare(UnsignedBytes.MAX_VALUE, (byte) (UnsignedBytes.MAX_VALUE + 1)))
+ .isGreaterThan(0);
}
public void testParseUnsignedByteWithRadix() throws NumberFormatException {
// We can easily afford to test this exhaustively.
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (int i = 0; i <= 0xff; i++) {
- assertEquals((byte) i, UnsignedBytes.parseUnsignedByte(Integer.toString(i, radix), radix));
+ assertThat(UnsignedBytes.parseUnsignedByte(Integer.toString(i, radix), radix))
+ .isEqualTo((byte) i);
}
assertParseFails(Integer.toString(1000, radix), radix);
assertParseFails(Integer.toString(-1, radix), radix);
@@ -197,7 +200,7 @@ public class UnsignedBytesTest extends TestCase {
public void testToString() {
// We can easily afford to test this exhaustively.
for (int i = 0; i <= 0xff; i++) {
- assertEquals(Integer.toString(i), UnsignedBytes.toString((byte) i));
+ assertThat(UnsignedBytes.toString((byte) i)).isEqualTo(Integer.toString(i));
}
}
@@ -205,17 +208,17 @@ public class UnsignedBytesTest extends TestCase {
// We can easily afford to test this exhaustively.
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (int i = 0; i <= 0xff; i++) {
- assertEquals(Integer.toString(i, radix), UnsignedBytes.toString((byte) i, radix));
+ assertThat(UnsignedBytes.toString((byte) i, radix)).isEqualTo(Integer.toString(i, radix));
}
}
}
public void testJoin() {
- assertEquals("", UnsignedBytes.join(",", new byte[] {}));
- assertEquals("1", UnsignedBytes.join(",", new byte[] {(byte) 1}));
- assertEquals("1,2", UnsignedBytes.join(",", (byte) 1, (byte) 2));
- assertEquals("123", UnsignedBytes.join("", (byte) 1, (byte) 2, (byte) 3));
- assertEquals("128,255", UnsignedBytes.join(",", (byte) 128, (byte) -1));
+ assertThat(UnsignedBytes.join(",", new byte[] {})).isEmpty();
+ assertThat(UnsignedBytes.join(",", new byte[] {(byte) 1})).isEqualTo("1");
+ assertThat(UnsignedBytes.join(",", (byte) 1, (byte) 2)).isEqualTo("1,2");
+ assertThat(UnsignedBytes.join("", (byte) 1, (byte) 2, (byte) 3)).isEqualTo("123");
+ assertThat(UnsignedBytes.join(",", (byte) 128, (byte) -1)).isEqualTo("128,255");
}
private static String unsafeComparatorClassName() {
@@ -251,12 +254,14 @@ public class UnsignedBytesTest extends TestCase {
public void testLexicographicalComparatorChoice() throws Exception {
Comparator<byte[]> defaultComparator = UnsignedBytes.lexicographicalComparator();
- assertNotNull(defaultComparator);
- assertSame(defaultComparator, UnsignedBytes.lexicographicalComparator());
+ assertThat(defaultComparator).isNotNull();
+ assertThat(UnsignedBytes.lexicographicalComparator()).isSameInstanceAs(defaultComparator);
if (unsafeComparatorAvailable()) {
- assertSame(defaultComparator.getClass(), Class.forName(unsafeComparatorClassName()));
+ assertThat(Class.forName(unsafeComparatorClassName()))
+ .isSameInstanceAs(defaultComparator.getClass());
} else {
- assertSame(defaultComparator, UnsignedBytes.lexicographicalComparatorJavaImpl());
+ assertThat(UnsignedBytes.lexicographicalComparatorJavaImpl())
+ .isSameInstanceAs(defaultComparator);
}
}
@@ -276,12 +281,12 @@ public class UnsignedBytesTest extends TestCase {
// The Unsafe implementation if it's available. Otherwise, the Java implementation.
Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
- assertSame(comparator, SerializableTester.reserialize(comparator));
+ assertThat(SerializableTester.reserialize(comparator)).isSameInstanceAs(comparator);
// The Java implementation.
Comparator<byte[]> javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl();
Helpers.testComparator(javaImpl, ordered);
- assertSame(javaImpl, SerializableTester.reserialize(javaImpl));
+ assertThat(SerializableTester.reserialize(javaImpl)).isSameInstanceAs(javaImpl);
}
@SuppressWarnings("unchecked")
@@ -295,12 +300,12 @@ public class UnsignedBytesTest extends TestCase {
byte[] left = new byte[1 + rnd.nextInt(32)];
rnd.nextBytes(left);
byte[] right = left.clone();
- assertTrue(comparator.compare(left, right) == 0);
+ assertThat(comparator.compare(left, right)).isEqualTo(0);
int i = rnd.nextInt(left.length);
left[i] ^= (byte) (1 + rnd.nextInt(255));
- assertTrue(comparator.compare(left, right) != 0);
- assertEquals(
- comparator.compare(left, right) > 0, UnsignedBytes.compare(left[i], right[i]) > 0);
+ assertThat(comparator.compare(left, right)).isNotEqualTo(0);
+ assertThat(UnsignedBytes.compare(left[i], right[i]) > 0)
+ .isEqualTo(comparator.compare(left, right) > 0);
}
}
}
@@ -315,13 +320,13 @@ public class UnsignedBytesTest extends TestCase {
static void testSort(byte[] input, byte[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sort(input);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
static void testSort(byte[] input, int from, int to, byte[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sort(input, from, to);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
public void testSortIndexed() {
@@ -344,14 +349,14 @@ public class UnsignedBytesTest extends TestCase {
private static void testSortDescending(byte[] input, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
byte[] input, int fromIndex, int toIndex, byte[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedBytes.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
diff --git a/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java b/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java
index 04bf27d05..7034447a9 100644
--- a/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java
+++ b/guava-tests/test/com/google/common/primitives/UnsignedIntegerTest.java
@@ -14,8 +14,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
@@ -58,16 +62,18 @@ public class UnsignedIntegerTest extends TestCase {
public void testFromIntBitsAndIntValueAreInverses() {
for (int value : TEST_INTS) {
- assertEquals(
- UnsignedInts.toString(value), value, UnsignedInteger.fromIntBits(value).intValue());
+ assertWithMessage(UnsignedInts.toString(value))
+ .that(UnsignedInteger.fromIntBits(value).intValue())
+ .isEqualTo(value);
}
}
public void testFromIntBitsLongValue() {
for (int value : TEST_INTS) {
long expected = value & 0xffffffffL;
- assertEquals(
- UnsignedInts.toString(value), expected, UnsignedInteger.fromIntBits(value).longValue());
+ assertWithMessage(UnsignedInts.toString(value))
+ .that(UnsignedInteger.fromIntBits(value).longValue())
+ .isEqualTo(expected);
}
}
@@ -77,10 +83,10 @@ public class UnsignedIntegerTest extends TestCase {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= min && value <= max;
try {
- assertEquals(value, UnsignedInteger.valueOf(value).longValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedInteger.valueOf(value).longValue()).isEqualTo(value);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
@@ -91,10 +97,10 @@ public class UnsignedIntegerTest extends TestCase {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= min && value <= max;
try {
- assertEquals(value, UnsignedInteger.valueOf(BigInteger.valueOf(value)).longValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedInteger.valueOf(BigInteger.valueOf(value)).longValue()).isEqualTo(value);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
@@ -102,16 +108,17 @@ public class UnsignedIntegerTest extends TestCase {
public void testToString() {
for (int value : TEST_INTS) {
UnsignedInteger unsignedValue = UnsignedInteger.fromIntBits(value);
- assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString());
+ assertThat(unsignedValue.toString()).isEqualTo(unsignedValue.bigIntegerValue().toString());
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testToStringRadix() {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (int l : TEST_INTS) {
UnsignedInteger value = UnsignedInteger.fromIntBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -121,7 +128,7 @@ public class UnsignedIntegerTest extends TestCase {
for (int radix : radices) {
for (int l : TEST_INTS) {
UnsignedInteger value = UnsignedInteger.fromIntBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -129,14 +136,16 @@ public class UnsignedIntegerTest extends TestCase {
public void testFloatValue() {
for (int value : TEST_INTS) {
UnsignedInteger unsignedValue = UnsignedInteger.fromIntBits(value);
- assertEquals(unsignedValue.bigIntegerValue().floatValue(), unsignedValue.floatValue());
+ assertThat(unsignedValue.floatValue())
+ .isEqualTo(unsignedValue.bigIntegerValue().floatValue());
}
}
public void testDoubleValue() {
for (int value : TEST_INTS) {
UnsignedInteger unsignedValue = UnsignedInteger.fromIntBits(value);
- assertEquals(unsignedValue.bigIntegerValue().doubleValue(), unsignedValue.doubleValue());
+ assertThat(unsignedValue.doubleValue())
+ .isEqualTo(unsignedValue.bigIntegerValue().doubleValue());
}
}
@@ -147,7 +156,7 @@ public class UnsignedIntegerTest extends TestCase {
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
int expected = aUnsigned.bigIntegerValue().add(bUnsigned.bigIntegerValue()).intValue();
UnsignedInteger unsignedSum = aUnsigned.plus(bUnsigned);
- assertEquals(expected, unsignedSum.intValue());
+ assertThat(unsignedSum.intValue()).isEqualTo(expected);
}
}
}
@@ -160,11 +169,12 @@ public class UnsignedIntegerTest extends TestCase {
int expected =
force32(aUnsigned.bigIntegerValue().subtract(bUnsigned.bigIntegerValue()).intValue());
UnsignedInteger unsignedSub = aUnsigned.minus(bUnsigned);
- assertEquals(expected, unsignedSub.intValue());
+ assertThat(unsignedSub.intValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // multiply
public void testTimes() {
for (int a : TEST_INTS) {
@@ -174,7 +184,9 @@ public class UnsignedIntegerTest extends TestCase {
int expected =
force32(aUnsigned.bigIntegerValue().multiply(bUnsigned.bigIntegerValue()).intValue());
UnsignedInteger unsignedMul = aUnsigned.times(bUnsigned);
- assertEquals(aUnsigned + " * " + bUnsigned, expected, unsignedMul.intValue());
+ assertWithMessage(aUnsigned + " * " + bUnsigned)
+ .that(unsignedMul.intValue())
+ .isEqualTo(expected);
}
}
}
@@ -187,7 +199,7 @@ public class UnsignedIntegerTest extends TestCase {
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
int expected = aUnsigned.bigIntegerValue().divide(bUnsigned.bigIntegerValue()).intValue();
UnsignedInteger unsignedDiv = aUnsigned.dividedBy(bUnsigned);
- assertEquals(expected, unsignedDiv.intValue());
+ assertThat(unsignedDiv.intValue()).isEqualTo(expected);
}
}
}
@@ -211,7 +223,7 @@ public class UnsignedIntegerTest extends TestCase {
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
int expected = aUnsigned.bigIntegerValue().mod(bUnsigned.bigIntegerValue()).intValue();
UnsignedInteger unsignedRem = aUnsigned.mod(bUnsigned);
- assertEquals(expected, unsignedRem.intValue());
+ assertThat(unsignedRem.intValue()).isEqualTo(expected);
}
}
}
@@ -232,13 +244,13 @@ public class UnsignedIntegerTest extends TestCase {
for (int b : TEST_INTS) {
UnsignedInteger aUnsigned = UnsignedInteger.fromIntBits(a);
UnsignedInteger bUnsigned = UnsignedInteger.fromIntBits(b);
- assertEquals(
- aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()),
- aUnsigned.compareTo(bUnsigned));
+ assertThat(aUnsigned.compareTo(bUnsigned))
+ .isEqualTo(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()));
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testEquals() {
EqualsTester equalsTester = new EqualsTester();
@@ -257,10 +269,11 @@ public class UnsignedIntegerTest extends TestCase {
for (int a : TEST_INTS) {
UnsignedInteger aUnsigned = UnsignedInteger.fromIntBits(a);
int intValue = aUnsigned.bigIntegerValue().intValue();
- assertEquals(intValue, aUnsigned.intValue());
+ assertThat(aUnsigned.intValue()).isEqualTo(intValue);
}
}
+ @J2ktIncompatible
@GwtIncompatible // serialization
public void testSerialization() {
for (int a : TEST_INTS) {
@@ -268,6 +281,7 @@ public class UnsignedIntegerTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedInteger.class);
diff --git a/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java b/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java
index 0d0b38008..1b118863a 100644
--- a/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java
+++ b/guava-tests/test/com/google/common/primitives/UnsignedIntsTest.java
@@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import java.util.Arrays;
@@ -52,7 +53,7 @@ public class UnsignedIntsTest extends TestCase {
public void testCheckedCast() {
for (long value : UNSIGNED_INTS) {
- assertEquals(value, UnsignedInts.toLong(UnsignedInts.checkedCast(value)));
+ assertThat(UnsignedInts.toLong(UnsignedInts.checkedCast(value))).isEqualTo(value);
}
assertCastFails(1L << 32);
assertCastFails(-1L);
@@ -65,23 +66,23 @@ public class UnsignedIntsTest extends TestCase {
UnsignedInts.checkedCast(value);
fail("Cast to int should have failed: " + value);
} catch (IllegalArgumentException ex) {
- assertThat(ex.getMessage()).contains(String.valueOf(value));
+ assertThat(ex).hasMessageThat().contains(String.valueOf(value));
}
}
public void testSaturatedCast() {
for (long value : UNSIGNED_INTS) {
- assertEquals(value, UnsignedInts.toLong(UnsignedInts.saturatedCast(value)));
+ assertThat(UnsignedInts.toLong(UnsignedInts.saturatedCast(value))).isEqualTo(value);
}
- assertEquals(GREATEST, UnsignedInts.saturatedCast(1L << 32));
- assertEquals(LEAST, UnsignedInts.saturatedCast(-1L));
- assertEquals(GREATEST, UnsignedInts.saturatedCast(Long.MAX_VALUE));
- assertEquals(LEAST, UnsignedInts.saturatedCast(Long.MIN_VALUE));
+ assertThat(UnsignedInts.saturatedCast(1L << 32)).isEqualTo(GREATEST);
+ assertThat(UnsignedInts.saturatedCast(-1L)).isEqualTo(LEAST);
+ assertThat(UnsignedInts.saturatedCast(Long.MAX_VALUE)).isEqualTo(GREATEST);
+ assertThat(UnsignedInts.saturatedCast(Long.MIN_VALUE)).isEqualTo(LEAST);
}
public void testToLong() {
for (long a : UNSIGNED_INTS) {
- assertEquals(a, UnsignedInts.toLong((int) a));
+ assertThat(UnsignedInts.toLong((int) a)).isEqualTo(a);
}
}
@@ -90,7 +91,7 @@ public class UnsignedIntsTest extends TestCase {
for (long b : UNSIGNED_INTS) {
int cmpAsLongs = Longs.compare(a, b);
int cmpAsUInt = UnsignedInts.compare((int) a, (int) b);
- assertEquals(Integer.signum(cmpAsLongs), Integer.signum(cmpAsUInt));
+ assertThat(Integer.signum(cmpAsUInt)).isEqualTo(Integer.signum(cmpAsLongs));
}
}
}
@@ -104,18 +105,18 @@ public class UnsignedIntsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, UnsignedInts.max(LEAST));
- assertEquals(GREATEST, UnsignedInts.max(GREATEST));
- assertEquals(
- (int) 0xff1a618bL,
- UnsignedInts.max(
- (int) 8L,
- (int) 6L,
- (int) 7L,
- (int) 0x12345678L,
- (int) 0x5a4316b8L,
- (int) 0xff1a618bL,
- (int) 0L));
+ assertThat(UnsignedInts.max(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedInts.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedInts.max(
+ (int) 8L,
+ (int) 6L,
+ (int) 7L,
+ (int) 0x12345678L,
+ (int) 0x5a4316b8L,
+ (int) 0xff1a618bL,
+ (int) 0L))
+ .isEqualTo((int) 0xff1a618bL);
}
public void testMin_noArgs() {
@@ -127,18 +128,18 @@ public class UnsignedIntsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, UnsignedInts.min(LEAST));
- assertEquals(GREATEST, UnsignedInts.min(GREATEST));
- assertEquals(
- (int) 0L,
- UnsignedInts.min(
- (int) 8L,
- (int) 6L,
- (int) 7L,
- (int) 0x12345678L,
- (int) 0x5a4316b8L,
- (int) 0xff1a618bL,
- (int) 0L));
+ assertThat(UnsignedInts.min(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedInts.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedInts.min(
+ (int) 8L,
+ (int) 6L,
+ (int) 7L,
+ (int) 0x12345678L,
+ (int) 0x5a4316b8L,
+ (int) 0xff1a618bL,
+ (int) 0L))
+ .isEqualTo((int) 0L);
}
public void testLexicographicalComparator() {
@@ -168,13 +169,13 @@ public class UnsignedIntsTest extends TestCase {
static void testSort(int[] input, int[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sort(input);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
static void testSort(int[] input, int from, int to, int[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sort(input, from, to);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
public void testSortIndexed() {
@@ -196,14 +197,14 @@ public class UnsignedIntsTest extends TestCase {
private static void testSortDescending(int[] input, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
int[] input, int fromIndex, int toIndex, int[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedInts.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -223,10 +224,10 @@ public class UnsignedIntsTest extends TestCase {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
try {
- assertEquals((int) (a / b), UnsignedInts.divide((int) a, (int) b));
- assertFalse(b == 0);
+ assertThat(UnsignedInts.divide((int) a, (int) b)).isEqualTo((int) (a / b));
+ assertThat(b).isNotEqualTo(0);
} catch (ArithmeticException e) {
- assertEquals(0, b);
+ assertThat(b).isEqualTo(0);
}
}
}
@@ -236,15 +237,16 @@ public class UnsignedIntsTest extends TestCase {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
try {
- assertEquals((int) (a % b), UnsignedInts.remainder((int) a, (int) b));
- assertFalse(b == 0);
+ assertThat(UnsignedInts.remainder((int) a, (int) b)).isEqualTo((int) (a % b));
+ assertThat(b).isNotEqualTo(0);
} catch (ArithmeticException e) {
- assertEquals(0, b);
+ assertThat(b).isEqualTo(0);
}
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // Too slow in GWT (~3min fully optimized)
public void testDivideRemainderEuclideanProperty() {
// Use a seed so that the test is deterministic:
@@ -253,17 +255,17 @@ public class UnsignedIntsTest extends TestCase {
int dividend = r.nextInt();
int divisor = r.nextInt();
// Test that the Euclidean property is preserved:
- assertTrue(
- dividend
+ assertThat(
+ dividend
- (divisor * UnsignedInts.divide(dividend, divisor)
- + UnsignedInts.remainder(dividend, divisor))
- == 0);
+ + UnsignedInts.remainder(dividend, divisor)))
+ .isEqualTo(0);
}
}
public void testParseInt() {
for (long a : UNSIGNED_INTS) {
- assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a)));
+ assertThat(UnsignedInts.parseUnsignedInt(Long.toString(a))).isEqualTo((int) a);
}
}
@@ -278,7 +280,8 @@ public class UnsignedIntsTest extends TestCase {
public void testParseIntWithRadix() {
for (long a : UNSIGNED_INTS) {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
- assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a, radix), radix));
+ assertThat(UnsignedInts.parseUnsignedInt(Long.toString(a, radix), radix))
+ .isEqualTo((int) a);
}
}
}
@@ -288,10 +291,10 @@ public class UnsignedIntsTest extends TestCase {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
// tests can successfully parse a number string with this radix.
String maxAsString = Long.toString((1L << 32) - 1, radix);
- assertEquals(-1, UnsignedInts.parseUnsignedInt(maxAsString, radix));
+ assertThat(UnsignedInts.parseUnsignedInt(maxAsString, radix)).isEqualTo(-1);
try {
- // tests that we get exception whre an overflow would occur.
+ // tests that we get exception where an overflow would occur.
long overflow = 1L << 32;
String overflowAsString = Long.toString(overflow, radix);
UnsignedInts.parseUnsignedInt(overflowAsString, radix);
@@ -301,6 +304,7 @@ public class UnsignedIntsTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/285538920): Exception mismatch
public void testParseIntThrowsExceptionForInvalidRadix() {
// Valid radix values are Character.MIN_RADIX to Character.MAX_RADIX,
// inclusive.
@@ -325,13 +329,13 @@ public class UnsignedIntsTest extends TestCase {
}
public void testDecodeInt() {
- assertEquals(0xffffffff, UnsignedInts.decode("0xffffffff"));
- assertEquals(01234567, UnsignedInts.decode("01234567")); // octal
- assertEquals(0x12345678, UnsignedInts.decode("#12345678"));
- assertEquals(76543210, UnsignedInts.decode("76543210"));
- assertEquals(0x13579135, UnsignedInts.decode("0x13579135"));
- assertEquals(0x13579135, UnsignedInts.decode("0X13579135"));
- assertEquals(0, UnsignedInts.decode("0"));
+ assertThat(UnsignedInts.decode("0xffffffff")).isEqualTo(0xffffffff);
+ assertThat(UnsignedInts.decode("01234567")).isEqualTo(01234567); // octal
+ assertThat(UnsignedInts.decode("#12345678")).isEqualTo(0x12345678);
+ assertThat(UnsignedInts.decode("76543210")).isEqualTo(76543210);
+ assertThat(UnsignedInts.decode("0x13579135")).isEqualTo(0x13579135);
+ assertThat(UnsignedInts.decode("0X13579135")).isEqualTo(0x13579135);
+ assertThat(UnsignedInts.decode("0")).isEqualTo(0);
}
public void testDecodeIntFails() {
@@ -365,24 +369,25 @@ public class UnsignedIntsTest extends TestCase {
int[] bases = {2, 5, 7, 8, 10, 16};
for (long a : UNSIGNED_INTS) {
for (int base : bases) {
- assertEquals(UnsignedInts.toString((int) a, base), Long.toString(a, base));
+ assertThat(Long.toString(a, base)).isEqualTo(UnsignedInts.toString((int) a, base));
}
}
}
public void testJoin() {
- assertEquals("", join());
- assertEquals("1", join(1));
- assertEquals("1,2", join(1, 2));
- assertEquals("4294967295,2147483648", join(-1, Integer.MIN_VALUE));
+ assertThat(join()).isEmpty();
+ assertThat(join(1)).isEqualTo("1");
+ assertThat(join(1, 2)).isEqualTo("1,2");
+ assertThat(join(-1, Integer.MIN_VALUE)).isEqualTo("4294967295,2147483648");
- assertEquals("123", UnsignedInts.join("", 1, 2, 3));
+ assertThat(UnsignedInts.join("", 1, 2, 3)).isEqualTo("123");
}
private static String join(int... values) {
return UnsignedInts.join(",", values);
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedInts.class);
diff --git a/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java b/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java
index cfa286257..335e6e3ef 100644
--- a/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java
+++ b/guava-tests/test/com/google/common/primitives/UnsignedLongTest.java
@@ -14,8 +14,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
@@ -69,8 +73,9 @@ public class UnsignedLongTest extends TestCase {
public void testAsUnsignedAndLongValueAreInverses() {
for (long value : TEST_LONGS) {
- assertEquals(
- UnsignedLongs.toString(value), value, UnsignedLong.fromLongBits(value).longValue());
+ assertWithMessage(UnsignedLongs.toString(value))
+ .that(UnsignedLong.fromLongBits(value).longValue())
+ .isEqualTo(value);
}
}
@@ -80,10 +85,9 @@ public class UnsignedLongTest extends TestCase {
(value >= 0)
? BigInteger.valueOf(value)
: BigInteger.valueOf(value).add(BigInteger.ZERO.setBit(64));
- assertEquals(
- UnsignedLongs.toString(value),
- expected,
- UnsignedLong.fromLongBits(value).bigIntegerValue());
+ assertWithMessage(UnsignedLongs.toString(value))
+ .that(UnsignedLong.fromLongBits(value).bigIntegerValue())
+ .isEqualTo(expected);
}
}
@@ -91,24 +95,25 @@ public class UnsignedLongTest extends TestCase {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= 0;
try {
- assertEquals(value, UnsignedLong.valueOf(value).longValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedLong.valueOf(value).longValue()).isEqualTo(value);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testValueOfBigInteger() {
BigInteger min = BigInteger.ZERO;
BigInteger max = UnsignedLong.MAX_VALUE.bigIntegerValue();
for (BigInteger big : TEST_BIG_INTEGERS) {
boolean expectSuccess = big.compareTo(min) >= 0 && big.compareTo(max) <= 0;
try {
- assertEquals(big, UnsignedLong.valueOf(big).bigIntegerValue());
- assertTrue(expectSuccess);
+ assertThat(UnsignedLong.valueOf(big).bigIntegerValue()).isEqualTo(big);
+ assertThat(expectSuccess).isTrue();
} catch (IllegalArgumentException e) {
- assertFalse(expectSuccess);
+ assertThat(expectSuccess).isFalse();
}
}
}
@@ -116,16 +121,17 @@ public class UnsignedLongTest extends TestCase {
public void testToString() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
- assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString());
+ assertThat(unsignedValue.toString()).isEqualTo(unsignedValue.bigIntegerValue().toString());
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testToStringRadix() {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
for (long l : TEST_LONGS) {
UnsignedLong value = UnsignedLong.fromLongBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -135,7 +141,7 @@ public class UnsignedLongTest extends TestCase {
for (int radix : radices) {
for (long l : TEST_LONGS) {
UnsignedLong value = UnsignedLong.fromLongBits(l);
- assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
+ assertThat(value.toString(radix)).isEqualTo(value.bigIntegerValue().toString(radix));
}
}
}
@@ -144,25 +150,24 @@ public class UnsignedLongTest extends TestCase {
public void testFloatValue() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
- assertEquals(
- "Float value of " + unsignedValue,
- unsignedValue.bigIntegerValue().floatValue(),
- unsignedValue.floatValue(),
- 0.0f);
+ assertWithMessage("Float value of " + unsignedValue)
+ .that(unsignedValue.floatValue())
+ .isWithin(0.0f)
+ .of(unsignedValue.bigIntegerValue().floatValue());
}
}
public void testDoubleValue() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
- assertEquals(
- "Double value of " + unsignedValue,
- unsignedValue.bigIntegerValue().doubleValue(),
- unsignedValue.doubleValue(),
- 0.0);
+ assertWithMessage("Double value of " + unsignedValue)
+ .that(unsignedValue.doubleValue())
+ .isWithin(0.0)
+ .of(unsignedValue.bigIntegerValue().doubleValue());
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testPlus() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -170,11 +175,12 @@ public class UnsignedLongTest extends TestCase {
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned.bigIntegerValue().add(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedSum = aUnsigned.plus(bUnsigned);
- assertEquals(expected, unsignedSum.longValue());
+ assertThat(unsignedSum.longValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testMinus() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -183,11 +189,12 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().subtract(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedSub = aUnsigned.minus(bUnsigned);
- assertEquals(expected, unsignedSub.longValue());
+ assertThat(unsignedSub.longValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testTimes() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -196,11 +203,12 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().multiply(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedMul = aUnsigned.times(bUnsigned);
- assertEquals(expected, unsignedMul.longValue());
+ assertThat(unsignedMul.longValue()).isEqualTo(expected);
}
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testDividedBy() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -210,7 +218,7 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().divide(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedDiv = aUnsigned.dividedBy(bUnsigned);
- assertEquals(expected, unsignedDiv.longValue());
+ assertThat(unsignedDiv.longValue()).isEqualTo(expected);
}
}
}
@@ -226,6 +234,7 @@ public class UnsignedLongTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/285538920): Wrong result for j2kt
public void testMod() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
@@ -235,7 +244,7 @@ public class UnsignedLongTest extends TestCase {
long expected =
aUnsigned.bigIntegerValue().remainder(bUnsigned.bigIntegerValue()).longValue();
UnsignedLong unsignedRem = aUnsigned.mod(bUnsigned);
- assertEquals(expected, unsignedRem.longValue());
+ assertThat(unsignedRem.longValue()).isEqualTo(expected);
}
}
}
@@ -256,13 +265,13 @@ public class UnsignedLongTest extends TestCase {
for (long b : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
- assertEquals(
- aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()),
- aUnsigned.compareTo(bUnsigned));
+ assertThat(aUnsigned.compareTo(bUnsigned))
+ .isEqualTo(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()));
}
}
}
+ @J2ktIncompatible
@GwtIncompatible // too slow
public void testEquals() {
EqualsTester equalsTester = new EqualsTester();
@@ -282,10 +291,11 @@ public class UnsignedLongTest extends TestCase {
for (long a : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
int intValue = aUnsigned.bigIntegerValue().intValue();
- assertEquals(intValue, aUnsigned.intValue());
+ assertThat(aUnsigned.intValue()).isEqualTo(intValue);
}
}
+ @J2ktIncompatible
@GwtIncompatible // serialization
public void testSerialization() {
for (long a : TEST_LONGS) {
@@ -293,6 +303,7 @@ public class UnsignedLongTest extends TestCase {
}
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedLong.class);
diff --git a/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java b/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java
index a8b799577..faa8ec72a 100644
--- a/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java
+++ b/guava-tests/test/com/google/common/primitives/UnsignedLongsTest.java
@@ -14,10 +14,12 @@
package com.google.common.primitives;
+import static com.google.common.truth.Truth.assertThat;
import static java.math.BigInteger.ONE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.testing.NullPointerTester;
import java.math.BigInteger;
@@ -40,23 +42,23 @@ public class UnsignedLongsTest extends TestCase {
public void testCompare() {
// max value
- assertTrue(UnsignedLongs.compare(0, 0xffffffffffffffffL) < 0);
- assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0) > 0);
+ assertThat(UnsignedLongs.compare(0, 0xffffffffffffffffL)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0xffffffffffffffffL, 0)).isGreaterThan(0);
// both with high bit set
- assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xffffffffffffffffL) < 0);
- assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0xff1a618b7f65ea12L) > 0);
+ assertThat(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xffffffffffffffffL)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0xffffffffffffffffL, 0xff1a618b7f65ea12L)).isGreaterThan(0);
// one with high bit set
- assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0xff1a618b7f65ea12L) < 0);
- assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0x5a4316b8c153ac4dL) > 0);
+ assertThat(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0xff1a618b7f65ea12L)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0x5a4316b8c153ac4dL)).isGreaterThan(0);
// neither with high bit set
- assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0x6cf78a4b139a4e2aL) < 0);
- assertTrue(UnsignedLongs.compare(0x6cf78a4b139a4e2aL, 0x5a4316b8c153ac4dL) > 0);
+ assertThat(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0x6cf78a4b139a4e2aL)).isLessThan(0);
+ assertThat(UnsignedLongs.compare(0x6cf78a4b139a4e2aL, 0x5a4316b8c153ac4dL)).isGreaterThan(0);
// same value
- assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xff1a618b7f65ea12L) == 0);
+ assertThat(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xff1a618b7f65ea12L)).isEqualTo(0);
}
public void testMax_noArgs() {
@@ -68,12 +70,12 @@ public class UnsignedLongsTest extends TestCase {
}
public void testMax() {
- assertEquals(LEAST, UnsignedLongs.max(LEAST));
- assertEquals(GREATEST, UnsignedLongs.max(GREATEST));
- assertEquals(
- 0xff1a618b7f65ea12L,
- UnsignedLongs.max(
- 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L));
+ assertThat(UnsignedLongs.max(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedLongs.max(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedLongs.max(
+ 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L))
+ .isEqualTo(0xff1a618b7f65ea12L);
}
public void testMin_noArgs() {
@@ -85,12 +87,12 @@ public class UnsignedLongsTest extends TestCase {
}
public void testMin() {
- assertEquals(LEAST, UnsignedLongs.min(LEAST));
- assertEquals(GREATEST, UnsignedLongs.min(GREATEST));
- assertEquals(
- 0L,
- UnsignedLongs.min(
- 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L));
+ assertThat(UnsignedLongs.min(LEAST)).isEqualTo(LEAST);
+ assertThat(UnsignedLongs.min(GREATEST)).isEqualTo(GREATEST);
+ assertThat(
+ UnsignedLongs.min(
+ 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L))
+ .isEqualTo(0L);
}
public void testLexicographicalComparator() {
@@ -120,13 +122,13 @@ public class UnsignedLongsTest extends TestCase {
static void testSort(long[] input, long[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sort(input);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
static void testSort(long[] input, int from, int to, long[] expected) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sort(input, from, to);
- assertTrue(Arrays.equals(expected, input));
+ assertThat(input).isEqualTo(expected);
}
public void testSortIndexed() {
@@ -149,14 +151,14 @@ public class UnsignedLongsTest extends TestCase {
private static void testSortDescending(long[] input, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sortDescending(input);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
private static void testSortDescending(
long[] input, int fromIndex, int toIndex, long[] expectedOutput) {
input = Arrays.copyOf(input, input.length);
UnsignedLongs.sortDescending(input, fromIndex, toIndex);
- assertTrue(Arrays.equals(expectedOutput, input));
+ assertThat(input).isEqualTo(expectedOutput);
}
public void testSortDescendingIndexed() {
@@ -173,26 +175,27 @@ public class UnsignedLongsTest extends TestCase {
}
public void testDivide() {
- assertEquals(2, UnsignedLongs.divide(14, 5));
- assertEquals(0, UnsignedLongs.divide(0, 50));
- assertEquals(1, UnsignedLongs.divide(0xfffffffffffffffeL, 0xfffffffffffffffdL));
- assertEquals(0, UnsignedLongs.divide(0xfffffffffffffffdL, 0xfffffffffffffffeL));
- assertEquals(281479271743488L, UnsignedLongs.divide(0xfffffffffffffffeL, 65535));
- assertEquals(0x7fffffffffffffffL, UnsignedLongs.divide(0xfffffffffffffffeL, 2));
- assertEquals(3689348814741910322L, UnsignedLongs.divide(0xfffffffffffffffeL, 5));
+ assertThat(UnsignedLongs.divide(14, 5)).isEqualTo(2);
+ assertThat(UnsignedLongs.divide(0, 50)).isEqualTo(0);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 0xfffffffffffffffdL)).isEqualTo(1);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffdL, 0xfffffffffffffffeL)).isEqualTo(0);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 65535)).isEqualTo(281479271743488L);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 2)).isEqualTo(0x7fffffffffffffffL);
+ assertThat(UnsignedLongs.divide(0xfffffffffffffffeL, 5)).isEqualTo(3689348814741910322L);
}
public void testRemainder() {
- assertEquals(4, UnsignedLongs.remainder(14, 5));
- assertEquals(0, UnsignedLongs.remainder(0, 50));
- assertEquals(1, UnsignedLongs.remainder(0xfffffffffffffffeL, 0xfffffffffffffffdL));
- assertEquals(
- 0xfffffffffffffffdL, UnsignedLongs.remainder(0xfffffffffffffffdL, 0xfffffffffffffffeL));
- assertEquals(65534L, UnsignedLongs.remainder(0xfffffffffffffffeL, 65535));
- assertEquals(0, UnsignedLongs.remainder(0xfffffffffffffffeL, 2));
- assertEquals(4, UnsignedLongs.remainder(0xfffffffffffffffeL, 5));
+ assertThat(UnsignedLongs.remainder(14, 5)).isEqualTo(4);
+ assertThat(UnsignedLongs.remainder(0, 50)).isEqualTo(0);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 0xfffffffffffffffdL)).isEqualTo(1);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffdL, 0xfffffffffffffffeL))
+ .isEqualTo(0xfffffffffffffffdL);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 65535)).isEqualTo(65534L);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 2)).isEqualTo(0);
+ assertThat(UnsignedLongs.remainder(0xfffffffffffffffeL, 5)).isEqualTo(4);
}
+ @J2ktIncompatible
@GwtIncompatible // Too slow in GWT (~3min fully optimized)
public void testDivideRemainderEuclideanProperty() {
// Use a seed so that the test is deterministic:
@@ -201,20 +204,25 @@ public class UnsignedLongsTest extends TestCase {
long dividend = r.nextLong();
long divisor = r.nextLong();
// Test that the Euclidean property is preserved:
- assertEquals(
- 0,
- dividend
- - (divisor * UnsignedLongs.divide(dividend, divisor)
- + UnsignedLongs.remainder(dividend, divisor)));
+ assertThat(
+ dividend
+ - (divisor * UnsignedLongs.divide(dividend, divisor)
+ + UnsignedLongs.remainder(dividend, divisor)))
+ .isEqualTo(0);
}
}
public void testParseLong() {
- assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("18446744073709551615"));
- assertEquals(0x7fffffffffffffffL, UnsignedLongs.parseUnsignedLong("9223372036854775807"));
- assertEquals(0xff1a618b7f65ea12L, UnsignedLongs.parseUnsignedLong("18382112080831834642"));
- assertEquals(0x5a4316b8c153ac4dL, UnsignedLongs.parseUnsignedLong("6504067269626408013"));
- assertEquals(0x6cf78a4b139a4e2aL, UnsignedLongs.parseUnsignedLong("7851896530399809066"));
+ assertThat(UnsignedLongs.parseUnsignedLong("18446744073709551615"))
+ .isEqualTo(0xffffffffffffffffL);
+ assertThat(UnsignedLongs.parseUnsignedLong("9223372036854775807"))
+ .isEqualTo(0x7fffffffffffffffL);
+ assertThat(UnsignedLongs.parseUnsignedLong("18382112080831834642"))
+ .isEqualTo(0xff1a618b7f65ea12L);
+ assertThat(UnsignedLongs.parseUnsignedLong("6504067269626408013"))
+ .isEqualTo(0x5a4316b8c153ac4dL);
+ assertThat(UnsignedLongs.parseUnsignedLong("7851896530399809066"))
+ .isEqualTo(0x6cf78a4b139a4e2aL);
}
public void testParseLongEmptyString() {
@@ -235,13 +243,13 @@ public class UnsignedLongsTest extends TestCase {
}
public void testDecodeLong() {
- assertEquals(0xffffffffffffffffL, UnsignedLongs.decode("0xffffffffffffffff"));
- assertEquals(01234567, UnsignedLongs.decode("01234567")); // octal
- assertEquals(0x1234567890abcdefL, UnsignedLongs.decode("#1234567890abcdef"));
- assertEquals(987654321012345678L, UnsignedLongs.decode("987654321012345678"));
- assertEquals(0x135791357913579L, UnsignedLongs.decode("0x135791357913579"));
- assertEquals(0x135791357913579L, UnsignedLongs.decode("0X135791357913579"));
- assertEquals(0L, UnsignedLongs.decode("0"));
+ assertThat(UnsignedLongs.decode("0xffffffffffffffff")).isEqualTo(0xffffffffffffffffL);
+ assertThat(UnsignedLongs.decode("01234567")).isEqualTo(01234567); // octal
+ assertThat(UnsignedLongs.decode("#1234567890abcdef")).isEqualTo(0x1234567890abcdefL);
+ assertThat(UnsignedLongs.decode("987654321012345678")).isEqualTo(987654321012345678L);
+ assertThat(UnsignedLongs.decode("0x135791357913579")).isEqualTo(0x135791357913579L);
+ assertThat(UnsignedLongs.decode("0X135791357913579")).isEqualTo(0x135791357913579L);
+ assertThat(UnsignedLongs.decode("0")).isEqualTo(0L);
}
public void testDecodeLongFails() {
@@ -272,8 +280,10 @@ public class UnsignedLongsTest extends TestCase {
}
public void testParseLongWithRadix() {
- assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("ffffffffffffffff", 16));
- assertEquals(0x1234567890abcdefL, UnsignedLongs.parseUnsignedLong("1234567890abcdef", 16));
+ assertThat(UnsignedLongs.parseUnsignedLong("ffffffffffffffff", 16))
+ .isEqualTo(0xffffffffffffffffL);
+ assertThat(UnsignedLongs.parseUnsignedLong("1234567890abcdef", 16))
+ .isEqualTo(0x1234567890abcdefL);
}
public void testParseLongWithRadixLimits() {
@@ -282,10 +292,10 @@ public class UnsignedLongsTest extends TestCase {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
// tests can successfully parse a number string with this radix.
String maxAsString = max.toString(radix);
- assertEquals(max.longValue(), UnsignedLongs.parseUnsignedLong(maxAsString, radix));
+ assertThat(UnsignedLongs.parseUnsignedLong(maxAsString, radix)).isEqualTo(max.longValue());
try {
- // tests that we get exception whre an overflow would occur.
+ // tests that we get exception where an overflow would occur.
BigInteger overflow = max.add(ONE);
String overflowAsString = overflow.toString(radix);
UnsignedLongs.parseUnsignedLong(overflowAsString, radix);
@@ -323,6 +333,7 @@ public class UnsignedLongsTest extends TestCase {
}
}
+ @J2ktIncompatible // TODO(b/285562794): Wrong result for j2kt
public void testToString() {
String[] tests = {
"0",
@@ -337,22 +348,23 @@ public class UnsignedLongsTest extends TestCase {
for (String x : tests) {
BigInteger xValue = new BigInteger(x, 16);
long xLong = xValue.longValue(); // signed
- assertEquals(xValue.toString(base), UnsignedLongs.toString(xLong, base));
+ assertThat(UnsignedLongs.toString(xLong, base)).isEqualTo(xValue.toString(base));
}
}
}
public void testJoin() {
- assertEquals("", UnsignedLongs.join(","));
- assertEquals("1", UnsignedLongs.join(",", 1));
- assertEquals("1,2", UnsignedLongs.join(",", 1, 2));
- assertEquals(
- "18446744073709551615,9223372036854775808", UnsignedLongs.join(",", -1, Long.MIN_VALUE));
- assertEquals("123", UnsignedLongs.join("", 1, 2, 3));
- assertEquals(
- "184467440737095516159223372036854775808", UnsignedLongs.join("", -1, Long.MIN_VALUE));
+ assertThat(UnsignedLongs.join(",")).isEmpty();
+ assertThat(UnsignedLongs.join(",", 1)).isEqualTo("1");
+ assertThat(UnsignedLongs.join(",", 1, 2)).isEqualTo("1,2");
+ assertThat(UnsignedLongs.join(",", -1, Long.MIN_VALUE))
+ .isEqualTo("18446744073709551615,9223372036854775808");
+ assertThat(UnsignedLongs.join("", 1, 2, 3)).isEqualTo("123");
+ assertThat(UnsignedLongs.join("", -1, Long.MIN_VALUE))
+ .isEqualTo("184467440737095516159223372036854775808");
}
+ @J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNulls() {
new NullPointerTester().testAllPublicStaticMethods(UnsignedLongs.class);
diff --git a/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java b/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java
index 56b20bdfb..310878f98 100644
--- a/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java
+++ b/guava-tests/test/com/google/common/reflect/AbstractInvocationHandlerTest.java
@@ -26,6 +26,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link AbstractInvocationHandler}.
@@ -136,7 +137,7 @@ public class AbstractInvocationHandlerTest extends TestCase {
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof DelegatingInvocationHandlerWithEquals) {
DelegatingInvocationHandlerWithEquals that = (DelegatingInvocationHandlerWithEquals) obj;
return delegate.equals(that.delegate);
diff --git a/guava-tests/test/com/google/common/reflect/ClassPathTest.java b/guava-tests/test/com/google/common/reflect/ClassPathTest.java
index 797baeb9f..8aed780d4 100644
--- a/guava-tests/test/com/google/common/reflect/ClassPathTest.java
+++ b/guava-tests/test/com/google/common/reflect/ClassPathTest.java
@@ -17,6 +17,7 @@ package com.google.common.reflect;
import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR;
import static com.google.common.io.MoreFiles.deleteRecursively;
import static com.google.common.truth.Truth.assertThat;
@@ -184,6 +185,7 @@ public class ClassPathTest extends TestCase {
assertThat(ClassPath.from(classloader).getTopLevelClasses()).isNotEmpty();
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScan_classPathCycle() throws IOException {
File jarFile = File.createTempFile("with_circular_class_path", ".jar");
@@ -201,6 +203,9 @@ public class ClassPathTest extends TestCase {
@AndroidIncompatible // Path (for symlink creation)
public void testScanDirectory_symlinkCycle() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Can we detect cycles under Windows?
+ }
ClassLoader loader = ClassPathTest.class.getClassLoader();
// directory with a cycle,
// /root
@@ -233,6 +238,9 @@ public class ClassPathTest extends TestCase {
@AndroidIncompatible // Path (for symlink creation)
public void testScanDirectory_symlinkToRootCycle() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Can we detect cycles under Windows?
+ }
ClassLoader loader = ClassPathTest.class.getClassLoader();
// directory with a cycle,
// /root
@@ -260,6 +268,7 @@ public class ClassPathTest extends TestCase {
.isEmpty();
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanFromFile_notJarFile() throws IOException {
ClassLoader classLoader = ClassPathTest.class.getClassLoader();
@@ -272,6 +281,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathEntry() throws MalformedURLException, URISyntaxException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
assertEquals(
new File("/usr/test/dep.jar").toURI(),
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "file:/usr/test/dep.jar")
@@ -342,6 +354,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathFromManifest_absoluteDirectory() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
@@ -349,6 +364,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathFromManifest_absoluteJar() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
@@ -356,6 +374,9 @@ public class ClassPathTest extends TestCase {
}
public void testGetClassPathFromManifest_multiplePaths() throws IOException {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute.jar relative.jar relative/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
@@ -411,7 +432,11 @@ public class ClassPathTest extends TestCase {
// Test that ResourceInfo.urls() returns identical content to ClassLoader.getResources()
+ @AndroidIncompatible
public void testGetClassPathUrls() throws Exception {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - We need to account for drive letters in the path.
+ }
String oldPathSeparator = PATH_SEPARATOR.value();
String oldClassPath = JAVA_CLASS_PATH.value();
System.setProperty(PATH_SEPARATOR.key(), ":");
@@ -458,6 +483,7 @@ public class ClassPathTest extends TestCase {
.testAllPublicInstanceMethods(ClassPath.from(getClass().getClassLoader()));
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testLocationsFrom_idempotentScan() throws IOException {
ImmutableSet<ClassPath.LocationInfo> locations =
@@ -488,6 +514,7 @@ public class ClassPathTest extends TestCase {
.testEquals();
}
+ @AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanAllResources() throws IOException {
assertThat(scanResourceNames(ClassLoader.getSystemClassLoader()))
@@ -602,6 +629,10 @@ public class ClassPathTest extends TestCase {
}
private static URL makeJarUrlWithName(String name) throws IOException {
+ /*
+ * TODO: cpovirk - Use java.nio.file.Files.createTempDirectory instead of
+ * c.g.c.io.Files.createTempDir?
+ */
File fullPath = new File(Files.createTempDir(), name);
File jarFile = pickAnyJarFile();
Files.copy(jarFile, fullPath);
@@ -636,4 +667,8 @@ public class ClassPathTest extends TestCase {
}
return builder.build();
}
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/guava-tests/test/com/google/common/reflect/InvokableTest.java b/guava-tests/test/com/google/common/reflect/InvokableTest.java
index 5e15d6643..60c8c15e4 100644
--- a/guava-tests/test/com/google/common/reflect/InvokableTest.java
+++ b/guava-tests/test/com/google/common/reflect/InvokableTest.java
@@ -49,9 +49,9 @@ public class InvokableTest extends TestCase {
public void testApiCompatibleWithAccessibleObject() {
ImmutableSet<String> invokableMethods =
publicMethodSignatures(Invokable.class, ImmutableSet.<String>of());
- ImmutableSet<String> accesibleObjectMethods =
+ ImmutableSet<String> accessibleObjectMethods =
publicMethodSignatures(AccessibleObject.class, ImmutableSet.of("canAccess"));
- assertThat(invokableMethods).containsAtLeastElementsIn(accesibleObjectMethods);
+ assertThat(invokableMethods).containsAtLeastElementsIn(accessibleObjectMethods);
Class<?> genericDeclaration;
try {
genericDeclaration = Class.forName("java.lang.reflect.GenericDeclaration");
@@ -453,7 +453,7 @@ public class InvokableTest extends TestCase {
static class Foo {}
- public void testConstructor_isOverridablel() throws Exception {
+ public void testConstructor_isOverridable() throws Exception {
Invokable<?, ?> delegate = Invokable.from(Foo.class.getDeclaredConstructor());
assertFalse(delegate.isOverridable());
assertFalse(delegate.isVarArgs());
@@ -733,7 +733,7 @@ public class InvokableTest extends TestCase {
private final String prefix;
private final int times;
- Prepender(@NotBlank String prefix, int times) throws NullPointerException {
+ Prepender(@NotBlank @Nullable String prefix, int times) throws NullPointerException {
this.prefix = prefix;
this.times = times;
}
diff --git a/guava-tests/test/com/google/common/reflect/ParameterTest.java b/guava-tests/test/com/google/common/reflect/ParameterTest.java
index 6e0500a9c..86ea0104f 100644
--- a/guava-tests/test/com/google/common/reflect/ParameterTest.java
+++ b/guava-tests/test/com/google/common/reflect/ParameterTest.java
@@ -29,6 +29,16 @@ import junit.framework.TestCase;
public class ParameterTest extends TestCase {
public void testNulls() {
+ try {
+ Class.forName("java.lang.reflect.AnnotatedType");
+ } catch (ClassNotFoundException runningInAndroidVm) {
+ /*
+ * Parameter declares a method that returns AnnotatedType, which isn't available on Android.
+ * This would cause NullPointerTester, which calls Class.getDeclaredMethods, to throw
+ * NoClassDefFoundError.
+ */
+ return;
+ }
for (Method method : ParameterTest.class.getDeclaredMethods()) {
for (Parameter param : Invokable.from(method).getParameters()) {
new NullPointerTester().testAllPublicInstanceMethods(param);
diff --git a/guava-tests/test/com/google/common/reflect/SubtypeTester.java b/guava-tests/test/com/google/common/reflect/SubtypeTester.java
index 3eec66843..7cd61c129 100644
--- a/guava-tests/test/com/google/common/reflect/SubtypeTester.java
+++ b/guava-tests/test/com/google/common/reflect/SubtypeTester.java
@@ -30,6 +30,7 @@ import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Comparator;
import javax.lang.model.element.Modifier;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tester of subtyping relationships between two types.
@@ -78,7 +79,7 @@ abstract class SubtypeTester implements Cloneable {
boolean suppressGetSupertype() default false;
}
- private Method method = null;
+ private @Nullable Method method = null;
/** Call this in a {@link TestSubtype} public method asserting subtype relationship. */
final <T> T isSubtype(T sub) {
@@ -105,7 +106,7 @@ abstract class SubtypeTester implements Cloneable {
* Call this in a {@link TestSubtype} public method asserting that subtype relationship does not
* hold.
*/
- final <X> X notSubtype(@SuppressWarnings("unused") Object sub) {
+ final <X> @Nullable X notSubtype(@SuppressWarnings("unused") Object sub) {
Type returnType = method.getGenericReturnType();
Type paramType = getOnlyParameterType();
TestSubtype spec = method.getAnnotation(TestSubtype.class);
diff --git a/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java b/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
index 69e59ff18..b8f5edbe0 100644
--- a/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
+++ b/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
@@ -178,10 +178,12 @@ public class TypeTokenResolutionTest extends TestCase {
assertEquals(String.class, new Owner.Nested<String>() {}.getTypeArgument());
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testResolveInnerClass() {
assertEquals(String.class, new Owner<Integer>().new Inner<String>() {}.getTypeArgument());
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testResolveOwnerClass() {
assertEquals(Integer.class, new Owner<Integer>().new Inner<String>() {}.getOwnerType());
}
@@ -253,7 +255,7 @@ public class TypeTokenResolutionTest extends TestCase {
}
}
- public void testConextIsParameterizedType() throws Exception {
+ public void testContextIsParameterizedType() throws Exception {
class Context {
@SuppressWarnings("unused") // used by reflection
Map<String, Integer> returningMap() {
diff --git a/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java b/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
index 0dd2318e9..b25aab57c 100644
--- a/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
+++ b/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
@@ -47,30 +47,35 @@ public class TypeTokenSubtypeTest extends TestCase {
}
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfInnerClass_nonStaticAnonymousClass() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfInnerClass_nonStaticAnonymousClass_typeParameterOfOwnerTypeNotMatch() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Indoor>().new Shop<Electronics>() {}.getClass();
assertFalse(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfInnerClass_nonStaticAnonymousClass_typeParameterOfInnerTypeNotMatch() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Outdoor>().new Shop<Grocery>() {}.getClass();
assertFalse(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public static void testSubtypeOfInnerClass_staticAnonymousClass() {
TypeToken<?> supertype = new TypeToken<Mall<Outdoor>.Shop<Electronics>>() {};
Class<?> subclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(subclass).isSubtypeOf(supertype));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public static void testSubtypeOfStaticAnonymousClass() {
Class<?> superclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(superclass).isSubtypeOf(superclass));
@@ -79,6 +84,7 @@ public class TypeTokenSubtypeTest extends TestCase {
.isSubtypeOf(superclass));
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public void testSubtypeOfNonStaticAnonymousClass() {
Class<?> superclass = new Mall<Outdoor>().new Shop<Electronics>() {}.getClass();
assertTrue(TypeToken.of(superclass).isSubtypeOf(superclass));
@@ -231,7 +237,7 @@ public class TypeTokenSubtypeTest extends TestCase {
@TestSubtype(suppressGetSupertype = true, suppressGetSubtype = true)
public List<RecursiveTypeBoundBugExample<?>> ifYouUseTheTypeVariableOnTheClassAndItIsRecursive(
List<RecursiveTypeBoundBugExample<? extends RecursiveTypeBoundBugExample<T>>> arg) {
- return notSubtype(arg); // isSubtype() currently incorectly considers it a subtype.
+ return notSubtype(arg); // isSubtype() currently incorrectly considers it a subtype.
}
}
diff --git a/guava-tests/test/com/google/common/reflect/TypeTokenTest.java b/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
index 171ef49fd..5d66b840b 100644
--- a/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
+++ b/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
@@ -402,7 +402,7 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends ArrayList<String> & CharSequence>
+ public <T extends ArrayList<String> & Serializable>
void testGetGenericSuperclass_typeVariable_boundIsClass() {
assertEquals(
new TypeToken<ArrayList<String>>() {},
@@ -410,7 +410,7 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends Enum<T> & CharSequence>
+ public <T extends Enum<T> & Serializable>
void testGetGenericSuperclass_typeVariable_boundIsFBoundedClass() {
assertEquals(
new TypeToken<Enum<T>>() {},
@@ -418,13 +418,13 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends List<String> & CharSequence>
+ public <T extends List<String> & Serializable>
void testGetGenericSuperclass_typeVariable_boundIsInterface() {
assertNull(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericSuperclass());
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends ArrayList<String> & CharSequence, T1 extends T>
+ public <T extends ArrayList<String> & Serializable, T1 extends T>
void testGetGenericSuperclass_typeVariable_boundIsTypeVariableAndClass() {
assertEquals(
TypeToken.of(new TypeCapture<T>() {}.capture()),
@@ -432,7 +432,7 @@ public class TypeTokenTest extends TestCase {
assertEquals(TypeToken.of(Object.class), new TypeToken<T[]>() {}.getGenericSuperclass());
}
- public <T extends List<String> & CharSequence, T1 extends T>
+ public <T extends List<String> & Serializable, T1 extends T>
void testGetGenericSuperclass_typeVariable_boundIsTypeVariableAndInterface() {
assertNull(TypeToken.of(new TypeCapture<T1>() {}.capture()).getGenericSuperclass());
assertEquals(TypeToken.of(Object.class), new TypeToken<T1[]>() {}.getGenericSuperclass());
@@ -1101,7 +1101,7 @@ public class TypeTokenTest extends TestCase {
}
public void testGetSupertype_chained() {
- @SuppressWarnings("unchecked") // StringListIterable extensd ListIterable<String>
+ @SuppressWarnings("unchecked") // StringListIterable extends ListIterable<String>
TypeToken<ListIterable<String>> listIterableType =
(TypeToken<ListIterable<String>>)
TypeToken.of(StringListIterable.class).getSupertype(ListIterable.class);
@@ -1747,6 +1747,7 @@ public class TypeTokenTest extends TestCase {
}
}
+ @SuppressWarnings("RestrictedApiChecker") // crashes under JDK8, which EP no longer supports
public <T> void testRejectTypeVariable_withOwnerType() {
// Neither has subclass
assertHasTypeVariable(new From<Integer>().new To<String>().type());
@@ -1793,7 +1794,7 @@ public class TypeTokenTest extends TestCase {
abstract <T2 extends CharSequence & Iterable<T2>> void acceptT2(T2 t2);
- static void verifyConsitentRawType() {
+ static void verifyConsistentRawType() {
for (Method method : RawTypeConsistencyTester.class.getDeclaredMethods()) {
assertEquals(
method.getReturnType(), TypeToken.of(method.getGenericReturnType()).getRawType());
@@ -1807,7 +1808,7 @@ public class TypeTokenTest extends TestCase {
}
public void testRawTypes() {
- RawTypeConsistencyTester.verifyConsitentRawType();
+ RawTypeConsistencyTester.verifyConsistentRawType();
assertEquals(Object.class, TypeToken.of(Types.subtypeOf(Object.class)).getRawType());
assertEquals(
CharSequence.class, TypeToken.of(Types.subtypeOf(CharSequence.class)).getRawType());
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
index 991cada29..8e94f174f 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
@@ -34,6 +34,7 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Base class for tests for emulated {@link AbstractFuture} that allow subclasses to swap in a
@@ -443,7 +444,8 @@ abstract class AbstractAbstractFutureTest extends TestCase {
verifyTimedGetOnPendingFuture(future);
}
- private static void assertSuccessful(AbstractFuture<Integer> future, Integer expectedResult)
+ private static void assertSuccessful(
+ AbstractFuture<Integer> future, @Nullable Integer expectedResult)
throws InterruptedException, TimeoutException, ExecutionException {
assertDone(future);
assertThat(future.isCancelled()).isFalse();
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
index dc020fb20..89d92c8c4 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
@@ -16,6 +16,8 @@
package com.google.common.util.concurrent;
+import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;
+import static com.google.common.base.StandardSystemProperty.OS_NAME;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
@@ -23,6 +25,7 @@ import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
+import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
import java.util.ArrayList;
import java.util.Arrays;
@@ -46,6 +49,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link AbstractFuture}.
@@ -293,6 +297,13 @@ public class AbstractFutureTest extends TestCase {
@SuppressWarnings({"DeprecatedThreadMethods", "ThreadPriorityCheck"})
@AndroidIncompatible // Thread.suspend
public void testToString_delayedTimeout() throws Exception {
+ Integer javaVersion = Ints.tryParse(JAVA_SPECIFICATION_VERSION.value());
+ // Parsing to an integer might fail because Java 8 returns "1.8" instead of "8."
+ // We can continue if it's 1.8, and we can continue if it's an integer in [9, 20).
+ if (javaVersion != null && javaVersion >= 20) {
+ // TODO(b/261217224): Make this test work under newer JDKs.
+ return;
+ }
TimedWaiterThread thread =
new TimedWaiterThread(new AbstractFuture<Object>() {}, 2, TimeUnit.SECONDS);
thread.start();
@@ -426,6 +437,9 @@ public class AbstractFutureTest extends TestCase {
*/
public void testFutureBash() {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Running very slowly on Windows CI.
+ }
final CyclicBarrier barrier =
new CyclicBarrier(
6 // for the setter threads
@@ -435,10 +449,10 @@ public class AbstractFutureTest extends TestCase {
final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicInteger numSuccessfulSetCalls = new AtomicInteger();
- Callable<Void> completeSuccessfullyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> completeSuccessfullyRunnable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().set("set")) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -446,12 +460,12 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> completeExceptionallyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> completeExceptionallyRunnable =
+ new Callable<@Nullable Void>() {
Exception failureCause = new Exception("setException");
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setException(failureCause)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -459,10 +473,10 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> cancelRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> cancelRunnable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().cancel(true)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -470,12 +484,12 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> setFutureCompleteSuccessfullyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCompleteSuccessfullyRunnable =
+ new Callable<@Nullable Void>() {
ListenableFuture<String> future = Futures.immediateFuture("setFuture");
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -483,13 +497,13 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> setFutureCompleteExceptionallyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCompleteExceptionallyRunnable =
+ new Callable<@Nullable Void>() {
ListenableFuture<String> future =
Futures.immediateFailedFuture(new Exception("setFuture"));
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -497,12 +511,12 @@ public class AbstractFutureTest extends TestCase {
return null;
}
};
- Callable<Void> setFutureCancelRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCancelRunnable =
+ new Callable<@Nullable Void>() {
ListenableFuture<String> future = Futures.immediateCancelledFuture();
@Override
- public Void call() {
+ public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
@@ -559,15 +573,15 @@ public class AbstractFutureTest extends TestCase {
allTasks.add(setFutureCancelRunnable);
for (int k = 0; k < 50; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
- // get usecase and another task that adds it as a listener to the future to exercise both
+ // get use case and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener =
k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
allTasks.add(Executors.callable(listener));
allTasks.add(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
currentFuture.get().addListener(listener, executor);
return null;
}
@@ -607,6 +621,9 @@ public class AbstractFutureTest extends TestCase {
// setFuture and cancel() interact in more complicated ways than the other setters.
public void testSetFutureCancelBash() {
+ if (isWindows()) {
+ return; // TODO: b/136041958 - Running very slowly on Windows CI.
+ }
final int size = 50;
final CyclicBarrier barrier =
new CyclicBarrier(
@@ -683,7 +700,7 @@ public class AbstractFutureTest extends TestCase {
allTasks.add(setFutureCompleteSuccessfullyRunnable);
for (int k = 0; k < size; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
- // get usecase and another task that adds it as a listener to the future to exercise both
+ // get use case and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener =
k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
@@ -751,21 +768,21 @@ public class AbstractFutureTest extends TestCase {
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicBoolean setFutureSuccess = new AtomicBoolean();
final AtomicBoolean cancellationSuccess = new AtomicBoolean();
- Callable<Void> cancelRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> cancelRunnable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
cancellationSuccess.set(currentFuture.get().cancel(true));
awaitUnchecked(barrier);
return null;
}
};
- Callable<Void> setFutureCompleteSuccessfullyRunnable =
- new Callable<Void>() {
+ Callable<@Nullable Void> setFutureCompleteSuccessfullyRunnable =
+ new Callable<@Nullable Void>() {
final ListenableFuture<String> future = Futures.immediateFuture("hello");
@Override
- public Void call() {
+ public @Nullable Void call() {
setFutureSuccess.set(currentFuture.get().setFuture(future));
awaitUnchecked(barrier);
return null;
@@ -1200,13 +1217,10 @@ public class AbstractFutureTest extends TestCase {
throws InterruptedException {
try {
String got = future.get();
- fail("Expected exception but got " + got);
+ throw new AssertionError("Expected exception but got " + got);
} catch (ExecutionException e) {
return e;
}
-
- // unreachable, but compiler doesn't know that fail() always throws
- return null;
}
private static final class WaiterThread extends Thread {
@@ -1318,4 +1332,8 @@ public class AbstractFutureTest extends TestCase {
interruptTaskWasCalled = true;
}
}
+
+ private static boolean isWindows() {
+ return OS_NAME.value().startsWith("Windows");
+ }
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
index 2df5a4f3a..0444c31be 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
@@ -33,65 +33,6 @@ import junit.framework.TestCase;
* @author Ben Yu
*/
public class AbstractIdleServiceTest extends TestCase {
-
- // Functional tests using real thread. We only verify publicly visible state.
- // Interaction assertions are done by the single-threaded unit tests.
- public static class FunctionalTest extends TestCase {
-
- private static class DefaultService extends AbstractIdleService {
- @Override
- protected void startUp() throws Exception {}
-
- @Override
- protected void shutDown() throws Exception {}
- }
-
- public void testServiceStartStop() throws Exception {
- AbstractIdleService service = new DefaultService();
- service.startAsync().awaitRunning();
- assertEquals(Service.State.RUNNING, service.state());
- service.stopAsync().awaitTerminated();
- assertEquals(Service.State.TERMINATED, service.state());
- }
-
- public void testStart_failed() throws Exception {
- final Exception exception = new Exception("deliberate");
- AbstractIdleService service =
- new DefaultService() {
- @Override
- protected void startUp() throws Exception {
- throw exception;
- }
- };
- try {
- service.startAsync().awaitRunning();
- fail();
- } catch (RuntimeException e) {
- assertThat(e).hasCauseThat().isSameInstanceAs(exception);
- }
- assertEquals(Service.State.FAILED, service.state());
- }
-
- public void testStop_failed() throws Exception {
- final Exception exception = new Exception("deliberate");
- AbstractIdleService service =
- new DefaultService() {
- @Override
- protected void shutDown() throws Exception {
- throw exception;
- }
- };
- service.startAsync().awaitRunning();
- try {
- service.stopAsync().awaitTerminated();
- fail();
- } catch (RuntimeException e) {
- assertThat(e).hasCauseThat().isSameInstanceAs(exception);
- }
- assertEquals(Service.State.FAILED, service.state());
- }
- }
-
public void testStart() {
TestService service = new TestService();
assertEquals(0, service.startUpCalled);
@@ -236,4 +177,60 @@ public class AbstractIdleServiceTest extends TestCase {
return directExecutor();
}
}
+
+ // Functional tests using real thread. We only verify publicly visible state.
+ // Interaction assertions are done by the single-threaded unit tests.
+
+ private static class DefaultService extends AbstractIdleService {
+ @Override
+ protected void startUp() throws Exception {}
+
+ @Override
+ protected void shutDown() throws Exception {}
+ }
+
+ public void testFunctionalServiceStartStop() {
+ AbstractIdleService service = new DefaultService();
+ service.startAsync().awaitRunning();
+ assertEquals(Service.State.RUNNING, service.state());
+ service.stopAsync().awaitTerminated();
+ assertEquals(Service.State.TERMINATED, service.state());
+ }
+
+ public void testFunctionalStart_failed() {
+ final Exception exception = new Exception("deliberate");
+ AbstractIdleService service =
+ new DefaultService() {
+ @Override
+ protected void startUp() throws Exception {
+ throw exception;
+ }
+ };
+ try {
+ service.startAsync().awaitRunning();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasCauseThat().isSameInstanceAs(exception);
+ }
+ assertEquals(Service.State.FAILED, service.state());
+ }
+
+ public void testFunctionalStop_failed() {
+ final Exception exception = new Exception("deliberate");
+ AbstractIdleService service =
+ new DefaultService() {
+ @Override
+ protected void shutDown() throws Exception {
+ throw exception;
+ }
+ };
+ service.startAsync().awaitRunning();
+ try {
+ service.stopAsync().awaitTerminated();
+ fail();
+ } catch (RuntimeException e) {
+ assertThat(e).hasCauseThat().isSameInstanceAs(exception);
+ }
+ assertEquals(Service.State.FAILED, service.state());
+ }
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
index a05a83869..f7266b274 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
@@ -43,6 +43,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit test for {@link AbstractScheduledService}.
@@ -52,7 +53,7 @@ import junit.framework.TestCase;
public class AbstractScheduledServiceTest extends TestCase {
volatile Scheduler configuration = newFixedDelaySchedule(0, 10, MILLISECONDS);
- volatile ScheduledFuture<?> future = null;
+ volatile @Nullable ScheduledFuture<?> future = null;
volatile boolean atFixedRateCalled = false;
volatile boolean withFixedDelayCalled = false;
@@ -313,9 +314,9 @@ public class AbstractScheduledServiceTest extends TestCase {
AtomicInteger numberOfTimesRunCalled = new AtomicInteger(0);
AtomicInteger numberOfTimesExecutorCalled = new AtomicInteger(0);
AtomicInteger numberOfTimesSchedulerCalled = new AtomicInteger(0);
- volatile Exception runException = null;
- volatile Exception startUpException = null;
- volatile Exception shutDownException = null;
+ volatile @Nullable Exception runException = null;
+ volatile @Nullable Exception startUpException = null;
+ volatile @Nullable Exception shutDownException = null;
@Override
protected void runOneIteration() throws Exception {
@@ -364,317 +365,317 @@ public class AbstractScheduledServiceTest extends TestCase {
}
}
- public static class SchedulerTest extends TestCase {
- // These constants are arbitrary and just used to make sure that the correct method is called
- // with the correct parameters.
- private static final int INITIAL_DELAY = 10;
- private static final int DELAY = 20;
- private static final TimeUnit UNIT = MILLISECONDS;
+ // Tests for Scheduler:
- // Unique runnable object used for comparison.
- final Runnable testRunnable =
- new Runnable() {
- @Override
- public void run() {}
- };
- boolean called = false;
-
- private void assertSingleCallWithCorrectParameters(
- Runnable command, long initialDelay, long delay, TimeUnit unit) {
- assertFalse(called); // only called once.
- called = true;
- assertEquals(INITIAL_DELAY, initialDelay);
- assertEquals(DELAY, delay);
- assertEquals(UNIT, unit);
- assertEquals(testRunnable, command);
- }
+ // These constants are arbitrary and just used to make sure that the correct method is called
+ // with the correct parameters.
+ private static final int INITIAL_DELAY = 10;
+ private static final int DELAY = 20;
+ private static final TimeUnit UNIT = MILLISECONDS;
- public void testFixedRateSchedule() {
- Scheduler schedule = Scheduler.newFixedRateSchedule(INITIAL_DELAY, DELAY, UNIT);
- Cancellable unused =
- schedule.schedule(
- null,
- new ScheduledThreadPoolExecutor(1) {
- @Override
- public ScheduledFuture<?> scheduleAtFixedRate(
- Runnable command, long initialDelay, long period, TimeUnit unit) {
- assertSingleCallWithCorrectParameters(command, initialDelay, period, unit);
- return new ThrowingScheduledFuture<>();
- }
- },
- testRunnable);
- assertTrue(called);
- }
-
- public void testFixedDelaySchedule() {
- Scheduler schedule = newFixedDelaySchedule(INITIAL_DELAY, DELAY, UNIT);
- Cancellable unused =
- schedule.schedule(
- null,
- new ScheduledThreadPoolExecutor(10) {
- @Override
- public ScheduledFuture<?> scheduleWithFixedDelay(
- Runnable command, long initialDelay, long delay, TimeUnit unit) {
- assertSingleCallWithCorrectParameters(command, initialDelay, delay, unit);
- return new ThrowingScheduledFuture<>();
- }
- },
- testRunnable);
- assertTrue(called);
- }
+ // Unique runnable object used for comparison.
+ final Runnable testRunnable =
+ new Runnable() {
+ @Override
+ public void run() {}
+ };
+ boolean called = false;
+
+ private void assertSingleCallWithCorrectParameters(
+ Runnable command, long initialDelay, long delay, TimeUnit unit) {
+ assertFalse(called); // only called once.
+ called = true;
+ assertEquals(INITIAL_DELAY, initialDelay);
+ assertEquals(DELAY, delay);
+ assertEquals(UNIT, unit);
+ assertEquals(testRunnable, command);
+ }
- private static final class ThrowingScheduledFuture<V> extends ForwardingFuture<V>
- implements ScheduledFuture<V> {
- @Override
- protected Future<V> delegate() {
- throw new UnsupportedOperationException("test should not care about this");
- }
+ public void testFixedRateSchedule() {
+ Scheduler schedule = Scheduler.newFixedRateSchedule(INITIAL_DELAY, DELAY, UNIT);
+ Cancellable unused =
+ schedule.schedule(
+ null,
+ new ScheduledThreadPoolExecutor(1) {
+ @Override
+ public ScheduledFuture<?> scheduleAtFixedRate(
+ Runnable command, long initialDelay, long period, TimeUnit unit) {
+ assertSingleCallWithCorrectParameters(command, initialDelay, period, unit);
+ return new ThrowingScheduledFuture<>();
+ }
+ },
+ testRunnable);
+ assertTrue(called);
+ }
- @Override
- public long getDelay(TimeUnit unit) {
- throw new UnsupportedOperationException("test should not care about this");
- }
+ public void testFixedDelaySchedule() {
+ Scheduler schedule = newFixedDelaySchedule(INITIAL_DELAY, DELAY, UNIT);
+ Cancellable unused =
+ schedule.schedule(
+ null,
+ new ScheduledThreadPoolExecutor(10) {
+ @Override
+ public ScheduledFuture<?> scheduleWithFixedDelay(
+ Runnable command, long initialDelay, long delay, TimeUnit unit) {
+ assertSingleCallWithCorrectParameters(command, initialDelay, delay, unit);
+ return new ThrowingScheduledFuture<>();
+ }
+ },
+ testRunnable);
+ assertTrue(called);
+ }
- @Override
- public int compareTo(Delayed other) {
- throw new UnsupportedOperationException("test should not care about this");
- }
+ private static final class ThrowingScheduledFuture<V> extends ForwardingFuture<V>
+ implements ScheduledFuture<V> {
+ @Override
+ protected Future<V> delegate() {
+ throw new UnsupportedOperationException("test should not care about this");
}
- public void testFixedDelayScheduleFarFuturePotentiallyOverflowingScheduleIsNeverReached()
- throws Exception {
- TestAbstractScheduledCustomService service =
- new TestAbstractScheduledCustomService() {
- @Override
- protected Scheduler scheduler() {
- return newFixedDelaySchedule(Long.MAX_VALUE, Long.MAX_VALUE, SECONDS);
- }
- };
- service.startAsync().awaitRunning();
- try {
- service.firstBarrier.await(5, SECONDS);
- fail();
- } catch (TimeoutException expected) {
- }
- assertEquals(0, service.numIterations.get());
- service.stopAsync();
- service.awaitTerminated();
+ @Override
+ public long getDelay(TimeUnit unit) {
+ throw new UnsupportedOperationException("test should not care about this");
}
- public void testCustomSchedulerFarFuturePotentiallyOverflowingScheduleIsNeverReached()
- throws Exception {
- TestAbstractScheduledCustomService service =
- new TestAbstractScheduledCustomService() {
- @Override
- protected Scheduler scheduler() {
- return new AbstractScheduledService.CustomScheduler() {
- @Override
- protected Schedule getNextSchedule() throws Exception {
- return new Schedule(Long.MAX_VALUE, SECONDS);
- }
- };
- }
- };
- service.startAsync().awaitRunning();
- try {
- service.firstBarrier.await(5, SECONDS);
- fail();
- } catch (TimeoutException expected) {
- }
- assertEquals(0, service.numIterations.get());
- service.stopAsync();
- service.awaitTerminated();
+ @Override
+ public int compareTo(Delayed other) {
+ throw new UnsupportedOperationException("test should not care about this");
}
+ }
- private static class TestCustomScheduler extends AbstractScheduledService.CustomScheduler {
- public AtomicInteger scheduleCounter = new AtomicInteger(0);
-
- @Override
- protected Schedule getNextSchedule() throws Exception {
- scheduleCounter.incrementAndGet();
- return new Schedule(0, SECONDS);
- }
+ public void testFixedDelayScheduleFarFuturePotentiallyOverflowingScheduleIsNeverReached()
+ throws Exception {
+ TestAbstractScheduledCustomService service =
+ new TestAbstractScheduledCustomService() {
+ @Override
+ protected Scheduler scheduler() {
+ return newFixedDelaySchedule(Long.MAX_VALUE, Long.MAX_VALUE, SECONDS);
+ }
+ };
+ service.startAsync().awaitRunning();
+ try {
+ service.firstBarrier.await(5, SECONDS);
+ fail();
+ } catch (TimeoutException expected) {
}
+ assertEquals(0, service.numIterations.get());
+ service.stopAsync();
+ service.awaitTerminated();
+ }
- public void testCustomSchedule_startStop() throws Exception {
- final CyclicBarrier firstBarrier = new CyclicBarrier(2);
- final CyclicBarrier secondBarrier = new CyclicBarrier(2);
- final AtomicBoolean shouldWait = new AtomicBoolean(true);
- Runnable task =
- new Runnable() {
- @Override
- public void run() {
- try {
- if (shouldWait.get()) {
- firstBarrier.await();
- secondBarrier.await();
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
+ public void testCustomSchedulerFarFuturePotentiallyOverflowingScheduleIsNeverReached()
+ throws Exception {
+ TestAbstractScheduledCustomService service =
+ new TestAbstractScheduledCustomService() {
+ @Override
+ protected Scheduler scheduler() {
+ return new AbstractScheduledService.CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ return new Schedule(Long.MAX_VALUE, SECONDS);
}
- }
- };
- TestCustomScheduler scheduler = new TestCustomScheduler();
- Cancellable future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
- firstBarrier.await();
- assertEquals(1, scheduler.scheduleCounter.get());
- secondBarrier.await();
- firstBarrier.await();
- assertEquals(2, scheduler.scheduleCounter.get());
- shouldWait.set(false);
- secondBarrier.await();
- future.cancel(false);
+ };
+ }
+ };
+ service.startAsync().awaitRunning();
+ try {
+ service.firstBarrier.await(5, SECONDS);
+ fail();
+ } catch (TimeoutException expected) {
}
+ assertEquals(0, service.numIterations.get());
+ service.stopAsync();
+ service.awaitTerminated();
+ }
- public void testCustomSchedulerServiceStop() throws Exception {
- TestAbstractScheduledCustomService service = new TestAbstractScheduledCustomService();
- service.startAsync().awaitRunning();
- service.firstBarrier.await();
- assertEquals(1, service.numIterations.get());
- service.stopAsync();
- service.secondBarrier.await();
- service.awaitTerminated();
- // Sleep for a while just to ensure that our task wasn't called again.
- Thread.sleep(UNIT.toMillis(3 * DELAY));
- assertEquals(1, service.numIterations.get());
- }
+ private static class TestCustomScheduler extends AbstractScheduledService.CustomScheduler {
+ public AtomicInteger scheduleCounter = new AtomicInteger(0);
- public void testCustomScheduler_deadlock() throws InterruptedException, BrokenBarrierException {
- final CyclicBarrier inGetNextSchedule = new CyclicBarrier(2);
- // This will flakily deadlock, so run it multiple times to increase the flake likelihood
- for (int i = 0; i < 1000; i++) {
- Service service =
- new AbstractScheduledService() {
- @Override
- protected void runOneIteration() {}
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ scheduleCounter.incrementAndGet();
+ return new Schedule(0, SECONDS);
+ }
+ }
- @Override
- protected Scheduler scheduler() {
- return new CustomScheduler() {
- @Override
- protected Schedule getNextSchedule() throws Exception {
- if (state() != State.STARTING) {
- inGetNextSchedule.await();
- Thread.yield();
- throw new RuntimeException("boom");
- }
- return new Schedule(0, NANOSECONDS);
- }
- };
+ public void testCustomSchedule_startStop() throws Exception {
+ final CyclicBarrier firstBarrier = new CyclicBarrier(2);
+ final CyclicBarrier secondBarrier = new CyclicBarrier(2);
+ final AtomicBoolean shouldWait = new AtomicBoolean(true);
+ Runnable task =
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if (shouldWait.get()) {
+ firstBarrier.await();
+ secondBarrier.await();
}
- };
- service.startAsync().awaitRunning();
- inGetNextSchedule.await();
- service.stopAsync();
- }
- }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ TestCustomScheduler scheduler = new TestCustomScheduler();
+ Cancellable future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
+ firstBarrier.await();
+ assertEquals(1, scheduler.scheduleCounter.get());
+ secondBarrier.await();
+ firstBarrier.await();
+ assertEquals(2, scheduler.scheduleCounter.get());
+ shouldWait.set(false);
+ secondBarrier.await();
+ future.cancel(false);
+ }
+
+ public void testCustomSchedulerServiceStop() throws Exception {
+ TestAbstractScheduledCustomService service = new TestAbstractScheduledCustomService();
+ service.startAsync().awaitRunning();
+ service.firstBarrier.await();
+ assertEquals(1, service.numIterations.get());
+ service.stopAsync();
+ service.secondBarrier.await();
+ service.awaitTerminated();
+ // Sleep for a while just to ensure that our task wasn't called again.
+ Thread.sleep(UNIT.toMillis(3 * DELAY));
+ assertEquals(1, service.numIterations.get());
+ }
+
+ public void testCustomScheduler_deadlock() throws InterruptedException, BrokenBarrierException {
+ final CyclicBarrier inGetNextSchedule = new CyclicBarrier(2);
+ // This will flakily deadlock, so run it multiple times to increase the flake likelihood
+ for (int i = 0; i < 1000; i++) {
+ Service service =
+ new AbstractScheduledService() {
+ @Override
+ protected void runOneIteration() {}
- public void testBig() throws Exception {
- TestAbstractScheduledCustomService service =
- new TestAbstractScheduledCustomService() {
@Override
protected Scheduler scheduler() {
- return new AbstractScheduledService.CustomScheduler() {
+ return new CustomScheduler() {
@Override
protected Schedule getNextSchedule() throws Exception {
- // Explicitly yield to increase the probability of a pathological scheduling.
- Thread.yield();
- return new Schedule(0, SECONDS);
+ if (state() != State.STARTING) {
+ inGetNextSchedule.await();
+ Thread.yield();
+ throw new RuntimeException("boom");
+ }
+ return new Schedule(0, NANOSECONDS);
}
};
}
};
- service.useBarriers = false;
service.startAsync().awaitRunning();
- Thread.sleep(50);
- service.useBarriers = true;
- service.firstBarrier.await();
- int numIterations = service.numIterations.get();
+ inGetNextSchedule.await();
service.stopAsync();
- service.secondBarrier.await();
- service.awaitTerminated();
- assertEquals(numIterations, service.numIterations.get());
}
+ }
- private static class TestAbstractScheduledCustomService extends AbstractScheduledService {
- final AtomicInteger numIterations = new AtomicInteger(0);
- volatile boolean useBarriers = true;
- final CyclicBarrier firstBarrier = new CyclicBarrier(2);
- final CyclicBarrier secondBarrier = new CyclicBarrier(2);
-
- @Override
- protected void runOneIteration() throws Exception {
- numIterations.incrementAndGet();
- if (useBarriers) {
- firstBarrier.await();
- secondBarrier.await();
- }
- }
-
- @Override
- protected ScheduledExecutorService executor() {
- // use a bunch of threads so that weird overlapping schedules are more likely to happen.
- return Executors.newScheduledThreadPool(10);
- }
-
- @Override
- protected Scheduler scheduler() {
- return new CustomScheduler() {
+ public void testBig() throws Exception {
+ TestAbstractScheduledCustomService service =
+ new TestAbstractScheduledCustomService() {
@Override
- protected Schedule getNextSchedule() throws Exception {
- return new Schedule(DELAY, UNIT);
+ protected Scheduler scheduler() {
+ return new AbstractScheduledService.CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ // Explicitly yield to increase the probability of a pathological scheduling.
+ Thread.yield();
+ return new Schedule(0, SECONDS);
+ }
+ };
}
};
+ service.useBarriers = false;
+ service.startAsync().awaitRunning();
+ Thread.sleep(50);
+ service.useBarriers = true;
+ service.firstBarrier.await();
+ int numIterations = service.numIterations.get();
+ service.stopAsync();
+ service.secondBarrier.await();
+ service.awaitTerminated();
+ assertEquals(numIterations, service.numIterations.get());
+ }
+
+ private static class TestAbstractScheduledCustomService extends AbstractScheduledService {
+ final AtomicInteger numIterations = new AtomicInteger(0);
+ volatile boolean useBarriers = true;
+ final CyclicBarrier firstBarrier = new CyclicBarrier(2);
+ final CyclicBarrier secondBarrier = new CyclicBarrier(2);
+
+ @Override
+ protected void runOneIteration() throws Exception {
+ numIterations.incrementAndGet();
+ if (useBarriers) {
+ firstBarrier.await();
+ secondBarrier.await();
}
}
- public void testCustomSchedulerFailure() throws Exception {
- TestFailingCustomScheduledService service = new TestFailingCustomScheduledService();
- service.startAsync().awaitRunning();
- for (int i = 1; i < 4; i++) {
- service.firstBarrier.await();
- assertEquals(i, service.numIterations.get());
- service.secondBarrier.await();
- }
- Thread.sleep(1000);
- try {
- service.stopAsync().awaitTerminated(100, SECONDS);
- fail();
- } catch (IllegalStateException e) {
- assertEquals(State.FAILED, service.state());
- }
+ @Override
+ protected ScheduledExecutorService executor() {
+ // use a bunch of threads so that weird overlapping schedules are more likely to happen.
+ return Executors.newScheduledThreadPool(10);
}
- private static class TestFailingCustomScheduledService extends AbstractScheduledService {
- final AtomicInteger numIterations = new AtomicInteger(0);
- final CyclicBarrier firstBarrier = new CyclicBarrier(2);
- final CyclicBarrier secondBarrier = new CyclicBarrier(2);
+ @Override
+ protected Scheduler scheduler() {
+ return new CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ return new Schedule(DELAY, UNIT);
+ }
+ };
+ }
+ }
- @Override
- protected void runOneIteration() throws Exception {
- numIterations.incrementAndGet();
- firstBarrier.await();
- secondBarrier.await();
- }
+ public void testCustomSchedulerFailure() throws Exception {
+ TestFailingCustomScheduledService service = new TestFailingCustomScheduledService();
+ service.startAsync().awaitRunning();
+ for (int i = 1; i < 4; i++) {
+ service.firstBarrier.await();
+ assertEquals(i, service.numIterations.get());
+ service.secondBarrier.await();
+ }
+ Thread.sleep(1000);
+ try {
+ service.stopAsync().awaitTerminated(100, SECONDS);
+ fail();
+ } catch (IllegalStateException e) {
+ assertEquals(State.FAILED, service.state());
+ }
+ }
- @Override
- protected ScheduledExecutorService executor() {
- // use a bunch of threads so that weird overlapping schedules are more likely to happen.
- return Executors.newScheduledThreadPool(10);
- }
+ private static class TestFailingCustomScheduledService extends AbstractScheduledService {
+ final AtomicInteger numIterations = new AtomicInteger(0);
+ final CyclicBarrier firstBarrier = new CyclicBarrier(2);
+ final CyclicBarrier secondBarrier = new CyclicBarrier(2);
- @Override
- protected Scheduler scheduler() {
- return new CustomScheduler() {
- @Override
- protected Schedule getNextSchedule() throws Exception {
- if (numIterations.get() > 2) {
- throw new IllegalStateException("Failed");
- }
- return new Schedule(DELAY, UNIT);
+ @Override
+ protected void runOneIteration() throws Exception {
+ numIterations.incrementAndGet();
+ firstBarrier.await();
+ secondBarrier.await();
+ }
+
+ @Override
+ protected ScheduledExecutorService executor() {
+ // use a bunch of threads so that weird overlapping schedules are more likely to happen.
+ return Executors.newScheduledThreadPool(10);
+ }
+
+ @Override
+ protected Scheduler scheduler() {
+ return new CustomScheduler() {
+ @Override
+ protected Schedule getNextSchedule() throws Exception {
+ if (numIterations.get() > 2) {
+ throw new IllegalStateException("Failed");
}
- };
- }
+ return new Schedule(DELAY, UNIT);
+ }
+ };
}
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java b/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java
index fec93946f..9ddcea9b7 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AggregateFutureStateFallbackAtomicHelperTest.java
@@ -40,9 +40,9 @@ import junit.framework.TestSuite;
* </ul>
*
* To force selection of our fallback strategies we load {@link AggregateFutureState} (and all of
- * {@code com.google.common.util.concurrent} in degenerate class loaders which make certain platform
- * classes unavailable. Then we construct a test suite so we can run the normal FuturesTest test
- * methods in these degenerate classloaders.
+ * {@code com.google.common.util.concurrent}) in degenerate class loaders which make certain
+ * platform classes unavailable. Then we construct a test suite so we can run the normal FuturesTest
+ * test methods in these degenerate classloaders.
*/
public class AggregateFutureStateFallbackAtomicHelperTest extends TestCase {
diff --git a/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java b/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java
index 5bc92dc20..b4766bc8c 100644
--- a/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/CallablesTest.java
@@ -26,6 +26,7 @@ import java.security.Permission;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Unit tests for {@link Callables}.
@@ -90,10 +91,10 @@ public class CallablesTest extends TestCase {
public void testRenaming() throws Exception {
String oldName = Thread.currentThread().getName();
final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
- Callable<Void> callable =
- new Callable<Void>() {
+ Callable<@Nullable Void> callable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
assertEquals(Thread.currentThread().getName(), newName.get());
return null;
}
@@ -107,10 +108,10 @@ public class CallablesTest extends TestCase {
String oldName = Thread.currentThread().getName();
final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
class MyException extends Exception {}
- Callable<Void> callable =
- new Callable<Void>() {
+ Callable<@Nullable Void> callable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
assertEquals(Thread.currentThread().getName(), newName.get());
throw new MyException();
}
@@ -141,10 +142,10 @@ public class CallablesTest extends TestCase {
try {
final String oldName = Thread.currentThread().getName();
Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
- Callable<Void> callable =
- new Callable<Void>() {
+ Callable<@Nullable Void> callable =
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
assertEquals(Thread.currentThread().getName(), oldName);
return null;
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java b/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
index 2b1dd2fa0..bf388b0ba 100644
--- a/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
@@ -16,6 +16,7 @@
package com.google.common.util.concurrent;
+import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Joiner;
import com.google.common.util.concurrent.CycleDetectingLockFactory.Policies;
@@ -26,8 +27,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import junit.framework.TestCase;
/**
@@ -543,16 +542,6 @@ public class CycleDetectingLockFactoryTest extends TestCase {
// "LockA -> LockB \b.*\b LockB -> LockC \b.*\b LockC -> LockA"
private void checkMessage(IllegalStateException exception, String... expectedLockCycle) {
String regex = Joiner.on("\\b.*\\b").join(expectedLockCycle);
- assertContainsRegex(regex, exception.getMessage());
- }
-
- // TODO(cpovirk): consider adding support for regex to Truth
- private static void assertContainsRegex(String expectedRegex, String actual) {
- Pattern pattern = Pattern.compile(expectedRegex);
- Matcher matcher = pattern.matcher(actual);
- if (!matcher.find()) {
- String actualDesc = (actual == null) ? "null" : ('<' + actual + '>');
- fail("expected to contain regex:<" + expectedRegex + "> but was:" + actualDesc);
- }
+ assertThat(exception).hasMessageThat().containsMatch(regex);
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java b/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java
index 068287c19..1dafb3b0b 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ExecutionSequencerTest.java
@@ -37,6 +37,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Tests for {@link ExecutionSequencer} */
public class ExecutionSequencerTest extends TestCase {
@@ -44,7 +45,7 @@ public class ExecutionSequencerTest extends TestCase {
ExecutorService executor;
private ExecutionSequencer serializer;
- private SettableFuture<Void> firstFuture;
+ private SettableFuture<@Nullable Void> firstFuture;
private TestCallable firstCallable;
@Override
@@ -76,7 +77,8 @@ public class ExecutionSequencerTest extends TestCase {
@SuppressWarnings({"unused", "nullness"})
Future<?> possiblyIgnoredError = serializer.submitAsync(firstCallable, directExecutor());
TestCallable secondCallable = new TestCallable(Futures.<Void>immediateFuture(null));
- ListenableFuture<Void> secondFuture = serializer.submitAsync(secondCallable, directExecutor());
+ ListenableFuture<@Nullable Void> secondFuture =
+ serializer.submitAsync(secondCallable, directExecutor());
TestCallable thirdCallable = new TestCallable(Futures.<Void>immediateFuture(null));
@SuppressWarnings({"unused", "nullness"})
Future<?> possiblyIgnoredError1 = serializer.submitAsync(thirdCallable, directExecutor());
@@ -90,7 +92,7 @@ public class ExecutionSequencerTest extends TestCase {
public void testCancellationMultipleThreads() throws Exception {
final BlockingCallable blockingCallable = new BlockingCallable();
- ListenableFuture<Void> unused = serializer.submit(blockingCallable, executor);
+ ListenableFuture<@Nullable Void> unused = serializer.submit(blockingCallable, executor);
ListenableFuture<Boolean> future2 =
serializer.submit(
new Callable<Boolean>() {
@@ -117,7 +119,7 @@ public class ExecutionSequencerTest extends TestCase {
public void testSecondTaskWaitsForFirstEvenIfCancelled() throws Exception {
final BlockingCallable blockingCallable = new BlockingCallable();
- ListenableFuture<Void> future1 = serializer.submit(blockingCallable, executor);
+ ListenableFuture<@Nullable Void> future1 = serializer.submit(blockingCallable, executor);
ListenableFuture<Boolean> future2 =
serializer.submit(
new Callable<Boolean>() {
@@ -153,12 +155,12 @@ public class ExecutionSequencerTest extends TestCase {
public void testCancellationWithReferencedObject() throws Exception {
Object toBeGCed = new Object();
WeakReference<Object> ref = new WeakReference<>(toBeGCed);
- final SettableFuture<Void> settableFuture = SettableFuture.create();
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
ListenableFuture<?> ignored =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -195,9 +197,9 @@ public class ExecutionSequencerTest extends TestCase {
final Future<?>[] thingToCancel = new Future<?>[1];
results.add(
serializer.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
thingToCancel[0].cancel(false);
return null;
}
@@ -223,13 +225,13 @@ public class ExecutionSequencerTest extends TestCase {
}
public void testAvoidsStackOverflow_manySubmitted() throws Exception {
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- ArrayList<ListenableFuture<Void>> results = new ArrayList<>(50_001);
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
+ ArrayList<ListenableFuture<@Nullable Void>> results = new ArrayList<>(50_001);
results.add(
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -242,12 +244,12 @@ public class ExecutionSequencerTest extends TestCase {
}
public void testAvoidsStackOverflow_manyCancelled() throws Exception {
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- ListenableFuture<Void> unused =
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
+ ListenableFuture<@Nullable Void> unused =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -270,12 +272,12 @@ public class ExecutionSequencerTest extends TestCase {
}
public void testAvoidsStackOverflow_alternatingCancelledAndSubmitted() throws Exception {
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- ListenableFuture<Void> unused =
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
+ ListenableFuture<@Nullable Void> unused =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -344,12 +346,12 @@ public class ExecutionSequencerTest extends TestCase {
},
service)
.get();
- final SettableFuture<Void> settableFuture = SettableFuture.create();
+ final SettableFuture<@Nullable Void> settableFuture = SettableFuture.create();
ListenableFuture<?> unused =
serializer.submitAsync(
- new AsyncCallable<Void>() {
+ new AsyncCallable<@Nullable Void>() {
@Override
- public ListenableFuture<Void> call() {
+ public ListenableFuture<@Nullable Void> call() {
return settableFuture;
}
},
@@ -359,9 +361,9 @@ public class ExecutionSequencerTest extends TestCase {
// after some number of iterations, switch threads
unused =
serializer.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
holder.count++;
return null;
}
@@ -383,9 +385,9 @@ public class ExecutionSequencerTest extends TestCase {
// Otherwise, schedule a task on directExecutor
unused =
serializer.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() {
+ public @Nullable Void call() {
holder.count++;
return null;
}
@@ -416,14 +418,14 @@ public class ExecutionSequencerTest extends TestCase {
assertThat(second.toString()).contains(secondCallable.future.toString());
}
- private static class BlockingCallable implements Callable<Void> {
+ private static class BlockingCallable implements Callable<@Nullable Void> {
private final CountDownLatch startLatch = new CountDownLatch(1);
private final CountDownLatch stopLatch = new CountDownLatch(1);
private volatile boolean running = false;
@Override
- public Void call() throws InterruptedException {
+ public @Nullable Void call() throws InterruptedException {
running = true;
startLatch.countDown();
stopLatch.await();
@@ -444,17 +446,17 @@ public class ExecutionSequencerTest extends TestCase {
}
}
- private static final class TestCallable implements AsyncCallable<Void> {
+ private static final class TestCallable implements AsyncCallable<@Nullable Void> {
- private final ListenableFuture<Void> future;
+ private final ListenableFuture<@Nullable Void> future;
private boolean called = false;
- private TestCallable(ListenableFuture<Void> future) {
+ private TestCallable(ListenableFuture<@Nullable Void> future) {
this.future = future;
}
@Override
- public ListenableFuture<Void> call() throws Exception {
+ public ListenableFuture<@Nullable Void> call() throws Exception {
called = true;
return future;
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
index 84b0426a6..ad391efdc 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
@@ -28,7 +28,7 @@ import java.lang.reflect.Method;
import java.util.Arrays;
/**
- * Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks.
+ * Tester for typical subclass of {@link ForwardingObject} by using Mockito.
*
* @author Ben Yu
*/
diff --git a/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java b/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java
index 22eba9bde..2efdebec5 100644
--- a/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java
@@ -21,19 +21,17 @@ import static com.google.common.util.concurrent.Futures.addCallback;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import com.google.common.annotations.GwtCompatible;
-import com.google.common.annotations.GwtIncompatible;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import junit.framework.TestCase;
import org.checkerframework.checker.nullness.qual.Nullable;
-import org.mockito.Mockito;
/**
* Test for {@link FutureCallback}.
*
* @author Anthony Zana
*/
-@GwtCompatible(emulated = true)
+@GwtCompatible
public class FutureCallbackTest extends TestCase {
public void testSameThreadSuccess() {
SettableFuture<String> f = SettableFuture.create();
@@ -89,38 +87,60 @@ public class FutureCallbackTest extends TestCase {
addCallback(f, callback, directExecutor());
}
- public void testRuntimeExeceptionFromGet() {
+ public void testRuntimeExceptionFromGet() {
RuntimeException e = new IllegalArgumentException("foo not found");
ListenableFuture<String> f = UncheckedThrowingFuture.throwingRuntimeException(e);
MockCallback callback = new MockCallback(e);
addCallback(f, callback, directExecutor());
}
- @GwtIncompatible // Mockito
public void testOnSuccessThrowsRuntimeException() throws Exception {
RuntimeException exception = new RuntimeException();
String result = "result";
SettableFuture<String> future = SettableFuture.create();
- @SuppressWarnings("unchecked") // Safe for a mock
- FutureCallback<String> callback = Mockito.mock(FutureCallback.class);
+ int[] successCalls = new int[1];
+ int[] failureCalls = new int[1];
+ FutureCallback<String> callback =
+ new FutureCallback<String>() {
+ @Override
+ public void onSuccess(String result) {
+ successCalls[0]++;
+ throw exception;
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ failureCalls[0]++;
+ }
+ };
addCallback(future, callback, directExecutor());
- Mockito.doThrow(exception).when(callback).onSuccess(result);
future.set(result);
assertEquals(result, future.get());
- Mockito.verify(callback).onSuccess(result);
- Mockito.verifyNoMoreInteractions(callback);
+ assertThat(successCalls[0]).isEqualTo(1);
+ assertThat(failureCalls[0]).isEqualTo(0);
}
- @GwtIncompatible // Mockito
public void testOnSuccessThrowsError() throws Exception {
class TestError extends Error {}
TestError error = new TestError();
String result = "result";
SettableFuture<String> future = SettableFuture.create();
- @SuppressWarnings("unchecked") // Safe for a mock
- FutureCallback<String> callback = Mockito.mock(FutureCallback.class);
+ int[] successCalls = new int[1];
+ int[] failureCalls = new int[1];
+ FutureCallback<String> callback =
+ new FutureCallback<String>() {
+ @Override
+ public void onSuccess(String result) {
+ successCalls[0]++;
+ throw error;
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ failureCalls[0]++;
+ }
+ };
addCallback(future, callback, directExecutor());
- Mockito.doThrow(error).when(callback).onSuccess(result);
try {
future.set(result);
fail("Should have thrown");
@@ -128,8 +148,8 @@ public class FutureCallbackTest extends TestCase {
assertSame(error, e);
}
assertEquals(result, future.get());
- Mockito.verify(callback).onSuccess(result);
- Mockito.verifyNoMoreInteractions(callback);
+ assertThat(successCalls[0]).isEqualTo(1);
+ assertThat(failureCalls[0]).isEqualTo(0);
}
public void testWildcardFuture() {
diff --git a/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java b/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
index 3fe2347a8..c46801b99 100644
--- a/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
@@ -141,7 +141,7 @@ public class FuturesTest extends TestCase {
}
public void testImmediateVoidFuture() throws Exception {
- ListenableFuture<Void> voidFuture = immediateVoidFuture();
+ ListenableFuture<@Nullable Void> voidFuture = immediateVoidFuture();
assertThat(getDone(voidFuture)).isNull();
assertThat(getDoneFromTimeoutOverload(voidFuture)).isNull();
@@ -388,7 +388,7 @@ public class FuturesTest extends TestCase {
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
- throw new AssertionFailedError("Unexpeted call to apply.");
+ throw new AssertionFailedError("Unexpected call to apply.");
}
};
assertTrue(transformAsync(input, function, directExecutor()).cancel(false));
@@ -402,7 +402,7 @@ public class FuturesTest extends TestCase {
new AsyncFunction<Foo, Bar>() {
@Override
public ListenableFuture<Bar> apply(Foo unused) {
- throw new AssertionFailedError("Unexpeted call to apply.");
+ throw new AssertionFailedError("Unexpected call to apply.");
}
};
assertTrue(transformAsync(input, function, directExecutor()).cancel(true));
@@ -1662,7 +1662,7 @@ public class FuturesTest extends TestCase {
}
private static <I, O> AsyncFunction<I, O> constantAsyncFunction(
- final ListenableFuture<O> output) {
+ final @Nullable ListenableFuture<O> output) {
return new AsyncFunction<I, O>() {
@Override
public ListenableFuture<O> apply(I input) {
@@ -1978,7 +1978,7 @@ public class FuturesTest extends TestCase {
pendingRunnables.add(runnable);
}
};
- ListenableFuture<Void> future = submit(runnable, executor);
+ ListenableFuture<@Nullable Void> future = submit(runnable, executor);
assertThat(future.isDone()).isFalse();
assertThat(executedRunnables).isEmpty();
assertThat(pendingRunnables).hasSize(1);
@@ -1997,7 +1997,7 @@ public class FuturesTest extends TestCase {
throw exception;
}
};
- ListenableFuture<Void> future = submit(runnable, directExecutor());
+ ListenableFuture<@Nullable Void> future = submit(runnable, directExecutor());
try {
getDone(future);
fail();
@@ -2110,7 +2110,8 @@ public class FuturesTest extends TestCase {
assertFalse(callableCalled.get());
}
- private static <T> AsyncCallable<T> constantAsyncCallable(final ListenableFuture<T> returnValue) {
+ private static <T> AsyncCallable<T> constantAsyncCallable(
+ final @Nullable ListenableFuture<T> returnValue) {
return new AsyncCallable<T>() {
@Override
public ListenableFuture<T> call() {
diff --git a/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java b/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
index 8b5caebf5..9e33d1f57 100644
--- a/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
@@ -35,6 +35,7 @@ import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Generated tests for {@link Monitor}.
@@ -460,7 +461,11 @@ public class GeneratedMonitorTest extends TestCase {
private final CountDownLatch callCompletedLatch;
private GeneratedMonitorTest(
- Method method, Scenario scenario, boolean fair, Timeout timeout, Outcome expectedOutcome) {
+ Method method,
+ Scenario scenario,
+ boolean fair,
+ @Nullable Timeout timeout,
+ Outcome expectedOutcome) {
super(nameFor(method, scenario, fair, timeout, expectedOutcome));
this.method = method;
this.scenario = scenario;
@@ -494,7 +499,7 @@ public class GeneratedMonitorTest extends TestCase {
runChosenTest();
}
};
- final FutureTask<Void> task = new FutureTask<>(runChosenTest, null);
+ final FutureTask<@Nullable Void> task = new FutureTask<>(runChosenTest, null);
startThread(
new Runnable() {
@Override
diff --git a/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java b/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java
index fcfe744e0..6d1591354 100644
--- a/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java
@@ -17,13 +17,13 @@ package com.google.common.util.concurrent;
import static com.google.common.truth.Truth.assertThat;
-import java.lang.reflect.Method;
+import com.google.common.util.concurrent.InterruptibleTask.Blocker;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.AbstractOwnableSynchronizer;
import java.util.concurrent.locks.LockSupport;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
public final class InterruptibleTaskTest extends TestCase {
@@ -31,10 +31,10 @@ public final class InterruptibleTaskTest extends TestCase {
// transition to DONE
public void testInterruptThrows() throws Exception {
final CountDownLatch isInterruptibleRegistered = new CountDownLatch(1);
- InterruptibleTask<Void> task =
- new InterruptibleTask<Void>() {
+ InterruptibleTask<@Nullable Void> task =
+ new InterruptibleTask<@Nullable Void>() {
@Override
- Void runInterruptibly() throws Exception {
+ @Nullable Void runInterruptibly() throws Exception {
BrokenChannel bc = new BrokenChannel();
bc.doBegin();
isInterruptibleRegistered.countDown();
@@ -53,7 +53,7 @@ public final class InterruptibleTaskTest extends TestCase {
}
@Override
- void afterRanInterruptiblySuccess(Void result) {}
+ void afterRanInterruptiblySuccess(@Nullable Void result) {}
@Override
void afterRanInterruptiblyFailure(Throwable error) {}
@@ -101,10 +101,10 @@ public final class InterruptibleTaskTest extends TestCase {
public void testInterruptIsSlow() throws Exception {
final CountDownLatch isInterruptibleRegistered = new CountDownLatch(1);
final SlowChannel slowChannel = new SlowChannel();
- final InterruptibleTask<Void> task =
- new InterruptibleTask<Void>() {
+ final InterruptibleTask<@Nullable Void> task =
+ new InterruptibleTask<@Nullable Void>() {
@Override
- Void runInterruptibly() throws Exception {
+ @Nullable Void runInterruptibly() throws Exception {
slowChannel.doBegin();
isInterruptibleRegistered.countDown();
try {
@@ -127,7 +127,7 @@ public final class InterruptibleTaskTest extends TestCase {
}
@Override
- void afterRanInterruptiblySuccess(Void result) {}
+ void afterRanInterruptiblySuccess(@Nullable Void result) {}
@Override
void afterRanInterruptiblyFailure(Throwable error) {}
@@ -152,12 +152,8 @@ public final class InterruptibleTaskTest extends TestCase {
// waiting for the slow interrupting thread to complete Thread.interrupt
awaitBlockedOnInstanceOf(runner, InterruptibleTask.Blocker.class);
- Object blocker = LockSupport.getBlocker(runner);
- assertThat(blocker).isInstanceOf(AbstractOwnableSynchronizer.class);
- Method getExclusiveOwnerThread =
- AbstractOwnableSynchronizer.class.getDeclaredMethod("getExclusiveOwnerThread");
- getExclusiveOwnerThread.setAccessible(true);
- Thread owner = (Thread) getExclusiveOwnerThread.invoke(blocker);
+ Blocker blocker = (Blocker) LockSupport.getBlocker(runner);
+ Thread owner = blocker.getOwner();
assertThat(owner).isSameInstanceAs(interrupter);
slowChannel.exitClose.countDown(); // release the interrupter
diff --git a/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java
new file mode 100644
index 000000000..5c12696ab
--- /dev/null
+++ b/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 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.util.concurrent;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Future;
+import junit.framework.TestCase;
+
+/** Test for {@link ListenableFuture}. */
+public class ListenableFutureTest extends TestCase {
+ public void testNoNewApis() throws Exception {
+ assertWithMessage(
+ "Do not add new methods to ListenableFuture. Its API needs to continue to match the"
+ + " version we released in a separate artifact com.google.guava:listenablefuture.")
+ .that(ListenableFuture.class.getDeclaredMethods())
+ .asList()
+ .containsExactly(
+ ListenableFuture.class.getMethod("addListener", Runnable.class, Executor.class));
+ assertWithMessage(
+ "Do not add new supertypes to ListenableFuture. Its API needs to continue to match the"
+ + " version we released in a separate artifact com.google.guava:listenablefuture.")
+ .that(ListenableFuture.class.getInterfaces())
+ .asList()
+ .containsExactly(Future.class);
+ }
+}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ListeningExecutorServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/ListeningExecutorServiceTest.java
new file mode 100644
index 000000000..1b1bcb679
--- /dev/null
+++ b/guava-tests/test/com/google/common/util/concurrent/ListeningExecutorServiceTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2020 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.util.concurrent;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
+import static com.google.common.util.concurrent.Futures.immediateFuture;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import junit.framework.TestCase;
+
+public final class ListeningExecutorServiceTest extends TestCase {
+
+ private Collection<? extends Callable<?>> recordedTasks;
+ private long recordedTimeout;
+ private TimeUnit recordedTimeUnit;
+
+ private final ListeningExecutorService executorService = new FakeExecutorService();
+
+ public void testInvokeAny() throws Exception {
+ Set<Callable<String>> tasks = Collections.singleton(() -> "invokeAny");
+
+ String result = executorService.invokeAny(tasks, Duration.ofSeconds(7));
+
+ assertThat(result).isEqualTo("invokeAny");
+ assertThat(recordedTasks).isSameInstanceAs(tasks);
+ assertThat(recordedTimeUnit).isEqualTo(NANOSECONDS);
+ assertThat(Duration.ofNanos(recordedTimeout)).isEqualTo(Duration.ofSeconds(7));
+ }
+
+ public void testInvokeAll() throws Exception {
+ Set<Callable<String>> tasks = Collections.singleton(() -> "invokeAll");
+
+ List<Future<String>> result = executorService.invokeAll(tasks, Duration.ofDays(365));
+
+ assertThat(result).hasSize(1);
+ assertThat(Futures.getDone(result.get(0))).isEqualTo("invokeAll");
+ assertThat(recordedTasks).isSameInstanceAs(tasks);
+ assertThat(recordedTimeUnit).isEqualTo(NANOSECONDS);
+ assertThat(Duration.ofNanos(recordedTimeout)).isEqualTo(Duration.ofDays(365));
+ }
+
+ public void testAwaitTermination() throws Exception {
+ boolean result = executorService.awaitTermination(Duration.ofMinutes(144));
+
+ assertThat(result).isTrue();
+ assertThat(recordedTimeUnit).isEqualTo(NANOSECONDS);
+ assertThat(Duration.ofNanos(recordedTimeout)).isEqualTo(Duration.ofMinutes(144));
+ }
+
+ private class FakeExecutorService extends AbstractListeningExecutorService {
+ @Override
+ public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ recordedTasks = tasks;
+ recordedTimeout = timeout;
+ recordedTimeUnit = unit;
+ try {
+ return tasks.iterator().next().call();
+ } catch (Exception e) {
+ throw new ExecutionException(e);
+ }
+ }
+
+ @Override
+ public <T> List<Future<T>> invokeAll(
+ Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
+ throws InterruptedException {
+ recordedTasks = tasks;
+ recordedTimeout = timeout;
+ recordedTimeUnit = unit;
+ try {
+ return Collections.singletonList(immediateFuture(tasks.iterator().next().call()));
+ } catch (Exception e) {
+ return Collections.singletonList(immediateFailedFuture(e));
+ }
+ }
+
+ @Override
+ public boolean awaitTermination(long timeout, TimeUnit unit) {
+ recordedTimeout = timeout;
+ recordedTimeUnit = unit;
+ return true;
+ }
+
+ @Override
+ public void execute(Runnable runnable) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void shutdown() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public List<Runnable> shutdownNow() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean isShutdown() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean isTerminated() {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java b/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
index aac61735e..dab6d92f9 100644
--- a/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
@@ -72,6 +72,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import org.checkerframework.checker.nullness.qual.Nullable;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -185,9 +186,9 @@ public class MoreExecutorsTest extends JSR166TestCase {
try {
Future<?> future =
executor.submit(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
// WAIT #1
barrier.await(1, TimeUnit.SECONDS);
diff --git a/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java b/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
index a6c08999b..bdd9e7885 100644
--- a/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
@@ -35,7 +35,6 @@ import java.util.Locale;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
-import org.easymock.EasyMock;
import org.mockito.Mockito;
/**
@@ -564,24 +563,9 @@ public class RateLimiterTest extends TestCase {
}
}
- /*
- * Note: Mockito appears to lose its ability to Mock doGetRate as of Android 21. If we start
- * testing with that version or newer, we'll need to suppress this test (or see if Mockito can be
- * changed to support this).
- */
+ @AndroidIncompatible // Mockito loses its ability to mock doGetRate as of Android 21
public void testMockingMockito() throws Exception {
RateLimiter mock = Mockito.mock(RateLimiter.class);
- doTestMocking(mock);
- }
-
- @AndroidIncompatible // EasyMock Class Extension doesn't appear to work on Android.
- public void testMockingEasyMock() throws Exception {
- RateLimiter mock = EasyMock.createNiceMock(RateLimiter.class);
- EasyMock.replay(mock);
- doTestMocking(mock);
- }
-
- private static void doTestMocking(RateLimiter mock) throws Exception {
for (Method method : RateLimiter.class.getMethods()) {
if (!isStatic(method.getModifiers())
&& !NOT_WORKING_ON_MOCKS.contains(method.getName())
diff --git a/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java b/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
index 80e7ab2e1..cbb6c1c82 100644
--- a/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
@@ -310,7 +310,7 @@ public class SequentialExecutorTest extends TestCase {
executor.execute(errorTask);
service.execute(barrierTask); // submit directly to the service
// the barrier task runs after the error task so we know that the error has been observed by
- // SequentialExecutor by the time the barrier is satified
+ // SequentialExecutor by the time the barrier is satisfied
barrier.await(1, TimeUnit.SECONDS);
executor.execute(barrierTask);
// timeout means the second task wasn't even tried
diff --git a/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java b/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java
index 9f89fb1b3..9f22a10cd 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java
@@ -504,7 +504,7 @@ public class ServiceManagerTest extends TestCase {
}
};
stoppingThread.start();
- // this should be super fast since the only non stopped service is a NoOpService
+ // this should be super fast since the only non-stopped service is a NoOpService
stoppingThread.join(1000);
assertFalse("stopAsync has deadlocked!.", stoppingThread.isAlive());
failLeave.countDown(); // release the background thread
@@ -623,7 +623,7 @@ public class ServiceManagerTest extends TestCase {
}
/**
- * This service will shutdown very quickly after stopAsync is called and uses a background thread
+ * This service will shut down very quickly after stopAsync is called and uses a background thread
* so that we know that the stopping() listeners will execute on a different thread than the
* terminated() listeners.
*/
diff --git a/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java b/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
index 35406864d..37ef84f66 100644
--- a/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
@@ -278,7 +278,7 @@ public class SimpleTimeLimiterTest extends TestCase {
finished = true;
return input;
} catch (InterruptedException e) {
- return null;
+ throw new AssertionError();
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/TestThread.java b/guava-tests/test/com/google/common/util/concurrent/TestThread.java
index 6d5609399..ef3b27410 100644
--- a/guava-tests/test/com/google/common/util/concurrent/TestThread.java
+++ b/guava-tests/test/com/google/common/util/concurrent/TestThread.java
@@ -58,7 +58,7 @@ public final class TestThread<L> extends Thread implements TearDown {
private final SynchronousQueue<Request> requestQueue = new SynchronousQueue<>();
private final SynchronousQueue<Response> responseQueue = new SynchronousQueue<>();
- private Throwable uncaughtThrowable = null;
+ private @Nullable Throwable uncaughtThrowable = null;
public TestThread(L lockLikeObject, String threadName) {
super(threadName);
@@ -275,7 +275,7 @@ public final class TestThread<L> extends Thread implements TearDown {
final Object result;
final Throwable throwable;
- Response(String methodName, Object result, Throwable throwable) {
+ Response(String methodName, @Nullable Object result, @Nullable Throwable throwable) {
this.methodName = methodName;
this.result = result;
this.throwable = throwable;
diff --git a/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java b/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java
index e735ae02a..e58d3eef0 100644
--- a/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/TrustedListenableFutureTaskTest.java
@@ -33,6 +33,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;
+import org.checkerframework.checker.nullness.qual.Nullable;
/** Test case for {@link TrustedListenableFutureTask}. */
@GwtCompatible(emulated = true)
@@ -172,11 +173,11 @@ public class TrustedListenableFutureTaskTest extends TestCase {
public void testToString() throws Exception {
final CountDownLatch enterLatch = new CountDownLatch(1);
final CountDownLatch exitLatch = new CountDownLatch(1);
- final TrustedListenableFutureTask<Void> task =
+ final TrustedListenableFutureTask<@Nullable Void> task =
TrustedListenableFutureTask.create(
- new Callable<Void>() {
+ new Callable<@Nullable Void>() {
@Override
- public Void call() throws Exception {
+ public @Nullable Void call() throws Exception {
enterLatch.countDown();
new CountDownLatch(1).await(); // wait forever
return null;
@@ -205,7 +206,7 @@ public class TrustedListenableFutureTaskTest extends TestCase {
exitLatch.await();
}
- @GwtIncompatible // used only in GwtIncomaptible tests
+ @GwtIncompatible // used only in GwtIncompatible tests
private void awaitUnchecked(CyclicBarrier barrier) {
try {
barrier.await();
diff --git a/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java
index fdb2c54e6..5cbc7c2b7 100644
--- a/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java
@@ -188,7 +188,7 @@ public class WrappingExecutorServiceTest extends TestCase {
}
}
- // TODO: If this test can ever depend on EasyMock or the like, use it instead.
+ // TODO: If this test can ever depend on Mockito or the like, use it instead.
private static final class MockExecutor implements ExecutorService {
private String lastMethodCalled = "";
private long lastTimeoutInMillis = -1;
diff --git a/guava/module.json b/guava/module.json
new file mode 100644
index 000000000..9d78db10f
--- /dev/null
+++ b/guava/module.json
@@ -0,0 +1,295 @@
+{
+ "formatVersion": "1.1",
+ "component": {
+ "group": "${pom.groupId}",
+ "module": "${pom.artifactId}",
+ "version": "${pom.version}",
+ "attributes": {
+ "org.gradle.status": "${module.status}"
+ }
+ },
+ "createdBy": {
+ "maven": {
+ "version": "${maven.version}",
+ "buildId": "${maven.build.version}"
+ }
+ },
+ "variants": [
+ {
+ "name": "${variant.jvmEnvironmentVariantName}ApiElements",
+ "attributes": {
+ "org.gradle.category": "library",
+ "org.gradle.dependency.bundling": "external",
+ "org.gradle.jvm.version": "8",
+ "org.gradle.jvm.environment": "${variant.jvmEnvironment}",
+ "org.gradle.libraryelements": "jar",
+ "org.gradle.usage": "java-api"
+ },
+ "dependencies": [
+ {
+ "group": "com.google.guava",
+ "module": "guava-parent",
+ "version": {
+ "requires": "${pom.version}"
+ },
+ "attributes": {
+ "org.gradle.category": "platform"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "failureaccess",
+ "version": {
+ "requires": "1.0.1"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "listenablefuture",
+ "version": {
+ "requires": "9999.0-empty-to-avoid-conflict-with-guava"
+ }
+ },
+ {
+ "group": "com.google.code.findbugs",
+ "module": "jsr305"
+ },
+ {
+ "group": "org.checkerframework",
+ "module": "checker-qual"
+ },
+ {
+ "group": "com.google.errorprone",
+ "module": "error_prone_annotations"
+ },
+ {
+ "group": "com.google.j2objc",
+ "module": "j2objc-annotations"
+ }
+ ],
+ "files": [
+ {
+ "name": "${project.build.finalName}.jar",
+ "url": "${project.build.finalName}.jar"
+ }
+ ],
+ "capabilities": [
+ {
+ "group": "com.google.guava",
+ "name": "guava",
+ "version": "${pom.version}"
+ },
+ {
+ "group": "com.google.collections",
+ "name": "google-collections",
+ "version": "${pom.version}"
+ }
+ ]
+ },
+ {
+ "name": "${variant.jvmEnvironmentVariantName}RuntimeElements",
+ "attributes": {
+ "org.gradle.category": "library",
+ "org.gradle.dependency.bundling": "external",
+ "org.gradle.jvm.version": "8",
+ "org.gradle.jvm.environment": "${variant.jvmEnvironment}",
+ "org.gradle.libraryelements": "jar",
+ "org.gradle.usage": "java-runtime"
+ },
+ "dependencies": [
+ {
+ "group": "com.google.guava",
+ "module": "guava-parent",
+ "version": {
+ "requires": "${pom.version}"
+ },
+ "attributes": {
+ "org.gradle.category": "platform"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "failureaccess",
+ "version": {
+ "requires": "1.0.1"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "listenablefuture",
+ "version": {
+ "requires": "9999.0-empty-to-avoid-conflict-with-guava"
+ }
+ },
+ {
+ "group": "com.google.code.findbugs",
+ "module": "jsr305"
+ },
+ {
+ "group": "org.checkerframework",
+ "module": "checker-qual"
+ },
+ {
+ "group": "com.google.errorprone",
+ "module": "error_prone_annotations"
+ }
+ ],
+ "files": [
+ {
+ "name": "${project.build.finalName}.jar",
+ "url": "${project.build.finalName}.jar"
+ }
+ ],
+ "capabilities": [
+ {
+ "group": "com.google.guava",
+ "name": "guava",
+ "version": "${pom.version}"
+ },
+ {
+ "group": "com.google.collections",
+ "name": "google-collections",
+ "version": "${pom.version}"
+ }
+ ]
+ },
+ {
+ "name": "${otherVariant.jvmEnvironmentVariantName}ApiElements",
+ "attributes": {
+ "org.gradle.category": "library",
+ "org.gradle.dependency.bundling": "external",
+ "org.gradle.jvm.version": "8",
+ "org.gradle.jvm.environment": "${otherVariant.jvmEnvironment}",
+ "org.gradle.libraryelements": "jar",
+ "org.gradle.usage": "java-api"
+ },
+ "dependencies": [
+ {
+ "group": "com.google.guava",
+ "module": "guava-parent",
+ "version": {
+ "requires": "${otherVariant.version}"
+ },
+ "attributes": {
+ "org.gradle.category": "platform"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "failureaccess",
+ "version": {
+ "requires": "1.0.1"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "listenablefuture",
+ "version": {
+ "requires": "9999.0-empty-to-avoid-conflict-with-guava"
+ }
+ },
+ {
+ "group": "com.google.code.findbugs",
+ "module": "jsr305"
+ },
+ {
+ "group": "org.checkerframework",
+ "module": "checker-qual"
+ },
+ {
+ "group": "com.google.errorprone",
+ "module": "error_prone_annotations"
+ },
+ {
+ "group": "com.google.j2objc",
+ "module": "j2objc-annotations"
+ }
+ ],
+ "files": [
+ {
+ "name": "${pom.artifactId}-${otherVariant.version}.jar",
+ "url": "../${otherVariant.version}/${pom.artifactId}-${otherVariant.version}.jar"
+ }
+ ],
+ "capabilities": [
+ {
+ "group": "com.google.guava",
+ "name": "guava",
+ "version": "${pom.version}"
+ },
+ {
+ "group": "com.google.collections",
+ "name": "google-collections",
+ "version": "${pom.version}"
+ }
+ ]
+ },
+ {
+ "name": "${otherVariant.jvmEnvironmentVariantName}RuntimeElements",
+ "attributes": {
+ "org.gradle.category": "library",
+ "org.gradle.dependency.bundling": "external",
+ "org.gradle.jvm.version": "8",
+ "org.gradle.jvm.environment": "${otherVariant.jvmEnvironment}",
+ "org.gradle.libraryelements": "jar",
+ "org.gradle.usage": "java-runtime"
+ },
+ "dependencies": [
+ {
+ "group": "com.google.guava",
+ "module": "guava-parent",
+ "version": {
+ "requires": "${otherVariant.version}"
+ },
+ "attributes": {
+ "org.gradle.category": "platform"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "failureaccess",
+ "version": {
+ "requires": "1.0.1"
+ }
+ },
+ {
+ "group": "com.google.guava",
+ "module": "listenablefuture",
+ "version": {
+ "requires": "9999.0-empty-to-avoid-conflict-with-guava"
+ }
+ },
+ {
+ "group": "com.google.code.findbugs",
+ "module": "jsr305"
+ },
+ {
+ "group": "org.checkerframework",
+ "module": "checker-qual"
+ },
+ {
+ "group": "com.google.errorprone",
+ "module": "error_prone_annotations"
+ }
+ ],
+ "files": [
+ {
+ "name": "${pom.artifactId}-${otherVariant.version}.jar",
+ "url": "../${otherVariant.version}/${pom.artifactId}-${otherVariant.version}.jar"
+ }
+ ],
+ "capabilities": [
+ {
+ "group": "com.google.guava",
+ "name": "guava",
+ "version": "${pom.version}"
+ },
+ {
+ "group": "com.google.collections",
+ "name": "google-collections",
+ "version": "${pom.version}"
+ }
+ ]
+ }
+ ]
+}
diff --git a/guava/pom.xml b/guava/pom.xml
index 81a2005c7..d87aa8952 100644
--- a/guava/pom.xml
+++ b/guava/pom.xml
@@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <!-- do_not_remove: published-with-gradle-metadata -->
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
</parent>
<artifactId>guava</artifactId>
<packaging>bundle</packaging>
@@ -47,6 +48,16 @@
<!-- TODO(cpovirk): want this only for dependency plugin but seems not to work there? Maven runs without failure, but the resulting Javadoc is missing the hoped-for inherited text -->
</dependencies>
<build>
+ <resources>
+ <resource>
+ <directory>..</directory>
+ <includes>
+ <include>LICENSE</include> <!-- copied from the parent pom because I couldn't figure out a way to make combine.children="append" work -->
+ <include>proguard/*</include>
+ </includes>
+ <targetPath>META-INF</targetPath>
+ </resource>
+ </resources>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
@@ -62,7 +73,7 @@
<extensions>true</extensions>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <version>2.5.0</version>
+ <version>5.1.8</version>
<executions>
<execution>
<id>bundle-manifest</id>
@@ -187,6 +198,7 @@
<links>
<link>https://errorprone.info/api/latest/</link>
</links>
+ <overview>../overview.html</overview>
</configuration>
<executions>
<execution>
@@ -199,6 +211,50 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>gradle-module-metadata</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>target/publish</outputDirectory>
+ <resources>
+ <resource>
+ <directory>.</directory>
+ <includes>
+ <include>module.json</include>
+ </includes>
+ <filtering>true</filtering>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-gradle-module-metadata</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>target/publish/module.json</file>
+ <type>module</type>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
<profiles>
diff --git a/guava/src/com/google/common/annotations/J2ktIncompatible.java b/guava/src/com/google/common/annotations/J2ktIncompatible.java
new file mode 100644
index 000000000..59511632e
--- /dev/null
+++ b/guava/src/com/google/common/annotations/J2ktIncompatible.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2009 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.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * The presence of this annotation on an API indicates that the method may <em>not</em> be used with
+ * J2kt.
+ *
+ * @since 32.0.0
+ */
+@Retention(RetentionPolicy.CLASS)
+@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
+@GwtCompatible
+public @interface J2ktIncompatible {}
diff --git a/guava/src/com/google/common/annotations/VisibleForTesting.java b/guava/src/com/google/common/annotations/VisibleForTesting.java
index e767afcdd..24b4db5bd 100644
--- a/guava/src/com/google/common/annotations/VisibleForTesting.java
+++ b/guava/src/com/google/common/annotations/VisibleForTesting.java
@@ -22,8 +22,8 @@ package com.google.common.annotations;
* bad design, and it does not prevent anyone from using the declaration---and experience has shown
* that they will. If the method breaks the encapsulation of its class, then its internal
* representation will be hard to change. Instead, use <a
- * href="http://errorprone.info/bugpattern/RestrictedApiChecker">RestrictedApiChecker</a>, which
- * enforces fine-grained visibility policies.
+ * href="http://errorprone.info/bugpattern/RestrictedApi">RestrictedApiChecker</a>, which enforces
+ * fine-grained visibility policies.
*
* @author Johannes Henkel
*/
diff --git a/guava/src/com/google/common/annotations/package-info.java b/guava/src/com/google/common/annotations/package-info.java
index 9ad041ffe..3cff985b7 100644
--- a/guava/src/com/google/common/annotations/package-info.java
+++ b/guava/src/com/google/common/annotations/package-info.java
@@ -13,7 +13,7 @@
*/
/**
- * Common annotation types. This package is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Annotation types. This package is a part of the open-source <a
+ * href="https://github.com/google/guava">Guava</a> library.
*/
package com.google.common.annotations;
diff --git a/guava/src/com/google/common/base/CaseFormat.java b/guava/src/com/google/common/base/CaseFormat.java
index 7b393ebd7..93fa7e4b7 100644
--- a/guava/src/com/google/common/base/CaseFormat.java
+++ b/guava/src/com/google/common/base/CaseFormat.java
@@ -151,7 +151,8 @@ public enum CaseFormat {
}
/**
- * Returns a {@code Converter} that converts strings from this format to {@code targetFormat}.
+ * Returns a serializable {@code Converter} that converts strings from this format to {@code
+ * targetFormat}.
*
* @since 16.0
*/
diff --git a/guava/src/com/google/common/base/CharMatcher.java b/guava/src/com/google/common/base/CharMatcher.java
index 253bc6a22..4ed1e9a90 100644
--- a/guava/src/com/google/common/base/CharMatcher.java
+++ b/guava/src/com/google/common/base/CharMatcher.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkPositionIndex;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.Arrays;
import java.util.BitSet;
@@ -412,6 +413,7 @@ public abstract class CharMatcher implements Predicate<Character> {
* constructs an eight-kilobyte bit array and queries that. In many situations this produces a
* matcher which is faster to query than the original.
*/
+ @J2ktIncompatible
@GwtIncompatible // SmallCharMatcher
CharMatcher precomputedInternal() {
final BitSet table = new BitSet();
@@ -442,6 +444,7 @@ public abstract class CharMatcher implements Predicate<Character> {
/**
* Helper method for {@link #precomputedInternal} that doesn't test if the negation is cheaper.
*/
+ @J2ktIncompatible
@GwtIncompatible // SmallCharMatcher
private static CharMatcher precomputedPositive(
int totalCharacters, BitSet table, String description) {
@@ -461,6 +464,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
}
+ @J2ktIncompatible
@GwtIncompatible // SmallCharMatcher
private static boolean isSmall(int totalCharacters, int tableLength) {
return totalCharacters <= SmallCharMatcher.MAX_SIZE
@@ -469,6 +473,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
/** Sets bits in {@code table} matched by this matcher. */
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
void setBits(BitSet table) {
for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) {
@@ -979,6 +984,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
/** Fast matcher using a {@link BitSet} table of matching characters. */
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
private static final class BitSetMatcher extends NamedFastMatcher {
@@ -1233,6 +1239,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return TABLE.charAt((MULTIPLIER * c) >>> SHIFT) == c;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1519,6 +1526,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return sequence.length() - original.countIn(sequence);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1555,6 +1563,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return first.matches(c) && second.matches(c);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1583,6 +1592,7 @@ public abstract class CharMatcher implements Predicate<Character> {
second = checkNotNull(b);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1637,6 +1647,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return isNot(match);
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1673,6 +1684,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return other.matches(match) ? any() : this;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1711,6 +1723,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return c == match1 || c == match2;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
@@ -1740,6 +1753,7 @@ public abstract class CharMatcher implements Predicate<Character> {
}
@Override
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
void setBits(BitSet table) {
for (char c : chars) {
@@ -1775,6 +1789,7 @@ public abstract class CharMatcher implements Predicate<Character> {
return startInclusive <= c && c <= endInclusive;
}
+ @J2ktIncompatible
@GwtIncompatible // used only from other GwtIncompatible code
@Override
void setBits(BitSet table) {
diff --git a/guava/src/com/google/common/base/Charsets.java b/guava/src/com/google/common/base/Charsets.java
index 7aebea826..538e604f2 100644
--- a/guava/src/com/google/common/base/Charsets.java
+++ b/guava/src/com/google/common/base/Charsets.java
@@ -16,6 +16,7 @@ package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.charset.Charset;
/**
@@ -42,6 +43,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#US_ASCII} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset US_ASCII = Charset.forName("US-ASCII");
@@ -70,6 +72,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#UTF_16BE} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
@@ -80,6 +83,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#UTF_16LE} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
@@ -91,6 +95,7 @@ public final class Charsets {
* java.nio.charset.StandardCharsets#UTF_16} instead.
*
*/
+ @J2ktIncompatible
@GwtIncompatible // Charset not supported by GWT
public static final Charset UTF_16 = Charset.forName("UTF-16");
diff --git a/guava/src/com/google/common/base/Converter.java b/guava/src/com/google/common/base/Converter.java
index 422480d16..63f4394f4 100644
--- a/guava/src/com/google/common/base/Converter.java
+++ b/guava/src/com/google/common/base/Converter.java
@@ -18,7 +18,6 @@ import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.ForOverride;
import com.google.errorprone.annotations.InlineMe;
@@ -191,7 +190,6 @@ public abstract class Converter<A, B> implements Function<A, B> {
*
* @return the converted value; is null <i>if and only if</i> {@code a} is null
*/
- @CanIgnoreReturnValue
@CheckForNull
public final B convert(@CheckForNull A a) {
return correctedDoForward(a);
@@ -261,7 +259,6 @@ public abstract class Converter<A, B> implements Function<A, B> {
* a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding
* element.
*/
- @CanIgnoreReturnValue
/*
* Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A,
* B>`, convertAll could accept and return iterables with nullable element types. In both cases,
@@ -286,8 +283,6 @@ public abstract class Converter<A, B> implements Function<A, B> {
}
@Override
- @SuppressWarnings("nullness") // See code comments on convertAll and Converter.apply.
- @CheckForNull
public B next() {
return convert(fromIterator.next());
}
@@ -461,41 +456,26 @@ public abstract class Converter<A, B> implements Function<A, B> {
*/
@Deprecated
@Override
- @CanIgnoreReturnValue
- /*
- * Even though we implement `Function<A, B>` instead of `Function<@Nullable A, @Nullable B>` (as
- * discussed in a code comment at the top of the class), we declare our override of Function.apply
- * to accept and return null. This requires a suppression, but it's safe:
- *
- * - Callers who use Converter as a Function<A, B> will neither pass null nor have it returned to
- * them. (Or, if they're not using nullness checking, they might be able to pass null and thus
- * have null returned to them. But our signature isn't making their existing nullness type error
- * any worse.)
- * - In the relatively unlikely event that anyone calls Converter.apply directly, that caller is
- * allowed to pass null but is also forced to deal with a potentially null return.
- * - Perhaps more important than actual *callers* of this method are various tools that look at
- * bytecode. Notably, NullPointerTester expects a method to throw NPE when passed null unless it
- * is annotated in a way that identifies its parameter type as potentially including null. (And
- * this method does not throw NPE -- nor do we want to enact a dangerous change to make it begin
- * doing so.) We can even imagine tools that rewrite bytecode to insert null checks before and
- * after calling methods with allegedly non-nullable parameters[*]. If we didn't annotate the
- * parameter and return type here, then anyone who used such a tool (and managed to pass null to
- * this method, presumably because that user doesn't run a normal nullness checker) could see
- * NullPointerException.
- *
- * [*] Granted, such tools could conceivably be smart enough to recognize that the apply() method
- * on a a Function<Foo, Bar> should never allow null inputs and never produce null outputs even if
- * this specific subclass claims otherwise. Such tools might still produce NPE for calls to this
- * method. And that is one reason that we should be nervous about "lying" by extending Function<A,
- * B> in the first place. But for now, we're giving it a try, since extending Function<@Nullable
- * A, @Nullable B> will cause issues *today*, whereas extending Function<A, B> causes problems in
- * various hypothetical futures. (Plus, a tool that were that smart would likely already introduce
- * problems with LegacyConverter.)
- */
- @SuppressWarnings("nullness")
- @CheckForNull
@InlineMe(replacement = "this.convert(a)")
- public final B apply(@CheckForNull A a) {
+ public final B apply(A a) {
+ /*
+ * Given that we declare this method as accepting and returning non-nullable values (because we
+ * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to
+ * perform runtime null checks on the input and output. (That would also make NullPointerTester
+ * happy!) However, since we didn't do that for many years, we're not about to start now.
+ * (Runtime checks could be particularly bad for users of LegacyConverter.)
+ *
+ * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like
+ * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to
+ * perform even a cast, much less a runtime check.
+ *
+ * All that said, don't forget that everyone should call converter.convert() instead of
+ * converter.apply(), anyway. If clients use only converter.convert(), then their nullness
+ * checkers are unlikely to ever look at the annotations on this declaration.
+ *
+ * Historical note: At one point, we'd declared this method as accepting and returning nullable
+ * values. For details on that, see earlier revisions of this file.
+ */
return convert(a);
}
diff --git a/guava/src/com/google/common/base/Defaults.java b/guava/src/com/google/common/base/Defaults.java
index 5d12343ed..089f4b572 100644
--- a/guava/src/com/google/common/base/Defaults.java
+++ b/guava/src/com/google/common/base/Defaults.java
@@ -17,6 +17,7 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
@@ -25,6 +26,7 @@ import javax.annotation.CheckForNull;
* @author Ben Yu
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Defaults {
diff --git a/guava/src/com/google/common/base/Enums.java b/guava/src/com/google/common/base/Enums.java
index 5c55b6594..d1749f016 100644
--- a/guava/src/com/google/common/base/Enums.java
+++ b/guava/src/com/google/common/base/Enums.java
@@ -16,8 +16,8 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
@@ -33,7 +33,8 @@ import javax.annotation.CheckForNull;
* @author Steve McKay
* @since 9.0
*/
-@GwtCompatible(emulated = true)
+@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class Enums {
@@ -48,7 +49,8 @@ public final class Enums {
*/
@GwtIncompatible // reflection
public static Field getField(Enum<?> enumValue) {
- Class<?> clazz = enumValue.getDeclaringClass();
+ Class<?>
+ clazz = enumValue.getDeclaringClass();
try {
return clazz.getDeclaredField(enumValue.name());
} catch (NoSuchFieldException impossible) {
@@ -98,17 +100,19 @@ public final class Enums {
}
/**
- * Returns a converter that converts between strings and {@code enum} values of type {@code
- * enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The converter
- * will throw an {@code IllegalArgumentException} if the argument is not the name of any enum
- * constant in the specified enum.
+ * Returns a serializable converter that converts between strings and {@code enum} values of type
+ * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The
+ * converter will throw an {@code IllegalArgumentException} if the argument is not the name of any
+ * enum constant in the specified enum.
*
* @since 16.0
*/
+ @GwtIncompatible
public static <T extends Enum<T>> Converter<String, T> stringConverter(Class<T> enumClass) {
return new StringConverter<>(enumClass);
}
+ @GwtIncompatible
private static final class StringConverter<T extends Enum<T>> extends Converter<String, T>
implements Serializable {
diff --git a/guava/src/com/google/common/base/Equivalence.java b/guava/src/com/google/common/base/Equivalence.java
index 4e2e89886..a2b8bb15b 100644
--- a/guava/src/com/google/common/base/Equivalence.java
+++ b/guava/src/com/google/common/base/Equivalence.java
@@ -21,6 +21,7 @@ import com.google.errorprone.annotations.ForOverride;
import java.io.Serializable;
import java.util.function.BiPredicate;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -162,46 +163,13 @@ public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullab
* Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a,
* b)}.
*
+ * <p>The returned object is serializable if both this {@code Equivalence} and {@code reference}
+ * are serializable (including when {@code reference} is null).
+ *
* @since 10.0
*/
public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) {
- /*
- * I'm pretty sure that this warning "makes sense" but doesn't indicate a real problem.
- *
- * Why it "makes sense": If we pass a `@Nullable Foo`, then we should also pass an
- * `Equivalence<? super @Nullable Foo>`. And there's no such thing because Equivalence doesn't
- * permit nullable type arguments.
- *
- * Why there's no real problem: Every Equivalence can handle null.
- *
- * We could work around this by giving Wrapper 2 type parameters. In the terms of this method,
- * that would be both the T parameter (from the class) and the S parameter (from this method).
- * However, such a change would be source-incompatible. (Plus, there's no reason for the S
- * parameter from the user's perspective, so it would be a wart.)
- *
- * We could probably also work around this by making Wrapper non-final and putting the
- * implementation into a subclass with those 2 type parameters. But we like `final`, if only to
- * deter users from using mocking frameworks to construct instances. (And could also complicate
- * serialization, which is discussed more in the next paragraph.)
- *
- * We could probably also work around this by having Wrapper accept an instance of a new
- * WrapperGuts class, which would then be the class that would declare the 2 type parameters.
- * But that would break deserialization of previously serialized Wrapper instances. And while we
- * specifically say not to rely on serialization across Guava versions, users sometimes do. So
- * we'd rather not break them without a good enough reason.
- *
- * (We could work around the serialization problem by writing custom serialization code. But
- * even that helps only the case of serializing with an old version and deserializing with a
- * new, not vice versa -- unless we introduce WrapperGuts and the logic to handle it today, wait
- * until "everyone" has picked up a version of Guava with that code, and *then* change to use
- * WrapperGuts.)
- *
- * Anyway, a suppression isn't really a big deal. But I have tried to do some due diligence on
- * avoiding it :)
- */
- @SuppressWarnings("nullness")
- Wrapper<S> w = new Wrapper<>(this, reference);
- return w;
+ return new Wrapper<>(this, reference);
}
/**
@@ -225,10 +193,19 @@ public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullab
* @since 10.0
*/
public static final class Wrapper<T extends @Nullable Object> implements Serializable {
- private final Equivalence<? super T> equivalence;
+ /*
+ * Equivalence's type argument is always non-nullable: Equivalence<Number>, never
+ * Equivalence<@Nullable Number>. That can still produce wrappers of various types --
+ * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just
+ * Equivalence<? super T> below, no type could satisfy both that bound and T's own
+ * bound. With this type, they have some overlap: in our example, Equivalence<Number>
+ * and Equivalence<Object>.
+ */
+ private final Equivalence<? super @NonNull T> equivalence;
+
@ParametricNullness private final T reference;
- private Wrapper(Equivalence<? super T> equivalence, @ParametricNullness T reference) {
+ private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) {
this.equivalence = checkNotNull(equivalence);
this.reference = reference;
}
@@ -292,6 +269,8 @@ public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullab
* <p>Note that this method performs a similar function for equivalences as {@link
* com.google.common.collect.Ordering#lexicographical} does for orderings.
*
+ * <p>The returned object is serializable if this object is serializable.
+ *
* @since 10.0
*/
@GwtCompatible(serializable = true)
diff --git a/guava/src/com/google/common/base/FinalizablePhantomReference.java b/guava/src/com/google/common/base/FinalizablePhantomReference.java
index 4f9399669..6f76b63f7 100644
--- a/guava/src/com/google/common/base/FinalizablePhantomReference.java
+++ b/guava/src/com/google/common/base/FinalizablePhantomReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import javax.annotation.CheckForNull;
@@ -29,6 +30,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class FinalizablePhantomReference<T> extends PhantomReference<T>
diff --git a/guava/src/com/google/common/base/FinalizableReference.java b/guava/src/com/google/common/base/FinalizableReference.java
index 73753c9b3..f538f9dc0 100644
--- a/guava/src/com/google/common/base/FinalizableReference.java
+++ b/guava/src/com/google/common/base/FinalizableReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
/**
@@ -25,6 +26,7 @@ import com.google.errorprone.annotations.DoNotMock;
* @since 2.0
*/
@DoNotMock("Use an instance of one of the Finalizable*Reference classes")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface FinalizableReference {
diff --git a/guava/src/com/google/common/base/FinalizableReferenceQueue.java b/guava/src/com/google/common/base/FinalizableReferenceQueue.java
index 7447b8051..7f1afbb39 100644
--- a/guava/src/com/google/common/base/FinalizableReferenceQueue.java
+++ b/guava/src/com/google/common/base/FinalizableReferenceQueue.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.FileNotFoundException;
@@ -88,6 +89,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class FinalizableReferenceQueue implements Closeable {
diff --git a/guava/src/com/google/common/base/FinalizableSoftReference.java b/guava/src/com/google/common/base/FinalizableSoftReference.java
index c0e9b6bae..f4b7c8005 100644
--- a/guava/src/com/google/common/base/FinalizableSoftReference.java
+++ b/guava/src/com/google/common/base/FinalizableSoftReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import javax.annotation.CheckForNull;
@@ -27,6 +28,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class FinalizableSoftReference<T> extends SoftReference<T>
diff --git a/guava/src/com/google/common/base/FinalizableWeakReference.java b/guava/src/com/google/common/base/FinalizableWeakReference.java
index 9cca92ed5..12c8dfbfc 100644
--- a/guava/src/com/google/common/base/FinalizableWeakReference.java
+++ b/guava/src/com/google/common/base/FinalizableWeakReference.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import javax.annotation.CheckForNull;
@@ -27,6 +28,7 @@ import javax.annotation.CheckForNull;
* @author Bob Lee
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class FinalizableWeakReference<T> extends WeakReference<T>
diff --git a/guava/src/com/google/common/base/Function.java b/guava/src/com/google/common/base/Function.java
index 45287b744..10c73283c 100644
--- a/guava/src/com/google/common/base/Function.java
+++ b/guava/src/com/google/common/base/Function.java
@@ -15,7 +15,6 @@
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -46,7 +45,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public interface Function<F extends @Nullable Object, T extends @Nullable Object>
extends java.util.function.Function<F, T> {
@Override
- @CanIgnoreReturnValue // TODO(kevinb): remove this
@ParametricNullness
T apply(@ParametricNullness F input);
diff --git a/guava/src/com/google/common/base/FunctionalEquivalence.java b/guava/src/com/google/common/base/FunctionalEquivalence.java
index 4383f4f36..1cd8c416d 100644
--- a/guava/src/com/google/common/base/FunctionalEquivalence.java
+++ b/guava/src/com/google/common/base/FunctionalEquivalence.java
@@ -16,7 +16,6 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
@@ -28,7 +27,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Bob Lee
* @since 10.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
final class FunctionalEquivalence<F, T> extends Equivalence<F> implements Serializable {
diff --git a/guava/src/com/google/common/base/Functions.java b/guava/src/com/google/common/base/Functions.java
index 78785047e..c0091ff7f 100644
--- a/guava/src/com/google/common/base/Functions.java
+++ b/guava/src/com/google/common/base/Functions.java
@@ -79,7 +79,12 @@ public final class Functions {
}
}
- /** Returns the identity function. */
+ /**
+ * Returns the identity function.
+ *
+ * <p><b>Discouraged:</b> Prefer using a lambda like {@code v -> v}, which is shorter and often
+ * more readable.
+ */
// implementation is "fully variant"; E has become a "pass-through" type
@SuppressWarnings("unchecked")
public static <E extends @Nullable Object> Function<E, E> identity() {
diff --git a/guava/src/com/google/common/base/Java8Compatibility.java b/guava/src/com/google/common/base/Java8Compatibility.java
index edc8b73bd..2dfbd6b1c 100644
--- a/guava/src/com/google/common/base/Java8Compatibility.java
+++ b/guava/src/com/google/common/base/Java8Compatibility.java
@@ -15,12 +15,14 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.Buffer;
/**
* Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
* https://github.com/google/guava/issues/3990
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
diff --git a/guava/src/com/google/common/base/JdkPattern.java b/guava/src/com/google/common/base/JdkPattern.java
index 4788398b7..a259d0061 100644
--- a/guava/src/com/google/common/base/JdkPattern.java
+++ b/guava/src/com/google/common/base/JdkPattern.java
@@ -15,12 +15,14 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** A regex pattern implementation which is backed by the {@link Pattern}. */
@ElementTypesAreNonnullByDefault
+@J2ktIncompatible
@GwtIncompatible
final class JdkPattern extends CommonPattern implements Serializable {
private final Pattern pattern;
diff --git a/guava/src/com/google/common/base/Joiner.java b/guava/src/com/google/common/base/Joiner.java
index 8b29f68f8..fe1b40a5e 100644
--- a/guava/src/com/google/common/base/Joiner.java
+++ b/guava/src/com/google/common/base/Joiner.java
@@ -17,7 +17,6 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -366,7 +365,6 @@ public class Joiner {
*
* @since 10.0
*/
- @Beta
@CanIgnoreReturnValue
public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)
throws IOException {
@@ -379,7 +377,6 @@ public class Joiner {
*
* @since 11.0
*/
- @Beta
@CanIgnoreReturnValue
public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)
throws IOException {
@@ -407,7 +404,6 @@ public class Joiner {
*
* @since 10.0
*/
- @Beta
@CanIgnoreReturnValue
public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {
return appendTo(builder, entries.iterator());
@@ -420,7 +416,6 @@ public class Joiner {
*
* @since 11.0
*/
- @Beta
@CanIgnoreReturnValue
public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {
try {
@@ -445,7 +440,6 @@ public class Joiner {
*
* @since 10.0
*/
- @Beta
public String join(Iterable<? extends Entry<?, ?>> entries) {
return join(entries.iterator());
}
@@ -456,7 +450,6 @@ public class Joiner {
*
* @since 11.0
*/
- @Beta
public String join(Iterator<? extends Entry<?, ?>> entries) {
return appendTo(new StringBuilder(), entries).toString();
}
diff --git a/guava/src/com/google/common/base/MoreObjects.java b/guava/src/com/google/common/base/MoreObjects.java
index 16e12bb50..f3826d96f 100644
--- a/guava/src/com/google/common/base/MoreObjects.java
+++ b/guava/src/com/google/common/base/MoreObjects.java
@@ -61,24 +61,7 @@ public final class MoreObjects {
* @throws NullPointerException if both {@code first} and {@code second} are null
* @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
*/
- /*
- * We annotate firstNonNull in a way that protects against NullPointerException at the cost of
- * forbidding some reasonable calls.
- *
- * The more permissive signature would be to accept (@CheckForNull T first, @CheckForNull T
- * second), since it's OK for `second` to be null as long as `first` is not also null. But we
- * expect for that flexibility to be useful relatively rarely: The more common use case is to
- * supply a clearly non-null default, like `firstNonNull(someString, "")`. And users who really
- * know that `first` is guaranteed non-null when `second` is null can write the logic out
- * longhand, including a requireNonNull call, which calls attention to the fact that the static
- * analyzer can't prove that the operation is safe.
- *
- * This matches the signature we currently have for requireNonNullElse in our own checker. (And
- * that in turn matches that method's signature under the Checker Framework.) As always, we could
- * consider the more flexible signature if we judge it worth the risks. If we do, we would likely
- * update both methods so that they continue to match.
- */
- public static <T> T firstNonNull(@CheckForNull T first, T second) {
+ public static <T> T firstNonNull(@CheckForNull T first, @CheckForNull T second) {
if (first != null) {
return first;
}
@@ -349,7 +332,7 @@ public final class MoreObjects {
}
private static boolean isEmpty(Object value) {
- // Put types estimated to be most frequent first.
+ // Put types estimated to be the most frequent first.
if (value instanceof CharSequence) {
return ((CharSequence) value).length() == 0;
} else if (value instanceof Collection) {
@@ -419,12 +402,14 @@ public final class MoreObjects {
return valueHolder;
}
+ @CanIgnoreReturnValue
private ToStringHelper addHolder(@CheckForNull Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
+ @CanIgnoreReturnValue
private ToStringHelper addHolder(String name, @CheckForNull Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
@@ -438,12 +423,14 @@ public final class MoreObjects {
return valueHolder;
}
+ @CanIgnoreReturnValue
private ToStringHelper addUnconditionalHolder(Object value) {
UnconditionalValueHolder valueHolder = addUnconditionalHolder();
valueHolder.value = value;
return this;
}
+ @CanIgnoreReturnValue
private ToStringHelper addUnconditionalHolder(String name, Object value) {
UnconditionalValueHolder valueHolder = addUnconditionalHolder();
valueHolder.value = value;
diff --git a/guava/src/com/google/common/base/Optional.java b/guava/src/com/google/common/base/Optional.java
index b47705e82..b30cb51e9 100644
--- a/guava/src/com/google/common/base/Optional.java
+++ b/guava/src/com/google/common/base/Optional.java
@@ -16,7 +16,6 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.io.Serializable;
@@ -52,6 +51,9 @@ import javax.annotation.CheckForNull;
* <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct
* from other programming environments, though it may bear some similarities.
*
+ * <p>An instance of this class is serializable if its reference is absent or is a serializable
+ * object.
+ *
* <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional}
* class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot
* share a common supertype). <i>All</i> known differences are listed either here or with the
@@ -239,7 +241,6 @@ public abstract class Optional<T> implements Serializable {
* @throws NullPointerException if this optional's value is absent and the supplier returns {@code
* null}
*/
- @Beta
public abstract T or(Supplier<? extends T> supplier);
/**
@@ -331,7 +332,6 @@ public abstract class Optional<T> implements Serializable {
*
* @since 11.0 (generics widened in 13.0)
*/
- @Beta
public static <T> Iterable<T> presentInstances(
final Iterable<? extends Optional<? extends T>> optionals) {
checkNotNull(optionals);
diff --git a/guava/src/com/google/common/base/PairwiseEquivalence.java b/guava/src/com/google/common/base/PairwiseEquivalence.java
index 74be27fd7..ea40518c5 100644
--- a/guava/src/com/google/common/base/PairwiseEquivalence.java
+++ b/guava/src/com/google/common/base/PairwiseEquivalence.java
@@ -56,7 +56,8 @@ final class PairwiseEquivalence<E, T extends @Nullable E> extends Equivalence<It
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof PairwiseEquivalence) {
- PairwiseEquivalence<?, ?> that = (PairwiseEquivalence<?, ?>) object;
+ @SuppressWarnings("unchecked")
+ PairwiseEquivalence<Object, Object> that = (PairwiseEquivalence<Object, Object>) object;
return this.elementEquivalence.equals(that.elementEquivalence);
}
diff --git a/guava/src/com/google/common/base/ParametricNullness.java b/guava/src/com/google/common/base/ParametricNullness.java
index 5b595adb3..0bcc65dc2 100644
--- a/guava/src/com/google/common/base/ParametricNullness.java
+++ b/guava/src/com/google/common/base/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/base/PatternCompiler.java b/guava/src/com/google/common/base/PatternCompiler.java
index 72a45faae..6a7b620b2 100644
--- a/guava/src/com/google/common/base/PatternCompiler.java
+++ b/guava/src/com/google/common/base/PatternCompiler.java
@@ -15,12 +15,14 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
/**
* Pluggable interface for compiling a regex pattern. By default this package uses the {@code
* java.util.regex} library, but an alternate implementation can be supplied using the {@link
* java.util.ServiceLoader} mechanism.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
interface PatternCompiler {
diff --git a/guava/src/com/google/common/base/Platform.java b/guava/src/com/google/common/base/Platform.java
index 644e89cbf..e24df7c7d 100644
--- a/guava/src/com/google/common/base/Platform.java
+++ b/guava/src/com/google/common/base/Platform.java
@@ -36,12 +36,6 @@ final class Platform {
private Platform() {}
- /** Calls {@link System#nanoTime()}. */
- @SuppressWarnings("GoodTime") // reading system time without TimeSource
- static long systemNanoTime() {
- return System.nanoTime();
- }
-
static CharMatcher precomputeCharMatcher(CharMatcher matcher) {
return matcher.precomputedInternal();
}
@@ -108,25 +102,4 @@ final class Platform {
return true;
}
}
-
- static void checkGwtRpcEnabled() {
- String propertyName = "guava.gwt.emergency_reenable_rpc";
-
- if (!Boolean.parseBoolean(System.getProperty(propertyName, "false"))) {
- throw new UnsupportedOperationException(
- Strings.lenientFormat(
- "We are removing GWT-RPC support for Guava types. You can temporarily reenable"
- + " support by setting the system property %s to true. For more about system"
- + " properties, see %s. For more about Guava's GWT-RPC support, see %s.",
- propertyName,
- "https://stackoverflow.com/q/5189914/28465",
- "https://groups.google.com/d/msg/guava-announce/zHZTFg7YF3o/rQNnwdHeEwAJ"));
- }
- logger.log(
- java.util.logging.Level.WARNING,
- "Later in 2020, we will remove GWT-RPC support for Guava types. You are seeing this"
- + " warning because you are sending a Guava type over GWT-RPC, which will break. You"
- + " can identify which type by looking at the class name in the attached stack trace.",
- new Throwable());
- }
}
diff --git a/guava/src/com/google/common/base/Preconditions.java b/guava/src/com/google/common/base/Preconditions.java
index 13ff77b7f..1e9ac39cb 100644
--- a/guava/src/com/google/common/base/Preconditions.java
+++ b/guava/src/com/google/common/base/Preconditions.java
@@ -118,8 +118,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public final class Preconditions {
private Preconditions() {}
- // TODO(cpovirk): Standardize parameter names (expression vs. b, reference vs. obj).
-
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
@@ -175,8 +173,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1) {
- if (!b) {
+ public static void checkArgument(boolean expression, String errorMessageTemplate, char p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -188,8 +186,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1) {
- if (!b) {
+ public static void checkArgument(boolean expression, String errorMessageTemplate, int p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -201,8 +199,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1) {
- if (!b) {
+ public static void checkArgument(boolean expression, String errorMessageTemplate, long p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -215,8 +213,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -228,8 +226,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1, char p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, char p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -241,8 +240,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1, int p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, char p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -254,8 +254,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, char p1, long p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, char p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -268,8 +269,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -281,8 +282,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1, char p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, int p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -294,8 +296,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1, int p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, int p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -307,8 +310,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, int p1, long p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, int p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -321,8 +325,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -334,8 +338,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1, char p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, long p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -347,8 +352,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1, int p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, long p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -360,8 +366,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkArgument(boolean b, String errorMessageTemplate, long p1, long p2) {
- if (!b) {
+ public static void checkArgument(
+ boolean expression, String errorMessageTemplate, long p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -374,8 +381,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -388,8 +395,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -402,8 +409,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -416,8 +423,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -430,8 +437,11 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression,
+ String errorMessageTemplate,
+ @CheckForNull Object p1,
+ @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -444,12 +454,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3) {
- if (!b) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
@@ -462,13 +472,13 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3,
@CheckForNull Object p4) {
- if (!b) {
+ if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
}
@@ -522,7 +532,7 @@ public final class Preconditions {
boolean expression,
/*
* TODO(cpovirk): Consider removing @CheckForNull here, as we've done with the other methods'
- * errorMessageTemplate parameters: It it unlikely that callers intend for their string
+ * errorMessageTemplate parameters: It is unlikely that callers intend for their string
* template to be null (though we do handle that case gracefully at runtime). I've left this
* one as it is because one of our users has defined a wrapper API around Preconditions,
* declaring a checkState method that accepts a possibly null template. So we'd need to update
@@ -543,8 +553,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -557,8 +567,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -571,8 +581,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -585,8 +595,9 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, @CheckForNull Object p1) {
- if (!b) {
+ public static void checkState(
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
@@ -599,8 +610,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1, char p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -613,8 +624,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1, int p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -627,8 +638,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, char p1, long p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, char p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -642,8 +653,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -656,8 +667,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1, char p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -670,8 +681,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1, int p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -684,8 +695,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, int p1, long p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, int p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -699,8 +710,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -713,8 +724,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1, char p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -727,8 +738,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1, int p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -741,8 +752,8 @@ public final class Preconditions {
*
* @since 20.0 (varargs overload since 2.0)
*/
- public static void checkState(boolean b, String errorMessageTemplate, long p1, long p2) {
- if (!b) {
+ public static void checkState(boolean expression, String errorMessageTemplate, long p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -756,8 +767,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -771,8 +782,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -786,8 +797,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -801,8 +812,8 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
- if (!b) {
+ boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -816,8 +827,11 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) {
- if (!b) {
+ boolean expression,
+ String errorMessageTemplate,
+ @CheckForNull Object p1,
+ @CheckForNull Object p2) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
@@ -831,12 +845,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3) {
- if (!b) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
@@ -850,13 +864,13 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
- boolean b,
+ boolean expression,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3,
@CheckForNull Object p4) {
- if (!b) {
+ if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
}
@@ -943,11 +957,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
- public static <T> T checkNotNull(@CheckForNull T obj, String errorMessageTemplate, char p1) {
- if (obj == null) {
+ public static <T> T checkNotNull(
+ @CheckForNull T reference, String errorMessageTemplate, char p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -958,11 +973,11 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
- public static <T> T checkNotNull(@CheckForNull T obj, String errorMessageTemplate, int p1) {
- if (obj == null) {
+ public static <T> T checkNotNull(@CheckForNull T reference, String errorMessageTemplate, int p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -973,11 +988,12 @@ public final class Preconditions {
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
- public static <T> T checkNotNull(@CheckForNull T obj, String errorMessageTemplate, long p1) {
- if (obj == null) {
+ public static <T> T checkNotNull(
+ @CheckForNull T reference, String errorMessageTemplate, long p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -989,11 +1005,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
- return obj;
+ return reference;
}
/**
@@ -1005,11 +1021,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1021,11 +1037,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1037,11 +1053,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1053,11 +1069,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, char p1, @CheckForNull Object p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1069,11 +1085,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1085,11 +1101,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1101,11 +1117,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1117,11 +1133,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, int p1, @CheckForNull Object p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1133,11 +1149,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1149,11 +1165,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1165,11 +1181,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1181,11 +1197,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, long p1, @CheckForNull Object p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1197,11 +1213,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, char p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1213,11 +1229,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, int p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1229,11 +1245,11 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
- if (obj == null) {
+ @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, long p2) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1245,14 +1261,14 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj,
+ @CheckForNull T reference,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2) {
- if (obj == null) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
- return obj;
+ return reference;
}
/**
@@ -1264,15 +1280,15 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj,
+ @CheckForNull T reference,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3) {
- if (obj == null) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2, p3));
}
- return obj;
+ return reference;
}
/**
@@ -1284,16 +1300,16 @@ public final class Preconditions {
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
- @CheckForNull T obj,
+ @CheckForNull T reference,
String errorMessageTemplate,
@CheckForNull Object p1,
@CheckForNull Object p2,
@CheckForNull Object p3,
@CheckForNull Object p4) {
- if (obj == null) {
+ if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
- return obj;
+ return reference;
}
/*
diff --git a/guava/src/com/google/common/base/Predicate.java b/guava/src/com/google/common/base/Predicate.java
index 4384ed0e5..7ec798314 100644
--- a/guava/src/com/google/common/base/Predicate.java
+++ b/guava/src/com/google/common/base/Predicate.java
@@ -15,7 +15,6 @@
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -60,7 +59,6 @@ public interface Predicate<T extends @Nullable Object> extends java.util.functio
* @throws NullPointerException if {@code input} is null and this predicate does not accept null
* arguments
*/
- @CanIgnoreReturnValue
boolean apply(@ParametricNullness T input);
/**
diff --git a/guava/src/com/google/common/base/Predicates.java b/guava/src/com/google/common/base/Predicates.java
index dc487fc56..30d2ac7dc 100644
--- a/guava/src/com/google/common/base/Predicates.java
+++ b/guava/src/com/google/common/base/Predicates.java
@@ -16,9 +16,9 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
@@ -195,8 +195,8 @@ public final class Predicates {
*
* @since 20.0 (since 10.0 under the incorrect name {@code assignableFrom})
*/
+ @J2ktIncompatible
@GwtIncompatible // Class.isAssignableFrom
- @Beta
public static Predicate<Class<?>> subtypeOf(Class<?> clazz) {
return new SubtypeOfPredicate(clazz);
}
@@ -235,6 +235,7 @@ public final class Predicates {
* @throws IllegalArgumentException if the pattern is invalid
* @since 3.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Only used by other GWT-incompatible code.
public static Predicate<CharSequence> containsPattern(String pattern) {
return new ContainsPatternFromStringPredicate(pattern);
@@ -247,6 +248,7 @@ public final class Predicates {
*
* @since 3.0
*/
+ @J2ktIncompatible
@GwtIncompatible(value = "java.util.regex.Pattern")
public static Predicate<CharSequence> contains(Pattern pattern) {
return new ContainsPatternPredicate(new JdkPattern(pattern));
@@ -486,7 +488,9 @@ public final class Predicates {
}
}
- /** @see Predicates#instanceOf(Class) */
+ /**
+ * @see Predicates#instanceOf(Class)
+ */
@GwtIncompatible // Class.isInstance
private static class InstanceOfPredicate<T extends @Nullable Object>
implements Predicate<T>, Serializable {
@@ -520,10 +524,13 @@ public final class Predicates {
return "Predicates.instanceOf(" + clazz.getName() + ")";
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
- /** @see Predicates#subtypeOf(Class) */
+ /**
+ * @see Predicates#subtypeOf(Class)
+ */
+ @J2ktIncompatible
@GwtIncompatible // Class.isAssignableFrom
private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable {
private final Class<?> clazz;
@@ -638,7 +645,10 @@ public final class Predicates {
private static final long serialVersionUID = 0;
}
- /** @see Predicates#contains(Pattern) */
+ /**
+ * @see Predicates#contains(Pattern)
+ */
+ @J2ktIncompatible
@GwtIncompatible // Only used by other GWT-incompatible code.
private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable {
final CommonPattern pattern;
@@ -686,7 +696,10 @@ public final class Predicates {
private static final long serialVersionUID = 0;
}
- /** @see Predicates#containsPattern(String) */
+ /**
+ * @see Predicates#containsPattern(String)
+ */
+ @J2ktIncompatible
@GwtIncompatible // Only used by other GWT-incompatible code.
private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate {
diff --git a/guava/src/com/google/common/base/SmallCharMatcher.java b/guava/src/com/google/common/base/SmallCharMatcher.java
index f0e801b67..816825641 100644
--- a/guava/src/com/google/common/base/SmallCharMatcher.java
+++ b/guava/src/com/google/common/base/SmallCharMatcher.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.NamedFastMatcher;
import java.util.BitSet;
@@ -25,6 +26,7 @@ import java.util.BitSet;
*
* @author Christopher Swenson
*/
+@J2ktIncompatible
@GwtIncompatible // no precomputation is done in GWT
@ElementTypesAreNonnullByDefault
final class SmallCharMatcher extends NamedFastMatcher {
diff --git a/guava/src/com/google/common/base/Splitter.java b/guava/src/com/google/common/base/Splitter.java
index e60e9887d..f8415a79a 100644
--- a/guava/src/com/google/common/base/Splitter.java
+++ b/guava/src/com/google/common/base/Splitter.java
@@ -17,9 +17,9 @@ package com.google.common.base;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
@@ -214,6 +214,7 @@ public final class Splitter {
* @return a splitter, with default settings, that uses this pattern
* @throws IllegalArgumentException if {@code separatorPattern} matches the empty string
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex
public static Splitter on(Pattern separatorPattern) {
return on(new JdkPattern(separatorPattern));
@@ -257,6 +258,7 @@ public final class Splitter {
* @throws IllegalArgumentException if {@code separatorPattern} matches the empty string or is a
* malformed expression
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.regex
public static Splitter onPattern(String separatorPattern) {
return on(Platform.compilePattern(separatorPattern));
@@ -434,7 +436,6 @@ public final class Splitter {
* @return a stream over the segments split from the parameter
* @since 28.2
*/
- @Beta
public Stream<String> splitToStream(CharSequence sequence) {
// Can't use Streams.stream() from base
return StreamSupport.stream(split(sequence).spliterator(), false);
@@ -446,7 +447,6 @@ public final class Splitter {
*
* @since 10.0
*/
- @Beta
public MapSplitter withKeyValueSeparator(String separator) {
return withKeyValueSeparator(on(separator));
}
@@ -457,7 +457,6 @@ public final class Splitter {
*
* @since 14.0
*/
- @Beta
public MapSplitter withKeyValueSeparator(char separator) {
return withKeyValueSeparator(on(separator));
}
@@ -481,7 +480,6 @@ public final class Splitter {
*
* @since 10.0
*/
- @Beta
public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
return new MapSplitter(this, keyValueSplitter);
}
@@ -494,7 +492,6 @@ public final class Splitter {
*
* @since 10.0
*/
- @Beta
public static final class MapSplitter {
private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry";
private final Splitter outerSplitter;
diff --git a/guava/src/com/google/common/base/StandardSystemProperty.java b/guava/src/com/google/common/base/StandardSystemProperty.java
index dc29792de..155037761 100644
--- a/guava/src/com/google/common/base/StandardSystemProperty.java
+++ b/guava/src/com/google/common/base/StandardSystemProperty.java
@@ -15,6 +15,7 @@
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
@@ -23,6 +24,7 @@ import javax.annotation.CheckForNull;
* @author Kurt Alfred Kluever
* @since 15.0
*/
+@J2ktIncompatible
@GwtIncompatible // java.lang.System#getProperty
@ElementTypesAreNonnullByDefault
public enum StandardSystemProperty {
@@ -125,7 +127,7 @@ public enum StandardSystemProperty {
this.key = key;
}
- /** Returns the key used to lookup this system property. */
+ /** Returns the key used to look up this system property. */
public String key() {
return key;
}
diff --git a/guava/src/com/google/common/base/Stopwatch.java b/guava/src/com/google/common/base/Stopwatch.java
index 9d5282d24..d67b22cd8 100644
--- a/guava/src/com/google/common/base/Stopwatch.java
+++ b/guava/src/com/google/common/base/Stopwatch.java
@@ -26,6 +26,7 @@ import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.time.Duration;
@@ -36,7 +37,7 @@ import java.util.concurrent.TimeUnit;
* successive readings of "now" in the same process.
*
* <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like
- * {@link System#currentTimeMillis()}, best represented as an {@link Instant}. Such values
+ * {@link System#currentTimeMillis()}, best represented as an {@link java.time.Instant}. Such values
* <i>can</i> be subtracted to obtain a {@code Duration} (such as by {@code Duration.between}), but
* doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings
* are inherently approximate, routinely affected by periodic clock corrections. Because this class
@@ -51,6 +52,12 @@ import java.util.concurrent.TimeUnit;
* performance reasons, without affecting most of your code.
* </ul>
*
+ * <p>The one downside of {@code Stopwatch} relative to {@link System#nanoTime()} is that {@code
+ * Stopwatch} requires object allocation and additional method calls, which can reduce the accuracy
+ * of the elapsed times reported. {@code Stopwatch} is still suitable for logging and metrics where
+ * reasonably accurate values are sufficient. If the uncommon case that you need to maximize
+ * accuracy, use {@code System.nanoTime()} directly instead.
+ *
* <p>Basic usage:
*
* <pre>{@code
@@ -217,6 +224,7 @@ public final class Stopwatch {
*
* @since 22.0
*/
+ @J2ktIncompatible
@GwtIncompatible
@J2ObjCIncompatible
public Duration elapsed() {
diff --git a/guava/src/com/google/common/base/Supplier.java b/guava/src/com/google/common/base/Supplier.java
index 08f96becc..518325a35 100644
--- a/guava/src/com/google/common/base/Supplier.java
+++ b/guava/src/com/google/common/base/Supplier.java
@@ -15,7 +15,6 @@
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -46,7 +45,6 @@ public interface Supplier<T extends @Nullable Object> extends java.util.function
*
* @return an instance of the appropriate type
*/
- @CanIgnoreReturnValue
@Override
@ParametricNullness
T get();
diff --git a/guava/src/com/google/common/base/Suppliers.java b/guava/src/com/google/common/base/Suppliers.java
index 6ced905b9..d97bff626 100644
--- a/guava/src/com/google/common/base/Suppliers.java
+++ b/guava/src/com/google/common/base/Suppliers.java
@@ -17,7 +17,6 @@ package com.google.common.base;
import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
@@ -97,7 +96,7 @@ public final class Suppliers {
* <p>The returned supplier is thread-safe. The delegate's {@code get()} method will be invoked at
* most once unless the underlying {@code get()} throws an exception. The supplier's serialized
* form does not contain the cached value, which will be recalculated when {@code get()} is called
- * on the reserialized instance.
+ * on the deserialized instance.
*
* <p>When the underlying delegate throws an exception then this memoizing supplier will keep
* delegating calls until it returns valid data.
@@ -157,11 +156,15 @@ public final class Suppliers {
@VisibleForTesting
static class NonSerializableMemoizingSupplier<T extends @Nullable Object> implements Supplier<T> {
- @CheckForNull volatile Supplier<T> delegate;
- volatile boolean initialized;
- // "value" does not need to be volatile; visibility piggy-backs
- // on volatile read of "initialized".
- @CheckForNull T value;
+ @SuppressWarnings("UnnecessaryLambda") // Must be a fixed singleton object
+ private static final Supplier<Void> SUCCESSFULLY_COMPUTED =
+ () -> {
+ throw new IllegalStateException(); // Should never get called.
+ };
+
+ private volatile Supplier<T> delegate;
+ // "value" does not need to be volatile; visibility piggy-backs on volatile read of "delegate".
+ @CheckForNull private T value;
NonSerializableMemoizingSupplier(Supplier<T> delegate) {
this.delegate = checkNotNull(delegate);
@@ -169,27 +172,20 @@ public final class Suppliers {
@Override
@ParametricNullness
+ @SuppressWarnings("unchecked") // Cast from Supplier<Void> to Supplier<T> is always valid
public T get() {
- // A 2-field variant of Double Checked Locking.
- if (!initialized) {
+ // Because Supplier is read-heavy, we use the "double-checked locking" pattern.
+ if (delegate != SUCCESSFULLY_COMPUTED) {
synchronized (this) {
- if (!initialized) {
- /*
- * requireNonNull is safe because we read and write `delegate` under synchronization.
- *
- * TODO(cpovirk): To avoid having to check for null, replace `delegate` with a singleton
- * `Supplier` that always throws an exception.
- */
- T t = requireNonNull(delegate).get();
+ if (delegate != SUCCESSFULLY_COMPUTED) {
+ T t = delegate.get();
value = t;
- initialized = true;
- // Release the delegate to GC.
- delegate = null;
+ delegate = (Supplier<T>) SUCCESSFULLY_COMPUTED;
return t;
}
}
}
- // This is safe because we checked `initialized.`
+ // This is safe because we checked `delegate.`
return uncheckedCastNullableTToT(value);
}
@@ -197,7 +193,9 @@ public final class Suppliers {
public String toString() {
Supplier<T> delegate = this.delegate;
return "Suppliers.memoize("
- + (delegate == null ? "<supplier that returned " + value + ">" : delegate)
+ + (delegate == SUCCESSFULLY_COMPUTED
+ ? "<supplier that returned " + value + ">"
+ : delegate)
+ ")";
}
}
@@ -247,6 +245,7 @@ public final class Suppliers {
@Override
@ParametricNullness
+ @SuppressWarnings("GoodTime") // reading system time without TimeSource
public T get() {
// Another variant of Double Checked Locking.
//
@@ -255,7 +254,7 @@ public final class Suppliers {
// the extra memory consumption and indirection are more
// expensive than the extra volatile reads.
long nanos = expirationNanos;
- long now = Platform.systemNanoTime();
+ long now = System.nanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
diff --git a/guava/src/com/google/common/base/Throwables.java b/guava/src/com/google/common/base/Throwables.java
index e45ce800c..23936897d 100644
--- a/guava/src/com/google/common/base/Throwables.java
+++ b/guava/src/com/google/common/base/Throwables.java
@@ -21,6 +21,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -69,6 +70,7 @@ public final class Throwables {
*
* @since 20.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Class.cast, Class.isInstance
public static <X extends Throwable> void throwIfInstanceOf(
Throwable throwable, Class<X> declaredType) throws X {
@@ -98,6 +100,7 @@ public final class Throwables {
* null}.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible // throwIfInstanceOf
public static <X extends Throwable> void propagateIfInstanceOf(
@CheckForNull Throwable throwable, Class<X> declaredType) throws X {
@@ -154,6 +157,7 @@ public final class Throwables {
* null}.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible
public static void propagateIfPossible(@CheckForNull Throwable throwable) {
if (throwable != null) {
@@ -179,6 +183,7 @@ public final class Throwables {
* @param throwable the Throwable to possibly propagate
* @param declaredType the single checked exception type declared by the calling method
*/
+ @J2ktIncompatible
@GwtIncompatible // propagateIfInstanceOf
public static <X extends Throwable> void propagateIfPossible(
@CheckForNull Throwable throwable, Class<X> declaredType) throws X {
@@ -197,6 +202,7 @@ public final class Throwables {
* @param declaredType1 any checked exception type declared by the calling method
* @param declaredType2 any other checked exception type declared by the calling method
*/
+ @J2ktIncompatible
@GwtIncompatible // propagateIfInstanceOf
public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
@CheckForNull Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
@@ -235,6 +241,7 @@ public final class Throwables {
* {@code Throwables.propagate}</a>.
*/
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible
@Deprecated
public static RuntimeException propagate(Throwable throwable) {
@@ -328,6 +335,7 @@ public final class Throwables {
* ClassCastException}'s cause is {@code throwable}.
* @since 22.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Class.cast(Object)
@CheckForNull
public static <X extends Throwable> X getCauseAs(
@@ -384,6 +392,7 @@ public final class Throwables {
* possible use the {@code java.lang.StackWalker.walk} method introduced in JDK 9.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace
public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
return lazyStackTraceIsLazy()
@@ -400,11 +409,13 @@ public final class Throwables {
* versions.
*/
@Deprecated
+ @J2ktIncompatible
@GwtIncompatible // getStackTraceElementMethod
public static boolean lazyStackTraceIsLazy() {
return getStackTraceElementMethod != null && getStackTraceDepthMethod != null;
}
+ @J2ktIncompatible
@GwtIncompatible // invokeAccessibleNonThrowingMethod
private static List<StackTraceElement> jlaStackTrace(Throwable t) {
checkNotNull(t);
@@ -435,6 +446,7 @@ public final class Throwables {
};
}
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
private static Object invokeAccessibleNonThrowingMethod(
Method method, Object receiver, Object... params) {
@@ -448,15 +460,17 @@ public final class Throwables {
}
/** JavaLangAccess class name to load using reflection */
- @GwtIncompatible // not used by GWT emulation
+ @J2ktIncompatible @GwtIncompatible // not used by GWT emulation
private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess";
/** SharedSecrets class name to load using reflection */
+ @J2ktIncompatible
@GwtIncompatible // not used by GWT emulation
@VisibleForTesting
static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets";
/** Access to some fancy internal JVM internals. */
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static final Object jla = getJLA();
@@ -465,6 +479,7 @@ public final class Throwables {
* The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to
* find it when available. When this is null, use the slow way.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod();
@@ -473,6 +488,7 @@ public final class Throwables {
* The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it
* when available. When this is null, use the slow way.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(jla);
@@ -481,6 +497,7 @@ public final class Throwables {
* Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in
* AppEngine, and not present in non-Sun JDKs.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Object getJLA() {
@@ -507,6 +524,7 @@ public final class Throwables {
* Returns the Method that can be used to resolve an individual StackTraceElement, or null if that
* method cannot be found (it is only to be found in fairly recent JDKs).
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Method getGetMethod() {
@@ -516,12 +534,13 @@ public final class Throwables {
/**
* Returns the Method that can be used to return the size of a stack, or null if that method
* cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link
- * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable)} getStackTraceDepth} prior to return it
+ * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable) getStackTraceDepth} prior to return it
* (might fail some JDKs).
*
* <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws
* UnsupportedOperationException</a>.
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Method getSizeMethod(Object jla) {
@@ -537,6 +556,7 @@ public final class Throwables {
}
}
+ @J2ktIncompatible
@GwtIncompatible // java.lang.reflect
@CheckForNull
private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath {
diff --git a/guava/src/com/google/common/base/Ticker.java b/guava/src/com/google/common/base/Ticker.java
index d898735c0..5b7a48688 100644
--- a/guava/src/com/google/common/base/Ticker.java
+++ b/guava/src/com/google/common/base/Ticker.java
@@ -48,8 +48,9 @@ public abstract class Ticker {
private static final Ticker SYSTEM_TICKER =
new Ticker() {
@Override
+ @SuppressWarnings("GoodTime") // reading system time without TimeSource
public long read() {
- return Platform.systemNanoTime();
+ return System.nanoTime();
}
};
}
diff --git a/guava/src/com/google/common/base/Utf8.java b/guava/src/com/google/common/base/Utf8.java
index bb945a35f..f1209bf45 100644
--- a/guava/src/com/google/common/base/Utf8.java
+++ b/guava/src/com/google/common/base/Utf8.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Character.MAX_SURROGATE;
import static java.lang.Character.MIN_SURROGATE;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
@@ -36,7 +35,6 @@ import com.google.common.annotations.GwtCompatible;
* @author Clément Roux
* @since 16.0
*/
-@Beta
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Utf8 {
diff --git a/guava/src/com/google/common/base/package-info.java b/guava/src/com/google/common/base/package-info.java
index f2218562e..bfae42674 100644
--- a/guava/src/com/google/common/base/package-info.java
+++ b/guava/src/com/google/common/base/package-info.java
@@ -15,45 +15,46 @@
/**
* Basic utility libraries and interfaces.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* <h2>Contents</h2>
*
- * <h3>String-related utilities</h3>
+ * The classes in this package that are most commonly useful are:
+ *
+ * <h3>String utilities</h3>
*
* <ul>
- * <li>{@link com.google.common.base.Ascii}
- * <li>{@link com.google.common.base.CaseFormat}
- * <li>{@link com.google.common.base.CharMatcher}
- * <li>{@link com.google.common.base.Charsets}
- * <li>{@link com.google.common.base.Joiner}
- * <li>{@link com.google.common.base.Splitter}
- * <li>{@link com.google.common.base.Strings}
+ * <li>{@link Ascii}
+ * <li>{@link CaseFormat}
+ * <li>{@link CharMatcher}
+ * <li>{@link Splitter}
+ * <li>{@link Strings}
* </ul>
*
* <h3>Function types</h3>
*
* <ul>
- * <li>{@link com.google.common.base.Function}, {@link com.google.common.base.Functions}
- * <li>{@link com.google.common.base.Predicate}, {@link com.google.common.base.Predicates}
- * <li>{@link com.google.common.base.Equivalence}
- * <li>{@link com.google.common.base.Converter}
- * <li>{@link com.google.common.base.Supplier}, {@link com.google.common.base.Suppliers}
+ * <li>{@link Converter}
+ * <li>{@link Equivalence}
* </ul>
*
* <h3>Other</h3>
*
* <ul>
- * <li>{@link com.google.common.base.Defaults}
- * <li>{@link com.google.common.base.Enums}
- * <li>{@link com.google.common.base.Objects}
- * <li>{@link com.google.common.base.Optional}
- * <li>{@link com.google.common.base.Preconditions}
- * <li>{@link com.google.common.base.Stopwatch}
- * <li>{@link com.google.common.base.Throwables}
+ * <li>{@link Enums}
+ * <li>{@link MoreObjects}
+ * <li>{@link Preconditions}
+ * <li>{@link StandardSystemProperty}
+ * <li>{@link Stopwatch}
+ * <li>{@link Throwables}
+ * <li>{@link Verify}
* </ul>
*
+ * <h3>The rest</h3>
+ *
+ * This package also contains some classes with niche use cases (e.g., {@link Utf8} and {@link
+ * Defaults}), as well as a number of classes that have been superseded by additions to the JDK.
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
diff --git a/guava/src/com/google/common/cache/AbstractLoadingCache.java b/guava/src/com/google/common/cache/AbstractLoadingCache.java
index 489597c51..5081a785b 100644
--- a/guava/src/com/google/common/cache/AbstractLoadingCache.java
+++ b/guava/src/com/google/common/cache/AbstractLoadingCache.java
@@ -18,6 +18,7 @@ import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.UncheckedExecutionException;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -45,6 +46,7 @@ public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V>
/** Constructor for use by subclasses. */
protected AbstractLoadingCache() {}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
@Override
public V getUnchecked(K key) {
try {
diff --git a/guava/src/com/google/common/cache/Cache.java b/guava/src/com/google/common/cache/Cache.java
index 8755595a0..41cce7037 100644
--- a/guava/src/com/google/common/cache/Cache.java
+++ b/guava/src/com/google/common/cache/Cache.java
@@ -18,7 +18,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
-import com.google.errorprone.annotations.CheckReturnValue;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CompatibleWith;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Map;
@@ -52,6 +52,7 @@ public interface Cache<K, V> {
* @since 11.0
*/
@CheckForNull
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
V getIfPresent(@CompatibleWith("K") Object key);
/**
@@ -100,6 +101,7 @@ public interface Cache<K, V> {
* @throws ExecutionError if an error was thrown while loading the value
* @since 11.0
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
V get(K key, Callable<? extends V> loader) throws ExecutionException;
/**
@@ -150,7 +152,6 @@ public interface Cache<K, V> {
void invalidateAll();
/** Returns the approximate number of entries in this cache. */
- @CheckReturnValue
long size();
/**
@@ -164,7 +165,6 @@ public interface Cache<K, V> {
* all values is returned.
*
*/
- @CheckReturnValue
CacheStats stats();
/**
@@ -175,7 +175,6 @@ public interface Cache<K, V> {
* concurrent use, but if the cache is modified (including by eviction) after the iterator is
* created, it is undefined which of the changes (if any) will be reflected in that iterator.
*/
- @CheckReturnValue
ConcurrentMap<K, V> asMap();
/**
diff --git a/guava/src/com/google/common/cache/CacheBuilder.java b/guava/src/com/google/common/cache/CacheBuilder.java
index 668769b6e..bbb2b185b 100644
--- a/guava/src/com/google/common/cache/CacheBuilder.java
+++ b/guava/src/com/google/common/cache/CacheBuilder.java
@@ -29,16 +29,17 @@ import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.cache.LocalCache.Strength;
-import com.google.errorprone.annotations.CheckReturnValue;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.J2ObjCIncompatible;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
import java.util.ConcurrentModificationException;
import java.util.IdentityHashMap;
import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.checkerframework.checker.nullness.qual.Nullable;
+import javax.annotation.CheckForNull;
/**
* A builder of {@link LoadingCache} and {@link Cache} instances.
@@ -96,7 +97,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* <li>accumulation of cache access statistics
* </ul>
*
- * <p>These features are all optional; caches can be created using all or none of them. By default
+ * <p>These features are all optional; caches can be created using all or none of them. By default,
* cache instances created by {@code CacheBuilder} will not perform any type of eviction.
*
* <p>Usage example:
@@ -130,13 +131,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* });
* }</pre>
*
- * <p>The returned cache is implemented as a hash table with similar performance characteristics to
- * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
- * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
- * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
- * modify the cache after the iterator is created, it is undefined which of these changes, if any,
- * are reflected in that iterator. These iterators never throw {@link
- * ConcurrentModificationException}.
+ * <p>The returned cache implements all optional operations of the {@link LoadingCache} and {@link
+ * Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly consistent
+ * iterators</i>. This means that they are safe for concurrent use, but if other threads modify the
+ * cache after the iterator is created, it is undefined which of these changes, if any, are
+ * reflected in that iterator. These iterators never throw {@link ConcurrentModificationException}.
*
* <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link
* Object#equals equals} method) to determine equality for keys or values. However, if {@link
@@ -144,34 +143,33 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity
* comparisons for values.
*
- * <p>Entries are automatically evicted from the cache when any of {@linkplain #maximumSize(long)
- * maximumSize}, {@linkplain #maximumWeight(long) maximumWeight}, {@linkplain #expireAfterWrite
- * expireAfterWrite}, {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys
- * weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are
- * requested.
+ * <p>Entries are automatically evicted from the cache when any of {@link #maximumSize(long)
+ * maximumSize}, {@link #maximumWeight(long) maximumWeight}, {@link #expireAfterWrite
+ * expireAfterWrite}, {@link #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys},
+ * {@link #weakValues weakValues}, or {@link #softValues softValues} are requested.
*
- * <p>If {@linkplain #maximumSize(long) maximumSize} or {@linkplain #maximumWeight(long)
- * maximumWeight} is requested entries may be evicted on each cache modification.
+ * <p>If {@link #maximumSize(long) maximumSize} or {@link #maximumWeight(long) maximumWeight} is
+ * requested entries may be evicted on each cache modification.
*
- * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or {@linkplain #expireAfterAccess
- * expireAfterAccess} is requested entries may be evicted on each cache modification, on occasional
- * cache accesses, or on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link
- * Cache#size}, but will never be visible to read or write operations.
+ * <p>If {@link #expireAfterWrite expireAfterWrite} or {@link #expireAfterAccess expireAfterAccess}
+ * is requested entries may be evicted on each cache modification, on occasional cache accesses, or
+ * on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link Cache#size}, but will
+ * never be visible to read or write operations.
*
- * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain
- * #softValues softValues} are requested, it is possible for a key or value present in the cache to
- * be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from
- * the cache on each cache modification, on occasional cache accesses, or on calls to {@link
- * Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be visible to
- * read or write operations.
+ * <p>If {@link #weakKeys weakKeys}, {@link #weakValues weakValues}, or {@link #softValues
+ * softValues} are requested, it is possible for a key or value present in the cache to be reclaimed
+ * by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on
+ * each cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}; such
+ * entries may be counted in {@link Cache#size}, but will never be visible to read or write
+ * operations.
*
* <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
* will be performed during write operations, or during occasional read operations in the absence of
* writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
- * calling it should not be necessary with a high throughput cache. Only caches built with
- * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
- * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys}, {@linkplain
- * #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic maintenance.
+ * calling it should not be necessary with a high throughput cache. Only caches built with {@link
+ * #removalListener removalListener}, {@link #expireAfterWrite expireAfterWrite}, {@link
+ * #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys}, {@link #weakValues
+ * weakValues}, or {@link #softValues softValues} perform periodic maintenance.
*
* <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
* retain all the configuration properties of the original cache. Note that the serialized form does
@@ -230,6 +228,18 @@ public final class CacheBuilder<K, V> {
});
static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
+ /*
+ * We avoid using a method reference or lambda here for now:
+ *
+ * - method reference: Inside Google, CacheBuilder is used from the implementation of a custom
+ * ClassLoader that is sometimes used as a system classloader. That's a problem because
+ * method-reference linking tries to look up the system classloader, and it fails because there
+ * isn't one yet.
+ *
+ * - lambda: Outside Google, we got a report of a similar problem in
+ * https://github.com/google/guava/issues/6565
+ */
+ @SuppressWarnings("AnonymousToLambda")
static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
new Supplier<StatsCounter>() {
@Override
@@ -262,7 +272,10 @@ public final class CacheBuilder<K, V> {
}
};
- private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
+ // We use a holder class to delay initialization: https://github.com/google/guava/issues/6566
+ private static final class LoggerHolder {
+ static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
+ }
static final int UNSET_INT = -1;
@@ -272,10 +285,10 @@ public final class CacheBuilder<K, V> {
int concurrencyLevel = UNSET_INT;
long maximumSize = UNSET_INT;
long maximumWeight = UNSET_INT;
- @Nullable Weigher<? super K, ? super V> weigher;
+ @CheckForNull Weigher<? super K, ? super V> weigher;
- @Nullable Strength keyStrength;
- @Nullable Strength valueStrength;
+ @CheckForNull Strength keyStrength;
+ @CheckForNull Strength valueStrength;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long expireAfterWriteNanos = UNSET_INT;
@@ -286,11 +299,11 @@ public final class CacheBuilder<K, V> {
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long refreshNanos = UNSET_INT;
- @Nullable Equivalence<Object> keyEquivalence;
- @Nullable Equivalence<Object> valueEquivalence;
+ @CheckForNull Equivalence<Object> keyEquivalence;
+ @CheckForNull Equivalence<Object> valueEquivalence;
- @Nullable RemovalListener<? super K, ? super V> removalListener;
- @Nullable Ticker ticker;
+ @CheckForNull RemovalListener<? super K, ? super V> removalListener;
+ @CheckForNull Ticker ticker;
Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
@@ -303,7 +316,6 @@ public final class CacheBuilder<K, V> {
* <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on
* the {@link #build} methods allow you to create a cache of any key and value type desired.
*/
- @CheckReturnValue
public static CacheBuilder<Object, Object> newBuilder() {
return new CacheBuilder<>();
}
@@ -314,7 +326,6 @@ public final class CacheBuilder<K, V> {
* @since 12.0
*/
@GwtIncompatible // To be supported
- @CheckReturnValue
public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
return spec.toCacheBuilder().lenientParsing();
}
@@ -327,7 +338,6 @@ public final class CacheBuilder<K, V> {
* @since 12.0
*/
@GwtIncompatible // To be supported
- @CheckReturnValue
public static CacheBuilder<Object, Object> from(String spec) {
return from(CacheBuilderSpec.parse(spec));
}
@@ -338,6 +348,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
CacheBuilder<K, V> lenientParsing() {
strictParsing = false;
return this;
@@ -352,6 +363,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = checkNotNull(equivalence);
@@ -372,6 +384,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
checkState(
valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
@@ -394,6 +407,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalArgumentException if {@code initialCapacity} is negative
* @throws IllegalStateException if an initial capacity was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
checkState(
this.initialCapacity == UNSET_INT,
@@ -439,6 +453,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
checkState(
this.concurrencyLevel == UNSET_INT,
@@ -474,6 +489,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalArgumentException if {@code maximumSize} is negative
* @throws IllegalStateException if a maximum size or weight was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> maximumSize(long maximumSize) {
checkState(
this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
@@ -515,6 +531,7 @@ public final class CacheBuilder<K, V> {
* @since 11.0
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
checkState(
this.maximumWeight == UNSET_INT,
@@ -557,13 +574,14 @@ public final class CacheBuilder<K, V> {
* @since 11.0
*/
@GwtIncompatible // To be supported
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
Weigher<? super K1, ? super V1> weigher) {
checkState(this.weigher == null);
if (strictParsing) {
checkState(
this.maximumSize == UNSET_INT,
- "weigher can not be combined with maximum size",
+ "weigher can not be combined with maximum size (%s provided)",
this.maximumSize);
}
@@ -604,10 +622,12 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if the key strength was already set
*/
@GwtIncompatible // java.lang.ref.WeakReference
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> weakKeys() {
return setKeyStrength(Strength.WEAK);
}
+ @CanIgnoreReturnValue
CacheBuilder<K, V> setKeyStrength(Strength strength) {
checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = checkNotNull(strength);
@@ -636,6 +656,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if the value strength was already set
*/
@GwtIncompatible // java.lang.ref.WeakReference
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> weakValues() {
return setValueStrength(Strength.WEAK);
}
@@ -661,10 +682,12 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if the value strength was already set
*/
@GwtIncompatible // java.lang.ref.SoftReference
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> softValues() {
return setValueStrength(Strength.SOFT);
}
+ @CanIgnoreReturnValue
CacheBuilder<K, V> setValueStrength(Strength strength) {
checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = checkNotNull(strength);
@@ -698,6 +721,7 @@ public final class CacheBuilder<K, V> {
@J2ObjCIncompatible
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // java.time.Duration decomposition
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) {
return expireAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
}
@@ -725,6 +749,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if {@link #expireAfterWrite} was already set
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
checkState(
expireAfterWriteNanos == UNSET_INT,
@@ -768,6 +793,7 @@ public final class CacheBuilder<K, V> {
@J2ObjCIncompatible
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // java.time.Duration decomposition
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterAccess(java.time.Duration duration) {
return expireAfterAccess(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
}
@@ -800,6 +826,7 @@ public final class CacheBuilder<K, V> {
* @throws IllegalStateException if {@link #expireAfterAccess} was already set
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
checkState(
expireAfterAccessNanos == UNSET_INT,
@@ -847,6 +874,7 @@ public final class CacheBuilder<K, V> {
@J2ObjCIncompatible
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // java.time.Duration decomposition
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> refreshAfterWrite(java.time.Duration duration) {
return refreshAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
}
@@ -883,6 +911,7 @@ public final class CacheBuilder<K, V> {
*/
@GwtIncompatible // To be supported (synchronously).
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
checkNotNull(unit);
checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
@@ -906,6 +935,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a ticker was already set
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> ticker(Ticker ticker) {
checkState(this.ticker == null);
this.ticker = checkNotNull(ticker);
@@ -926,11 +956,11 @@ public final class CacheBuilder<K, V> {
*
* <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
* reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
- * same instance, but only the returned reference has the correct generic type information so as
- * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in
- * the class documentation above, configuring a builder and building your cache in a single
- * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown
- * by a cache operation at some <i>undefined</i> point in the future.
+ * same instance, but only the returned reference has the correct generic type information to
+ * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the
+ * class documentation above, configuring a builder and building your cache in a single statement.
+ * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache
+ * operation at some <i>undefined</i> point in the future.
*
* <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
* the {@code Cache} user, only logged via a {@link Logger}.
@@ -940,7 +970,6 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a removal listener was already set
*/
- @CheckReturnValue
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
RemovalListener<? super K1, ? super V1> listener) {
checkState(this.removalListener == null);
@@ -968,6 +997,7 @@ public final class CacheBuilder<K, V> {
* @return this {@code CacheBuilder} instance (for chaining)
* @since 12.0 (previously, stats collection was automatic)
*/
+ @CanIgnoreReturnValue
public CacheBuilder<K, V> recordStats() {
statsCounterSupplier = CACHE_STATS_COUNTER;
return this;
@@ -993,7 +1023,6 @@ public final class CacheBuilder<K, V> {
* @param loader the cache loader used to obtain new values
* @return a cache having the requested features
*/
- @CheckReturnValue
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
CacheLoader<? super K1, V1> loader) {
checkWeightWithWeigher();
@@ -1012,7 +1041,6 @@ public final class CacheBuilder<K, V> {
* @return a cache having the requested features
* @since 11.0
*/
- @CheckReturnValue
public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
checkWeightWithWeigher();
checkNonLoadingCache();
@@ -1031,7 +1059,8 @@ public final class CacheBuilder<K, V> {
checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
} else {
if (maximumWeight == UNSET_INT) {
- logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
+ LoggerHolder.logger.log(
+ Level.WARNING, "ignoring weigher specified without maximumWeight");
}
}
}
diff --git a/guava/src/com/google/common/cache/CacheBuilderSpec.java b/guava/src/com/google/common/cache/CacheBuilderSpec.java
index 7757f3bc4..adc55e0c6 100644
--- a/guava/src/com/google/common/cache/CacheBuilderSpec.java
+++ b/guava/src/com/google/common/cache/CacheBuilderSpec.java
@@ -328,7 +328,7 @@ public final class CacheBuilderSpec {
protected void parseInteger(CacheBuilderSpec spec, int value) {
checkArgument(
spec.initialCapacity == null,
- "initial capacity was already set to ",
+ "initial capacity was already set to %s",
spec.initialCapacity);
spec.initialCapacity = value;
}
@@ -338,9 +338,10 @@ public final class CacheBuilderSpec {
static class MaximumSizeParser extends LongParser {
@Override
protected void parseLong(CacheBuilderSpec spec, long value) {
- checkArgument(spec.maximumSize == null, "maximum size was already set to ", spec.maximumSize);
checkArgument(
- spec.maximumWeight == null, "maximum weight was already set to ", spec.maximumWeight);
+ spec.maximumSize == null, "maximum size was already set to %s", spec.maximumSize);
+ checkArgument(
+ spec.maximumWeight == null, "maximum weight was already set to %s", spec.maximumWeight);
spec.maximumSize = value;
}
}
@@ -350,8 +351,9 @@ public final class CacheBuilderSpec {
@Override
protected void parseLong(CacheBuilderSpec spec, long value) {
checkArgument(
- spec.maximumWeight == null, "maximum weight was already set to ", spec.maximumWeight);
- checkArgument(spec.maximumSize == null, "maximum size was already set to ", spec.maximumSize);
+ spec.maximumWeight == null, "maximum weight was already set to %s", spec.maximumWeight);
+ checkArgument(
+ spec.maximumSize == null, "maximum size was already set to %s", spec.maximumSize);
spec.maximumWeight = value;
}
}
@@ -362,7 +364,7 @@ public final class CacheBuilderSpec {
protected void parseInteger(CacheBuilderSpec spec, int value) {
checkArgument(
spec.concurrencyLevel == null,
- "concurrency level was already set to ",
+ "concurrency level was already set to %s",
spec.concurrencyLevel);
spec.concurrencyLevel = value;
}
diff --git a/guava/src/com/google/common/cache/CacheLoader.java b/guava/src/com/google/common/cache/CacheLoader.java
index 7a5e017d0..1401595c7 100644
--- a/guava/src/com/google/common/cache/CacheLoader.java
+++ b/guava/src/com/google/common/cache/CacheLoader.java
@@ -23,10 +23,8 @@ import com.google.common.base.Supplier;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
-import com.google.errorprone.annotations.CheckReturnValue;
import java.io.Serializable;
import java.util.Map;
-import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
/**
@@ -134,10 +132,11 @@ public abstract class CacheLoader<K, V> {
* Returns a cache loader that uses {@code function} to load keys, without supporting either
* reloading or bulk loading. This allows creating a cache loader using a lambda expression.
*
+ * <p>The returned object is serializable if {@code function} is serializable.
+ *
* @param function the function to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by passing each key to {@code function}
*/
- @CheckReturnValue
public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
return new FunctionToCacheLoader<>(function);
}
@@ -147,13 +146,14 @@ public abstract class CacheLoader<K, V> {
* to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
+ * <p>The returned object is serializable if {@code supplier} is serializable.
+ *
* @param supplier the supplier to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
* key
*/
- @CheckReturnValue
public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
- return new SupplierToCacheLoader<V>(supplier);
+ return new SupplierToCacheLoader<>(supplier);
}
private static final class FunctionToCacheLoader<K, V> extends CacheLoader<K, V>
@@ -181,7 +181,6 @@ public abstract class CacheLoader<K, V> {
*
* @since 17.0
*/
- @CheckReturnValue
@GwtIncompatible // Executor + Futures
public static <K, V> CacheLoader<K, V> asyncReloading(
final CacheLoader<K, V> loader, final Executor executor) {
@@ -194,15 +193,9 @@ public abstract class CacheLoader<K, V> {
}
@Override
- public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
+ public ListenableFuture<V> reload(final K key, final V oldValue) {
ListenableFutureTask<V> task =
- ListenableFutureTask.create(
- new Callable<V>() {
- @Override
- public V call() throws Exception {
- return loader.reload(key, oldValue).get();
- }
- });
+ ListenableFutureTask.create(() -> loader.reload(key, oldValue).get());
executor.execute(task);
return task;
}
diff --git a/guava/src/com/google/common/cache/CacheStats.java b/guava/src/com/google/common/cache/CacheStats.java
index 8307e942a..3ca54e12e 100644
--- a/guava/src/com/google/common/cache/CacheStats.java
+++ b/guava/src/com/google/common/cache/CacheStats.java
@@ -151,8 +151,8 @@ public final class CacheStats {
/**
* Returns the total number of times that {@link Cache} lookup methods attempted to load new
- * values. This includes both successful load operations, as well as those that threw exceptions.
- * This is defined as {@code loadSuccessCount + loadExceptionCount}.
+ * values. This includes both successful load operations and those that threw exceptions. This is
+ * defined as {@code loadSuccessCount + loadExceptionCount}.
*
* <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
* guaranteed not to throw an exception). If you require specific handling, we recommend
diff --git a/guava/src/com/google/common/cache/ForwardingLoadingCache.java b/guava/src/com/google/common/cache/ForwardingLoadingCache.java
index ecd44ca8d..d98e2a627 100644
--- a/guava/src/com/google/common/cache/ForwardingLoadingCache.java
+++ b/guava/src/com/google/common/cache/ForwardingLoadingCache.java
@@ -17,6 +17,7 @@ package com.google.common.cache;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.ExecutionException;
/**
@@ -41,16 +42,19 @@ public abstract class ForwardingLoadingCache<K, V> extends ForwardingCache<K, V>
@Override
protected abstract LoadingCache<K, V> delegate();
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V get(K key) throws ExecutionException {
return delegate().get(key);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V getUnchecked(K key) {
return delegate().getUnchecked(key);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return delegate().getAll(keys);
diff --git a/guava/src/com/google/common/cache/LoadingCache.java b/guava/src/com/google/common/cache/LoadingCache.java
index e338ac4c3..a782aef55 100644
--- a/guava/src/com/google/common/cache/LoadingCache.java
+++ b/guava/src/com/google/common/cache/LoadingCache.java
@@ -19,6 +19,7 @@ import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
@@ -67,6 +68,7 @@ public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
* value
* @throws ExecutionError if an error was thrown while loading the value
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
V get(K key) throws ExecutionException;
/**
@@ -93,6 +95,7 @@ public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
* explained in the last paragraph above, this should be an unchecked exception only.)
* @throws ExecutionError if an error was thrown while loading the value
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
V getUnchecked(K key);
/**
@@ -119,6 +122,7 @@ public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
* @throws ExecutionError if an error was thrown while loading the values
* @since 11.0
*/
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException;
/**
diff --git a/guava/src/com/google/common/cache/LocalCache.java b/guava/src/com/google/common/cache/LocalCache.java
index f2cbee3db..00fb43575 100644
--- a/guava/src/com/google/common/cache/LocalCache.java
+++ b/guava/src/com/google/common/cache/LocalCache.java
@@ -49,10 +49,13 @@ import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.Uninterruptibles;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import java.io.IOException;
+import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
@@ -67,7 +70,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
@@ -85,6 +87,7 @@ import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -234,13 +237,13 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
final StatsCounter globalStatsCounter;
/** The default cache loader to use on loading operations. */
- final @Nullable CacheLoader<? super K, V> defaultLoader;
+ @CheckForNull final CacheLoader<? super K, V> defaultLoader;
/**
* Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
*/
LocalCache(
- CacheBuilder<? super K, ? super V> builder, @Nullable CacheLoader<? super K, V> loader) {
+ CacheBuilder<? super K, ? super V> builder, @CheckForNull CacheLoader<? super K, V> loader) {
concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS);
keyStrength = builder.getKeyStrength();
@@ -258,8 +261,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
removalListener = builder.getRemovalListener();
removalNotificationQueue =
(removalListener == NullListener.INSTANCE)
- ? LocalCache.<RemovalNotification<K, V>>discardingQueue()
- : new ConcurrentLinkedQueue<RemovalNotification<K, V>>();
+ ? LocalCache.discardingQueue()
+ : new ConcurrentLinkedQueue<>();
ticker = builder.getTicker(recordsTime());
entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries());
@@ -444,21 +447,24 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
STRONG {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongEntry<>(key, hash, next);
}
},
STRONG_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongAccessEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
@@ -466,14 +472,17 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
STRONG_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongWriteEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
@@ -481,14 +490,17 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
STRONG_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongAccessWriteEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
@@ -497,21 +509,24 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
WEAK {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakEntry<>(segment.keyReferenceQueue, key, hash, next);
}
},
WEAK_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakAccessEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
@@ -519,14 +534,17 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
WEAK_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakWriteEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
@@ -534,14 +552,17 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
WEAK_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakAccessWriteEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
+ Segment<K, V> segment,
+ ReferenceEntry<K, V> original,
+ ReferenceEntry<K, V> newNext,
+ K key) {
+ ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
@@ -584,18 +605,23 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* @param next entry in the same bucket
*/
abstract <K, V> ReferenceEntry<K, V> newEntry(
- Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next);
+ Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next);
/**
* Copies an entry, assigning it a new {@code next} entry.
*
- * @param original the entry to copy
+ * @param original the entry to copy. But avoid calling {@code getKey} on it: Instead, use the
+ * {@code key} parameter. That way, we prevent the key from being garbage collected in the
+ * case of weak keys. If we create a new entry with a key that is null at construction time,
+ * we're not sure if entry will necessarily ever be garbage collected.
* @param newNext entry in the same bucket
+ * @param key the key to copy from the original entry to the new one. Use this in preference to
+ * {@code original.getKey()}.
*/
// Guarded By Segment.this
<K, V> ReferenceEntry<K, V> copyEntry(
- Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- return newEntry(segment, original.getKey(), original.getHash(), newNext);
+ Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) {
+ return newEntry(segment, key, original.getHash(), newNext);
}
// Guarded By Segment.this
@@ -626,7 +652,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/** A reference to a value. */
interface ValueReference<K, V> {
/** Returns the value. Does not block or throw exceptions. */
- @Nullable
+ @CheckForNull
V get();
/**
@@ -645,7 +671,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Returns the entry associated with this value reference, or {@code null} if this value
* reference is independent of any entry.
*/
- @Nullable
+ @CheckForNull
ReferenceEntry<K, V> getEntry();
/**
@@ -654,17 +680,17 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* <p>{@code value} may be null only for a loading reference.
*/
ValueReference<K, V> copyFor(
- ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry);
+ ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry);
/**
* Notify pending loads that a new value was set. This is only relevant to loading value
* references.
*/
- void notifyNewValue(@Nullable V newValue);
+ void notifyNewValue(@CheckForNull V newValue);
/**
- * Returns true if a new value is currently loading, regardless of whether or not there is an
- * existing value. It is assumed that the return value of this method is constant for any given
+ * Returns true if a new value is currently loading, regardless of whether there is an existing
+ * value. It is assumed that the return value of this method is constant for any given
* ValueReference instance.
*/
boolean isLoading();
@@ -682,6 +708,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/** Placeholder. Indicates that the value hasn't been set yet. */
static final ValueReference<Object, Object> UNSET =
new ValueReference<Object, Object>() {
+ @CheckForNull
@Override
public Object get() {
return null;
@@ -692,6 +719,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return 0;
}
+ @CheckForNull
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
@@ -700,7 +728,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public ValueReference<Object, Object> copyFor(
ReferenceQueue<Object> queue,
- @Nullable Object value,
+ @CheckForNull Object value,
ReferenceEntry<Object, Object> entry) {
return this;
}
@@ -715,6 +743,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return false;
}
+ @CheckForNull
@Override
public Object waitForValue() {
return null;
@@ -733,6 +762,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
+ @CheckForNull
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
@@ -741,6 +771,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
+ @CheckForNull
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
@@ -751,6 +782,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return 0;
}
+ @CheckForNull
@Override
public Object getKey() {
return null;
@@ -904,11 +936,13 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return true;
}
+ @CheckForNull
@Override
public Object peek() {
return null;
}
+ @CheckForNull
@Override
public Object poll() {
return null;
@@ -943,7 +977,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
static class StrongEntry<K, V> extends AbstractReferenceEntry<K, V> {
final K key;
- StrongEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ StrongEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
this.key = key;
this.hash = hash;
this.next = next;
@@ -957,7 +991,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// The code below is exactly the same for each entry type.
final int hash;
- final @Nullable ReferenceEntry<K, V> next;
+ @CheckForNull final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
@@ -982,7 +1016,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
static final class StrongAccessEntry<K, V> extends StrongEntry<K, V> {
- StrongAccessEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ StrongAccessEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
@@ -1028,7 +1062,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
static final class StrongWriteEntry<K, V> extends StrongEntry<K, V> {
- StrongWriteEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ StrongWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
@@ -1074,7 +1108,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
static final class StrongAccessWriteEntry<K, V> extends StrongEntry<K, V> {
- StrongAccessWriteEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ StrongAccessWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
@@ -1161,7 +1195,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/** Used for weakly-referenced keys. */
static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> {
- WeakEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ WeakEntry(ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
@@ -1244,7 +1278,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// The code below is exactly the same for each entry type.
final int hash;
- final @Nullable ReferenceEntry<K, V> next;
+ @CheckForNull final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
@@ -1269,7 +1303,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
static final class WeakAccessEntry<K, V> extends WeakEntry<K, V> {
- WeakAccessEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ WeakAccessEntry(
+ ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
@@ -1315,7 +1350,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
static final class WeakWriteEntry<K, V> extends WeakEntry<K, V> {
- WeakWriteEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ WeakWriteEntry(
+ ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
@@ -1362,7 +1398,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
static final class WeakAccessWriteEntry<K, V> extends WeakEntry<K, V> {
WeakAccessWriteEntry(
- ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
@@ -1666,7 +1702,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* This method is a convenience for testing. Code should call {@link Segment#newEntry} directly.
*/
@VisibleForTesting
- ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
Segment<K, V> segment = segmentFor(hash);
segment.lock();
try {
@@ -1697,7 +1733,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return valueStrength.referenceValue(segmentFor(hash), entry, checkNotNull(value), weight);
}
- int hash(@Nullable Object key) {
+ int hash(@CheckForNull Object key) {
int h = keyEquivalence.hash(key);
return rehash(h);
}
@@ -1740,11 +1776,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
- * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to
- * cleanup stale entries. As such it should only be called outside of a segment context, such as
- * during iteration.
+ * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean
+ * up stale entries. As such it should only be called outside a segment context, such as during
+ * iteration.
*/
- @Nullable
+ @CheckForNull
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
return null;
@@ -1889,7 +1925,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
int threshold;
/** The per-segment table. */
- volatile @Nullable AtomicReferenceArray<ReferenceEntry<K, V>> table;
+ @CheckForNull volatile AtomicReferenceArray<ReferenceEntry<K, V>> table;
/** The maximum weight of this segment. UNSET_INT if there is no maximum. */
final long maxSegmentWeight;
@@ -1898,13 +1934,13 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* The key reference queue contains entries whose keys have been garbage collected, and which
* need to be cleaned up internally.
*/
- final @Nullable ReferenceQueue<K> keyReferenceQueue;
+ @CheckForNull final ReferenceQueue<K> keyReferenceQueue;
/**
* The value reference queue contains value references whose values have been garbage collected,
* and which need to be cleaned up internally.
*/
- final @Nullable ReferenceQueue<V> valueReferenceQueue;
+ @CheckForNull final ReferenceQueue<V> valueReferenceQueue;
/**
* The recency queue is used to record which entries were accessed for updating the access
@@ -1946,24 +1982,16 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
this.statsCounter = checkNotNull(statsCounter);
initTable(newEntryArray(initialCapacity));
- keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<K>() : null;
+ keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null;
- valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<V>() : null;
+ valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null;
recencyQueue =
- map.usesAccessQueue()
- ? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
- : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
+ map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue();
- writeQueue =
- map.usesWriteQueue()
- ? new WriteQueue<K, V>()
- : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
+ writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue();
- accessQueue =
- map.usesAccessQueue()
- ? new AccessQueue<K, V>()
- : LocalCache.<ReferenceEntry<K, V>>discardingQueue();
+ accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
@@ -1980,7 +2008,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@GuardedBy("this")
- ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
+ ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return map.entryFactory.newEntry(this, checkNotNull(key), hash, next);
}
@@ -1988,9 +2016,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
+ @CheckForNull
@GuardedBy("this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
- if (original.getKey() == null) {
+ K key = original.getKey();
+ if (key == null) {
// key collected
return null;
}
@@ -2002,7 +2032,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return null;
}
- ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext);
+ ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext, key);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
@@ -2023,6 +2053,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// loading
+ @CanIgnoreReturnValue
V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
checkNotNull(key);
checkNotNull(loader);
@@ -2060,7 +2091,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
- @Nullable
+ @CheckForNull
V get(Object key, int hash) {
try {
if (count != 0) { // read-volatile
@@ -2214,7 +2245,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
valueReference = e.getValueReference();
if (map.isExpired(e, now)) {
// This is a duplicate check, as preWriteCleanup already purged expired
- // entries, but let's accomodate an incorrect expiration queue.
+ // entries, but let's accommodate an incorrect expiration queue.
enqueueNotification(
entryKey,
hash,
@@ -2290,15 +2321,12 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
CacheLoader<? super K, V> loader) {
final ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
loadingFuture.addListener(
- new Runnable() {
- @Override
- public void run() {
- try {
- getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
- } catch (Throwable t) {
- logger.log(Level.WARNING, "Exception thrown during refresh", t);
- loadingValueReference.setException(t);
- }
+ () -> {
+ try {
+ getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
+ } catch (Throwable t) {
+ logger.log(Level.WARNING, "Exception thrown during refresh", t);
+ loadingValueReference.setException(t);
}
},
directExecutor());
@@ -2306,6 +2334,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
/** Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats. */
+ @CanIgnoreReturnValue
V getAndRecordStats(
K key,
int hash,
@@ -2353,7 +2382,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* {@code null} if another thread is performing the refresh or if an error occurs during
* refresh.
*/
- @Nullable
+ @CanIgnoreReturnValue
+ @CheckForNull
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
final LoadingValueReference<K, V> loadingValueReference =
insertLoadingValueReference(key, hash, checkTime);
@@ -2376,7 +2406,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Returns a newly inserted {@code LoadingValueReference}, or null if the live value reference
* is already loading.
*/
- @Nullable
+ @CheckForNull
LoadingValueReference<K, V> insertLoadingValueReference(
final K key, final int hash, boolean checkTime) {
ReferenceEntry<K, V> e = null;
@@ -2564,7 +2594,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
- // all of the segment's entries.
+ // all the segment's entries.
if (accessQueue.contains(e)) {
accessQueue.add(e);
}
@@ -2606,7 +2636,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@GuardedBy("this")
void enqueueNotification(
- @Nullable K key, int hash, @Nullable V value, int weight, RemovalCause cause) {
+ @CheckForNull K key, int hash, @CheckForNull V value, int weight, RemovalCause cause) {
totalWeight -= weight;
if (cause.wasEvicted()) {
statsCounter.recordEviction();
@@ -2668,7 +2698,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// Specialized implementations of map methods
- @Nullable
+ @CheckForNull
ReferenceEntry<K, V> getEntry(Object key, int hash) {
for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) {
if (e.getHash() != hash) {
@@ -2689,7 +2719,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return null;
}
- @Nullable
+ @CheckForNull
ReferenceEntry<K, V> getLiveEntry(Object key, int hash, long now) {
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e == null) {
@@ -2770,7 +2800,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
- @Nullable
+ @CanIgnoreReturnValue
+ @CheckForNull
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
@@ -2976,7 +3007,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
- @Nullable
+ @CheckForNull
V replace(K key, int hash, V newValue) {
lock();
try {
@@ -3031,7 +3062,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
- @Nullable
+ @CheckForNull
V remove(Object key, int hash) {
lock();
try {
@@ -3124,6 +3155,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
+ @CanIgnoreReturnValue
boolean storeLoadedValue(
K key, int hash, LoadingValueReference<K, V> oldValueReference, V newValue) {
lock();
@@ -3223,11 +3255,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@GuardedBy("this")
- @Nullable
+ @CheckForNull
ReferenceEntry<K, V> removeValueFromChain(
ReferenceEntry<K, V> first,
ReferenceEntry<K, V> entry,
- @Nullable K key,
+ @CheckForNull K key,
int hash,
V value,
ValueReference<K, V> valueReference,
@@ -3245,7 +3277,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@GuardedBy("this")
- @Nullable
+ @CheckForNull
ReferenceEntry<K, V> removeEntryFromChain(
ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) {
int newCount = count;
@@ -3276,6 +3308,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
/** Removes an entry whose key has been garbage collected. */
+ @CanIgnoreReturnValue
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
@@ -3311,6 +3344,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
/** Removes an entry whose value has been garbage collected. */
+ @CanIgnoreReturnValue
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
@@ -3348,12 +3382,13 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return false;
} finally {
unlock();
- if (!isHeldByCurrentThread()) { // don't cleanup inside of put
+ if (!isHeldByCurrentThread()) { // don't clean up inside of put
postWriteCleanup();
}
}
}
+ @CanIgnoreReturnValue
boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) {
lock();
try {
@@ -3389,6 +3424,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@VisibleForTesting
@GuardedBy("this")
+ @CanIgnoreReturnValue
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
@@ -3481,7 +3517,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
public LoadingValueReference(ValueReference<K, V> oldValue) {
- this.oldValue = (oldValue == null) ? LocalCache.<K, V>unset() : oldValue;
+ this.oldValue = (oldValue == null) ? LocalCache.unset() : oldValue;
}
@Override
@@ -3499,10 +3535,12 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return oldValue.getWeight();
}
- public boolean set(@Nullable V newValue) {
+ @CanIgnoreReturnValue
+ public boolean set(@CheckForNull V newValue) {
return futureValue.set(newValue);
}
+ @CanIgnoreReturnValue
public boolean setException(Throwable t) {
return futureValue.setException(t);
}
@@ -3512,7 +3550,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public void notifyNewValue(@Nullable V newValue) {
+ public void notifyNewValue(@CheckForNull V newValue) {
if (newValue != null) {
// The pending load was clobbered by a manual write.
// Unblock all pending gets, and have them return the new value.
@@ -3541,12 +3579,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// *before* returning newValue from the cache query.
return transform(
newValue,
- new com.google.common.base.Function<V, V>() {
- @Override
- public V apply(V newValue) {
- LoadingValueReference.this.set(newValue);
- return newValue;
- }
+ newResult -> {
+ LoadingValueReference.this.set(newResult);
+ return newResult;
},
directExecutor());
} catch (Throwable t) {
@@ -3602,7 +3637,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public ValueReference<K, V> copyFor(
- ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry) {
+ ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry) {
return this;
}
}
@@ -3682,12 +3717,14 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return true;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
return (next == head) ? null : next;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
@@ -3701,6 +3738,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
@SuppressWarnings("unchecked")
+ @CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInWriteQueue();
@@ -3750,6 +3788,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
+ @CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInWriteQueue();
@@ -3821,12 +3860,14 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return true;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
return (next == head) ? null : next;
}
+ @CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
@@ -3840,6 +3881,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
@SuppressWarnings("unchecked")
+ @CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInAccessQueue();
@@ -3889,6 +3931,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
+ @CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInAccessQueue();
@@ -3919,19 +3962,19 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].count != 0) {
+ for (Segment<K, V> segment : segments) {
+ if (segment.count != 0) {
return false;
}
- sum += segments[i].modCount;
+ sum += segment.modCount;
}
if (sum != 0L) { // recheck unless no modifications
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].count != 0) {
+ for (Segment<K, V> segment : segments) {
+ if (segment.count != 0) {
return false;
}
- sum -= segments[i].modCount;
+ sum -= segment.modCount;
}
return sum == 0L;
}
@@ -3941,8 +3984,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
long longSize() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
- for (int i = 0; i < segments.length; ++i) {
- sum += segments[i].count;
+ for (Segment<K, V> segment : segments) {
+ sum += segment.count;
}
return sum;
}
@@ -3952,8 +3995,10 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return Ints.saturatedCast(longSize());
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
- public @Nullable V get(@Nullable Object key) {
+ @CheckForNull
+ public V get(@CheckForNull Object key) {
if (key == null) {
return null;
}
@@ -3961,12 +4006,14 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).get(key, hash);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).get(key, hash, loader);
}
- public @Nullable V getIfPresent(Object key) {
+ @CheckForNull
+ public V getIfPresent(Object key) {
int hash = hash(checkNotNull(key));
V value = segmentFor(hash).get(key, hash);
if (value == null) {
@@ -3977,10 +4024,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return value;
}
- // Only becomes available in Java 8 when it's on the interface.
- // @Override
@Override
- public @Nullable V getOrDefault(@Nullable Object key, @Nullable V defaultValue) {
+ @CheckForNull
+ public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
V result = get(key);
return (result != null) ? result : defaultValue;
}
@@ -4060,7 +4106,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't
* implement {@code loadAll}.
*/
- @Nullable
+ @CheckForNull
Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader)
throws ExecutionException {
checkNotNull(loader);
@@ -4124,7 +4170,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
* Returns the internal entry for the specified key. The entry may be loading, expired, or
* partially collected.
*/
- ReferenceEntry<K, V> getEntry(@Nullable Object key) {
+ @CheckForNull
+ ReferenceEntry<K, V> getEntry(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
return null;
@@ -4139,7 +4186,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public boolean containsKey(@Nullable Object key) {
+ public boolean containsKey(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
return false;
@@ -4149,7 +4196,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public boolean containsValue(@Nullable Object value) {
+ public boolean containsValue(@CheckForNull Object value) {
// does not impact recency ordering
if (value == null) {
return false;
@@ -4188,6 +4235,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return false;
}
+ @CheckForNull
+ @CanIgnoreReturnValue
@Override
public V put(K key, V value) {
checkNotNull(key);
@@ -4196,6 +4245,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).put(key, hash, value, false);
}
+ @CheckForNull
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
@@ -4227,7 +4277,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public V merge(K key, V newValue, BiFunction<? super V, ? super V, ? extends V> function) {
+ @CheckForNull
+ public V merge(
+ K key, V newValue, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
checkNotNull(key);
checkNotNull(newValue);
checkNotNull(function);
@@ -4242,8 +4294,10 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
+ @CheckForNull
+ @CanIgnoreReturnValue
@Override
- public V remove(@Nullable Object key) {
+ public V remove(@CheckForNull Object key) {
if (key == null) {
return null;
}
@@ -4251,8 +4305,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).remove(key, hash);
}
+ @CanIgnoreReturnValue
@Override
- public boolean remove(@Nullable Object key, @Nullable Object value) {
+ public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
if (key == null || value == null) {
return false;
}
@@ -4260,8 +4315,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).remove(key, hash, value);
}
+ @CanIgnoreReturnValue
@Override
- public boolean replace(K key, @Nullable V oldValue, V newValue) {
+ public boolean replace(K key, @CheckForNull V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
@@ -4271,6 +4327,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
+ @CheckForNull
+ @CanIgnoreReturnValue
@Override
public V replace(K key, V value) {
checkNotNull(key);
@@ -4293,7 +4351,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
}
- @RetainedWith @Nullable Set<K> keySet;
+ @LazyInit @RetainedWith @CheckForNull Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -4302,7 +4360,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return (ks != null) ? ks : (keySet = new KeySet());
}
- @RetainedWith @Nullable Collection<V> values;
+ @LazyInit @RetainedWith @CheckForNull Collection<V> values;
@Override
public Collection<V> values() {
@@ -4311,7 +4369,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return (vs != null) ? vs : (values = new Values());
}
- @RetainedWith @Nullable Set<Entry<K, V>> entrySet;
+ @LazyInit @RetainedWith @CheckForNull Set<Entry<K, V>> entrySet;
@Override
@GwtIncompatible // Not supported.
@@ -4327,11 +4385,11 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
int nextSegmentIndex;
int nextTableIndex;
- @Nullable Segment<K, V> currentSegment;
- @Nullable AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
- @Nullable ReferenceEntry<K, V> nextEntry;
- @Nullable WriteThroughEntry nextExternal;
- @Nullable WriteThroughEntry lastReturned;
+ @CheckForNull Segment<K, V> currentSegment;
+ @CheckForNull AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
+ @CheckForNull ReferenceEntry<K, V> nextEntry;
+ @CheckForNull WriteThroughEntry nextExternal;
+ @CheckForNull WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
@@ -4472,7 +4530,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public boolean equals(@Nullable Object object) {
+ public boolean equals(@CheckForNull Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
@@ -4540,7 +4598,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
private static <E> ArrayList<E> toArrayList(Collection<E> c) {
// Avoid calling ArrayList(Collection), which may call back into toArray.
- ArrayList<E> result = new ArrayList<E>(c.size());
+ ArrayList<E> result = new ArrayList<>(c.size());
Iterators.addAll(result, c.iterator());
return result;
}
@@ -4689,10 +4747,10 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
final Weigher<K, V> weigher;
final int concurrencyLevel;
final RemovalListener<? super K, ? super V> removalListener;
- final @Nullable Ticker ticker;
+ @CheckForNull final Ticker ticker;
final CacheLoader<? super K, V> loader;
- transient @Nullable Cache<K, V> delegate;
+ @CheckForNull transient Cache<K, V> delegate;
ManualSerializationProxy(LocalCache<K, V> cache) {
this(
@@ -4754,7 +4812,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
builder.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (weigher != OneWeigher.INSTANCE) {
- builder.weigher(weigher);
+ Object unused = builder.weigher(weigher);
if (maxWeight != UNSET_INT) {
builder.maximumWeight(maxWeight);
}
@@ -4797,7 +4855,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
implements LoadingCache<K, V>, Serializable {
private static final long serialVersionUID = 1;
- transient @Nullable LoadingCache<K, V> autoDelegate;
+ @CheckForNull transient LoadingCache<K, V> autoDelegate;
LoadingSerializationProxy(LocalCache<K, V> cache) {
super(cache);
@@ -4825,7 +4883,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
}
@Override
- public final V apply(K key) {
+ public V apply(K key) {
return autoDelegate.apply(key);
}
@@ -4843,7 +4901,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
final LocalCache<K, V> localCache;
LocalManualCache(CacheBuilder<? super K, ? super V> builder) {
- this(new LocalCache<K, V>(builder, null));
+ this(new LocalCache<>(builder, null));
}
private LocalManualCache(LocalCache<K, V> localCache) {
@@ -4853,7 +4911,8 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
// Cache methods
@Override
- public @Nullable V getIfPresent(Object key) {
+ @CheckForNull
+ public V getIfPresent(Object key) {
return localCache.getIfPresent(key);
}
@@ -4933,6 +4992,10 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
Object writeReplace() {
return new ManualSerializationProxy<>(localCache);
}
+
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use ManualSerializationProxy");
+ }
}
static class LocalLoadingCache<K, V> extends LocalManualCache<K, V>
@@ -4940,7 +5003,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
LocalLoadingCache(
CacheBuilder<? super K, ? super V> builder, CacheLoader<? super K, V> loader) {
- super(new LocalCache<K, V>(builder, checkNotNull(loader)));
+ super(new LocalCache<>(builder, checkNotNull(loader)));
}
// LoadingCache methods
@@ -4950,6 +5013,7 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
return localCache.getOrLoad(key);
}
+ @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V getUnchecked(K key) {
try {
@@ -4982,5 +5046,9 @@ class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
Object writeReplace() {
return new LoadingSerializationProxy<>(localCache);
}
+
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use LoadingSerializationProxy");
+ }
}
}
diff --git a/guava/src/com/google/common/cache/ParametricNullness.java b/guava/src/com/google/common/cache/ParametricNullness.java
index 64682de55..eaf194d4a 100644
--- a/guava/src/com/google/common/cache/ParametricNullness.java
+++ b/guava/src/com/google/common/cache/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/cache/package-info.java b/guava/src/com/google/common/cache/package-info.java
index a7791de49..fc678d44a 100644
--- a/guava/src/com/google/common/cache/package-info.java
+++ b/guava/src/com/google/common/cache/package-info.java
@@ -13,23 +13,24 @@
*/
/**
- * This package contains caching utilities.
+ * <a href="https://guava.dev/CacheBuilder">Discouraged</a> (in favor of <a
+ * href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>) caching utilities.
*
- * <p>The core interface used to represent caches is {@link com.google.common.cache.Cache}.
- * In-memory caches can be configured and created using {@link
- * com.google.common.cache.CacheBuilder}, with cache entries being loaded by {@link
- * com.google.common.cache.CacheLoader}. Statistics about cache performance are exposed using {@link
- * com.google.common.cache.CacheStats}.
+ * <p>The core interface used to represent caches is {@link Cache}. In-memory caches can be
+ * configured and created using {@link CacheBuilder}, with cache entries being loaded by {@link
+ * CacheLoader}. Statistics about cache performance are exposed using {@link CacheStats}.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/CachesExplained">caches</a>.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* @author Charles Fry
*/
+@CheckReturnValue
@ParametersAreNonnullByDefault
package com.google.common.cache;
+import com.google.errorprone.annotations.CheckReturnValue;
import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/guava/src/com/google/common/collect/AbstractBiMap.java b/guava/src/com/google/common/collect/AbstractBiMap.java
index 9b2ad2af5..0563ea0e8 100644
--- a/guava/src/com/google/common/collect/AbstractBiMap.java
+++ b/guava/src/com/google/common/collect/AbstractBiMap.java
@@ -22,8 +22,10 @@ import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
@@ -52,8 +54,12 @@ import org.checkerframework.checker.nullness.qual.Nullable;
abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
+ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (lateinit)
private transient Map<K, V> delegate;
- @RetainedWith transient AbstractBiMap<V, K> inverse;
+
+ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (lateinit)
+ @RetainedWith
+ transient AbstractBiMap<V, K> inverse;
/** Package-private constructor for creating a map-backed bimap. */
AbstractBiMap(Map<K, V> forward, Map<V, K> backward) {
@@ -225,7 +231,7 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
return inverse;
}
- @CheckForNull private transient Set<K> keySet;
+ @LazyInit @CheckForNull private transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -270,7 +276,7 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- @CheckForNull private transient Set<V> valueSet;
+ @LazyInit @CheckForNull private transient Set<V> valueSet;
@Override
public Set<V> values() {
@@ -313,7 +319,7 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
}
- @CheckForNull private transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -422,15 +428,8 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
// See java.util.Collections.CheckedEntrySet for details on attacks.
@Override
- public Object[] toArray() {
- /*
- * standardToArray returns `@Nullable Object[]` rather than `Object[]` but only because it can
- * be used with collections that may contain null. This collection never contains nulls, so we
- * can treat it as a plain `Object[]`.
- */
- @SuppressWarnings("nullness")
- Object[] result = standardToArray();
- return result;
+ public @Nullable Object[] toArray() {
+ return standardToArray();
}
@Override
@@ -488,14 +487,18 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
return inverse.checkKey(value);
}
- /** @serialData the forward bimap */
+ /**
+ * @serialData the forward bimap
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(inverse());
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -503,14 +506,17 @@ abstract class AbstractBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
@GwtIncompatible // Not needed in the emulated source.
+ @J2ktIncompatible
Object readResolve() {
return inverse().inverse();
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/AbstractIterator.java b/guava/src/com/google/common/collect/AbstractIterator.java
index 66273f438..aa01300be 100644
--- a/guava/src/com/google/common/collect/AbstractIterator.java
+++ b/guava/src/com/google/common/collect/AbstractIterator.java
@@ -127,7 +127,6 @@ public abstract class AbstractIterator<T extends @Nullable Object> extends Unmod
return null;
}
- @CanIgnoreReturnValue // TODO(kak): Should we remove this? Some people are using it to prefetch?
@Override
public final boolean hasNext() {
checkState(state != State.FAILED);
diff --git a/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java b/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
index 4c5a0f041..1e48281bf 100644
--- a/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
+++ b/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
@@ -1188,6 +1188,7 @@ abstract class AbstractMapBasedMultimap<K extends @Nullable Object, V extends @N
}
@Override
+ @ParametricNullness
public T next() {
if (!valueIterator.hasNext()) {
Entry<K, Collection<V>> mapEntry = keyIterator.next();
diff --git a/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java b/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
index b37214e02..2b055b12f 100644
--- a/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
+++ b/guava/src/com/google/common/collect/AbstractMapBasedMultiset.java
@@ -25,6 +25,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.InvalidObjectException;
@@ -344,10 +345,12 @@ abstract class AbstractMapBasedMultiset<E extends @Nullable Object> extends Abst
// Don't allow default serialization.
@GwtIncompatible // java.io.ObjectStreamException
+ @J2ktIncompatible
private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("Stream data required");
}
@GwtIncompatible // not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = -2250766705698539974L;
}
diff --git a/guava/src/com/google/common/collect/AbstractNavigableMap.java b/guava/src/com/google/common/collect/AbstractNavigableMap.java
index 47048d06a..fa68dc524 100644
--- a/guava/src/com/google/common/collect/AbstractNavigableMap.java
+++ b/guava/src/com/google/common/collect/AbstractNavigableMap.java
@@ -44,13 +44,13 @@ abstract class AbstractNavigableMap<K extends @Nullable Object, V extends @Nulla
@Override
@CheckForNull
public Entry<K, V> firstEntry() {
- return Iterators.getNext(entryIterator(), null);
+ return Iterators.<@Nullable Entry<K, V>>getNext(entryIterator(), null);
}
@Override
@CheckForNull
public Entry<K, V> lastEntry() {
- return Iterators.getNext(descendingEntryIterator(), null);
+ return Iterators.<@Nullable Entry<K, V>>getNext(descendingEntryIterator(), null);
}
@Override
diff --git a/guava/src/com/google/common/collect/AbstractSortedMultiset.java b/guava/src/com/google/common/collect/AbstractSortedMultiset.java
index 621e8f98a..98b6211a7 100644
--- a/guava/src/com/google/common/collect/AbstractSortedMultiset.java
+++ b/guava/src/com/google/common/collect/AbstractSortedMultiset.java
@@ -17,6 +17,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Comparator;
import java.util.Iterator;
@@ -122,7 +123,7 @@ abstract class AbstractSortedMultiset<E extends @Nullable Object> extends Abstra
return Multisets.iteratorImpl(descendingMultiset());
}
- @CheckForNull private transient SortedMultiset<E> descendingMultiset;
+ @LazyInit @CheckForNull private transient SortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
diff --git a/guava/src/com/google/common/collect/AllEqualOrdering.java b/guava/src/com/google/common/collect/AllEqualOrdering.java
index f6ca6faff..366044b01 100644
--- a/guava/src/com/google/common/collect/AllEqualOrdering.java
+++ b/guava/src/com/google/common/collect/AllEqualOrdering.java
@@ -43,8 +43,7 @@ final class AllEqualOrdering extends Ordering<@Nullable Object> implements Seria
}
@Override
- @SuppressWarnings("nullness") // unsafe: see supertype
- public <E extends @Nullable Object> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
+ public <E> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
return ImmutableList.copyOf(iterable);
}
diff --git a/guava/src/com/google/common/collect/ArrayListMultimap.java b/guava/src/com/google/common/collect/ArrayListMultimap.java
index e31f491f0..c0ed5571f 100644
--- a/guava/src/com/google/common/collect/ArrayListMultimap.java
+++ b/guava/src/com/google/common/collect/ArrayListMultimap.java
@@ -20,6 +20,7 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -155,12 +156,14 @@ public final class ArrayListMultimap<K extends @Nullable Object, V extends @Null
* key, number of values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
@@ -171,5 +174,6 @@ public final class ArrayListMultimap<K extends @Nullable Object, V extends @Null
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/ArrayTable.java b/guava/src/com/google/common/collect/ArrayTable.java
index 1fce76244..411ee6335 100644
--- a/guava/src/com/google/common/collect/ArrayTable.java
+++ b/guava/src/com/google/common/collect/ArrayTable.java
@@ -21,13 +21,13 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.emptyMap;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Objects;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.lang.reflect.Array;
@@ -89,7 +89,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jared Levy
* @since 10.0
*/
-@Beta
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
@@ -662,7 +661,7 @@ public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
return columnKeyToIndex.keySet();
}
- @CheckForNull private transient ColumnMap columnMap;
+ @LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, @Nullable V>> columnMap() {
@@ -757,7 +756,7 @@ public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
return rowKeyToIndex.keySet();
}
- @CheckForNull private transient RowMap rowMap;
+ @LazyInit @CheckForNull private transient RowMap rowMap;
@Override
public Map<R, Map<C, @Nullable V>> rowMap() {
diff --git a/guava/src/com/google/common/collect/BiMap.java b/guava/src/com/google/common/collect/BiMap.java
index 12eb4e3e1..d95a71eb7 100644
--- a/guava/src/com/google/common/collect/BiMap.java
+++ b/guava/src/com/google/common/collect/BiMap.java
@@ -28,6 +28,15 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* that of its keys. This constraint enables bimaps to support an "inverse view", which is another
* bimap containing the same entries as this bimap but with reversed keys and values.
*
+ * <h3>Implementations</h3>
+ *
+ * <ul>
+ * <li>{@link ImmutableBiMap}
+ * <li>{@link HashBiMap}
+ * <li>{@link EnumBiMap}
+ * <li>{@link EnumHashBiMap}
+ * </ul>
+ *
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">{@code BiMap}</a>.
*
diff --git a/guava/src/com/google/common/collect/ClassToInstanceMap.java b/guava/src/com/google/common/collect/ClassToInstanceMap.java
index 9bd826fd9..094a7fdd7 100644
--- a/guava/src/com/google/common/collect/ClassToInstanceMap.java
+++ b/guava/src/com/google/common/collect/ClassToInstanceMap.java
@@ -21,6 +21,8 @@ import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Map;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A map, each entry of which maps a Java <a href="http://tinyurl.com/2cmwkz">raw type</a> to an
@@ -30,43 +32,36 @@ import javax.annotation.CheckForNull;
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries for primitive types,
* and a primitive type and its corresponding wrapper type may map to different values.
*
- * <p>This class's support for {@code null} requires some explanation: From release 31.0 onward,
- * Guava specifies the nullness of its types through annotations. In the case of {@code
- * ClassToInstanceMap}, it specifies that both the key and value types are restricted to
- * non-nullable types. This specification is reasonable for <i>keys</i>, which must be non-null
- * classes. This is in contrast to the specification for <i>values</i>: Null values <i>are</i>
- * supported by the implementation {@link MutableClassToInstanceMap}, even though that
- * implementation and this interface specify otherwise. Thus, if you use a nullness checker, you can
- * safely suppress any warnings it produces when you write null values into a {@code
- * MutableClassToInstanceMap}. Just be sure to be prepared for null values when reading from it,
- * since nullness checkers will assume that vaules are non-null then, too.
+ * <h3>Implementations</h3>
*
- * <p>See the Guava User Guide article on <a href=
- * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
- * ClassToInstanceMap}</a>.
+ * <ul>
+ * <li>{@link ImmutableClassToInstanceMap}
+ * <li>{@link MutableClassToInstanceMap}
+ * </ul>
*
* <p>To map a generic type to an instance of that type, use {@link
* com.google.common.reflect.TypeToInstanceMap} instead.
*
- * @param <B> the common supertype that all entries must share; often this is simply {@link Object}
- * @author Kevin Bourrillion
+ * <p>See the Guava User Guide article on <a href=
+ * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
+ * ClassToInstanceMap}</a>.
+ *
+ * @param <B> the common supertype that all values will share. When in doubt, just use {@link
+ * Object}, or use {@code @Nullable Object} to allow null values.
* @since 2.0
*/
@DoNotMock("Use ImmutableClassToInstanceMap or MutableClassToInstanceMap")
@GwtCompatible
@ElementTypesAreNonnullByDefault
-// If we ever support non-null projections (https://github.com/jspecify/jspecify/issues/86), we
-// we might annotate this as...
-// ClassToInstanceMap<B extends @Nullable Object> extends Map<Class<? extends @Nonnull B>, B>
-// ...and change its methods similarly (<T extends @Nonnull B> or Class<@Nonnull T>).
-public interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B> {
+public interface ClassToInstanceMap<B extends @Nullable Object>
+ extends Map<Class<? extends @NonNull B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no entry for this class
* is present. This will only return a value that was bound to this specific class, not a value
* that may have been bound to a subtype.
*/
@CheckForNull
- <T extends B> T getInstance(Class<T> type);
+ <T extends @NonNull B> T getInstance(Class<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate this value with any
@@ -77,5 +72,5 @@ public interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B> {
*/
@CanIgnoreReturnValue
@CheckForNull
- <T extends B> T putInstance(Class<T> type, T value);
+ <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value);
}
diff --git a/guava/src/com/google/common/collect/CollectCollectors.java b/guava/src/com/google/common/collect/CollectCollectors.java
index f582660c8..e0982ab0f 100644
--- a/guava/src/com/google/common/collect/CollectCollectors.java
+++ b/guava/src/com/google/common/collect/CollectCollectors.java
@@ -17,10 +17,12 @@
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.collectingAndThen;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.Comparator;
@@ -95,16 +97,20 @@ final class CollectCollectors {
return (Collector) EnumSetAccumulator.TO_IMMUTABLE_ENUM_SET;
}
+ private static <E extends Enum<E>>
+ Collector<E, EnumSetAccumulator<E>, ImmutableSet<E>> toImmutableEnumSetGeneric() {
+ return Collector.of(
+ EnumSetAccumulator::new,
+ EnumSetAccumulator::add,
+ EnumSetAccumulator::combine,
+ EnumSetAccumulator::toImmutableSet,
+ Collector.Characteristics.UNORDERED);
+ }
+
private static final class EnumSetAccumulator<E extends Enum<E>> {
@SuppressWarnings({"rawtypes", "unchecked"})
static final Collector<Enum<?>, ?, ImmutableSet<? extends Enum<?>>> TO_IMMUTABLE_ENUM_SET =
- (Collector)
- Collector.<Enum, EnumSetAccumulator, ImmutableSet<?>>of(
- EnumSetAccumulator::new,
- EnumSetAccumulator::add,
- EnumSetAccumulator::combine,
- EnumSetAccumulator::toImmutableSet,
- Collector.Characteristics.UNORDERED);
+ (Collector) toImmutableEnumSetGeneric();
@CheckForNull private EnumSet<E> set;
@@ -128,7 +134,12 @@ final class CollectCollectors {
}
ImmutableSet<E> toImmutableSet() {
- return (set == null) ? ImmutableSet.<E>of() : ImmutableEnumSet.asImmutable(set);
+ if (set == null) {
+ return ImmutableSet.of();
+ }
+ ImmutableSet<E> ret = ImmutableEnumSet.asImmutable(set);
+ set = null; // subsequent manual manipulation of the accumulator mustn't affect ret
+ return ret;
}
}
@@ -249,6 +260,7 @@ final class CollectCollectors {
new Collector.Characteristics[0]);
}
+ @J2ktIncompatible
static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
Function<? super T, ? extends K> keyFunction,
@@ -277,6 +289,7 @@ final class CollectCollectors {
Collector.Characteristics.UNORDERED);
}
+ @J2ktIncompatible
static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
Function<? super T, ? extends K> keyFunction,
@@ -303,6 +316,7 @@ final class CollectCollectors {
EnumMapAccumulator::toImmutableMap);
}
+ @J2ktIncompatible
private static class EnumMapAccumulator<K extends Enum<K>, V> {
private final BinaryOperator<V> mergeFunction;
@CheckForNull private EnumMap<K, V> map = null;
@@ -313,9 +327,10 @@ final class CollectCollectors {
void put(K key, V value) {
if (map == null) {
- map = new EnumMap<>(key.getDeclaringClass());
+ map = new EnumMap<>(singletonMap(key, value));
+ } else {
+ map.merge(key, value, mergeFunction);
}
- map.merge(key, value, mergeFunction);
}
EnumMapAccumulator<K, V> combine(EnumMapAccumulator<K, V> other) {
diff --git a/guava/src/com/google/common/collect/Collections2.java b/guava/src/com/google/common/collect/Collections2.java
index eb928596a..91eb4562c 100644
--- a/guava/src/com/google/common/collect/Collections2.java
+++ b/guava/src/com/google/common/collect/Collections2.java
@@ -21,7 +21,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
@@ -380,7 +379,6 @@ public final class Collections2 {
* @throws NullPointerException if the specified iterable is null or has any null elements.
* @since 12.0
*/
- @Beta
public static <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(
Iterable<E> elements) {
return orderedPermutations(elements, Ordering.natural());
@@ -432,7 +430,6 @@ public final class Collections2 {
* the specified comparator is null.
* @since 12.0
*/
- @Beta
public static <E> Collection<List<E>> orderedPermutations(
Iterable<E> elements, Comparator<? super E> comparator) {
return new OrderedPermutationCollection<E>(elements, comparator);
@@ -594,7 +591,6 @@ public final class Collections2 {
* @throws NullPointerException if the specified collection is null or has any null elements.
* @since 12.0
*/
- @Beta
public static <E> Collection<List<E>> permutations(Collection<E> elements) {
return new PermutationCollection<E>(ImmutableList.copyOf(elements));
}
diff --git a/guava/src/com/google/common/collect/CompactHashMap.java b/guava/src/com/google/common/collect/CompactHashMap.java
index e40b05eda..c5cac7ca5 100644
--- a/guava/src/com/google/common/collect/CompactHashMap.java
+++ b/guava/src/com/google/common/collect/CompactHashMap.java
@@ -25,11 +25,13 @@ import static com.google.common.collect.NullnessCasts.unsafeNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.InvalidObjectException;
@@ -687,7 +689,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
}
- @CheckForNull private transient Set<K> keySetView;
+ @LazyInit @CheckForNull private transient Set<K> keySetView;
@Override
public Set<K> keySet() {
@@ -797,7 +799,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
}
- @CheckForNull private transient Set<Entry<K, V>> entrySetView;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySetView;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -980,7 +982,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
return false;
}
- @CheckForNull private transient Collection<V> valuesView;
+ @LazyInit @CheckForNull private transient Collection<V> valuesView;
@Override
public Collection<V> values() {
@@ -1116,6 +1118,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
}
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
@@ -1128,6 +1131,7 @@ class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
}
@SuppressWarnings("unchecked")
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
diff --git a/guava/src/com/google/common/collect/CompactHashSet.java b/guava/src/com/google/common/collect/CompactHashSet.java
index 2cfcf0a13..dc3c76934 100644
--- a/guava/src/com/google/common/collect/CompactHashSet.java
+++ b/guava/src/com/google/common/collect/CompactHashSet.java
@@ -23,6 +23,7 @@ import static com.google.common.collect.Hashing.smearedHash;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
@@ -698,6 +699,7 @@ class CompactHashSet<E extends @Nullable Object> extends AbstractSet<E> implemen
}
}
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
@@ -707,6 +709,7 @@ class CompactHashSet<E extends @Nullable Object> extends AbstractSet<E> implemen
}
@SuppressWarnings("unchecked")
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
diff --git a/guava/src/com/google/common/collect/CompactLinkedHashMap.java b/guava/src/com/google/common/collect/CompactLinkedHashMap.java
index 97b3a4b1c..8a3f93dfc 100644
--- a/guava/src/com/google/common/collect/CompactLinkedHashMap.java
+++ b/guava/src/com/google/common/collect/CompactLinkedHashMap.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
@@ -52,6 +53,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Louis Wasserman
*/
+@J2ktIncompatible // no support for access-order mode in LinkedHashMap delegate
@GwtIncompatible // not worth using in GWT for now
@ElementTypesAreNonnullByDefault
class CompactLinkedHashMap<K extends @Nullable Object, V extends @Nullable Object>
diff --git a/guava/src/com/google/common/collect/ComparisonChain.java b/guava/src/com/google/common/collect/ComparisonChain.java
index 9c05205ec..79b7c6cc8 100644
--- a/guava/src/com/google/common/collect/ComparisonChain.java
+++ b/guava/src/com/google/common/collect/ComparisonChain.java
@@ -24,7 +24,10 @@ import java.util.Comparator;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
- * A utility for performing a chained comparison statement. For example:
+ * A utility for performing a chained comparison statement. <b>Note:</b> Java 8+ users should
+ * generally prefer the methods in {@link Comparator}; see <a href="#java8">below</a>.
+ *
+ * <p>Example usage of {@code ComparisonChain}:
*
* <pre>{@code
* public int compareTo(Foo that) {
@@ -52,6 +55,37 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* "https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#comparecompareto">{@code
* ComparisonChain}</a>.
*
+ * <h4 id="java8">Java 8+ equivalents</h4>
+ *
+ * If you are using Java version 8 or greater, you should generally use the static methods in {@link
+ * Comparator} instead of {@code ComparisonChain}. The example above can be implemented like this:
+ *
+ * <pre>{@code
+ * import static java.util.Comparator.comparing;
+ * import static java.util.Comparator.nullsLast;
+ * import static java.util.Comparator.naturalOrder;
+ *
+ * ...
+ * private static final Comparator<Foo> COMPARATOR =
+ * comparing((Foo foo) -> foo.aString)
+ * .thenComparing(foo -> foo.anInt)
+ * .thenComparing(foo -> foo.anEnum, nullsLast(naturalOrder()));}
+ *
+ * {@code @Override}{@code
+ * public int compareTo(Foo that) {
+ * return COMPARATOR.compare(this, that);
+ * }
+ * }</pre>
+ *
+ * <p>With method references it is more succinct: {@code comparing(Foo::aString)} for example.
+ *
+ * <p>Using {@link Comparator} avoids certain types of bugs, for example when you meant to write
+ * {@code .compare(a.foo, b.foo)} but you actually wrote {@code .compare(a.foo, a.foo)} or {@code
+ * .compare(a.foo, b.bar)}. {@code ComparisonChain} also has a potential performance problem that
+ * {@code Comparator} doesn't: it evaluates all the parameters of all the {@code .compare} calls,
+ * even when the result of the comparison is already known from previous {@code .compare} calls.
+ * That can be expensive.
+ *
* @author Mark Davis
* @author Kevin Bourrillion
* @since 2.0
@@ -243,6 +277,12 @@ public abstract class ComparisonChain {
* Compares two {@code boolean} values, considering {@code true} to be less than {@code false},
* <i>if</i> the result of this comparison chain has not already been determined.
*
+ * <p>Java 8+ users: you can get the equivalent from {@link Booleans#trueFirst()}. For example:
+ *
+ * <pre>
+ * Comparator.comparing(Foo::isBar, {@link Booleans#trueFirst()})
+ * </pre>
+ *
* @since 12.0
*/
public abstract ComparisonChain compareTrueFirst(boolean left, boolean right);
@@ -251,6 +291,12 @@ public abstract class ComparisonChain {
* Compares two {@code boolean} values, considering {@code false} to be less than {@code true},
* <i>if</i> the result of this comparison chain has not already been determined.
*
+ * <p>Java 8+ users: you can get the equivalent from {@link Booleans#falseFirst()}. For example:
+ *
+ * <pre>
+ * Comparator.comparing(Foo::isBar, {@link Booleans#falseFirst()})
+ * </pre>
+ *
* @since 12.0 (present as {@code compare} since 2.0)
*/
public abstract ComparisonChain compareFalseFirst(boolean left, boolean right);
diff --git a/guava/src/com/google/common/collect/CompoundOrdering.java b/guava/src/com/google/common/collect/CompoundOrdering.java
index 42feed373..95ebb82bb 100644
--- a/guava/src/com/google/common/collect/CompoundOrdering.java
+++ b/guava/src/com/google/common/collect/CompoundOrdering.java
@@ -30,12 +30,14 @@ final class CompoundOrdering<T extends @Nullable Object> extends Ordering<T>
implements Serializable {
final Comparator<? super T>[] comparators;
+ @SuppressWarnings("unchecked") // Generic array creation
CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) {
this.comparators = (Comparator<? super T>[]) new Comparator[] {primary, secondary};
}
+ @SuppressWarnings("unchecked") // Generic array creation
CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) {
- this.comparators = Iterables.toArray(comparators, new Comparator[0]);
+ this.comparators = Iterables.toArray(comparators, (Comparator<? super T>[]) new Comparator[0]);
}
@Override
diff --git a/guava/src/com/google/common/collect/ConcurrentHashMultiset.java b/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
index 47248412b..723ab0696 100644
--- a/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
+++ b/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
@@ -21,8 +21,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Serialization.FieldSetter;
import com.google.common.math.IntMath;
@@ -55,6 +55,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author mike nonemacher
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable {
@@ -118,7 +119,6 @@ public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> impleme
* @throws IllegalArgumentException if {@code countMap} is not empty
* @since 20.0
*/
- @Beta
public static <E> ConcurrentHashMultiset<E> create(ConcurrentMap<E, AtomicInteger> countMap) {
return new ConcurrentHashMultiset<>(countMap);
}
@@ -594,6 +594,7 @@ public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> impleme
stream.writeObject(countMap);
}
+ @J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
diff --git a/guava/src/com/google/common/collect/ConsumingQueueIterator.java b/guava/src/com/google/common/collect/ConsumingQueueIterator.java
index 7721e1277..3a923ae21 100644
--- a/guava/src/com/google/common/collect/ConsumingQueueIterator.java
+++ b/guava/src/com/google/common/collect/ConsumingQueueIterator.java
@@ -23,7 +23,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An Iterator implementation which draws elements from a queue, removing them from the queue as it
- * iterates.
+ * iterates. This class is not thread safe.
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
@@ -36,7 +36,7 @@ final class ConsumingQueueIterator<T extends @Nullable Object> extends AbstractI
@Override
@CheckForNull
- public T computeNext() {
+ protected T computeNext() {
// TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker.
if (queue.isEmpty()) {
return endOfData();
diff --git a/guava/src/com/google/common/collect/ContiguousSet.java b/guava/src/com/google/common/collect/ContiguousSet.java
index b3e4889d7..d0792054e 100644
--- a/guava/src/com/google/common/collect/ContiguousSet.java
+++ b/guava/src/com/google/common/collect/ContiguousSet.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotCall;
@@ -103,7 +102,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Integer> closed(int lower, int upper) {
return create(Range.closed(lower, upper), DiscreteDomain.integers());
}
@@ -116,7 +114,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Long> closed(long lower, long upper) {
return create(Range.closed(lower, upper), DiscreteDomain.longs());
}
@@ -129,7 +126,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Integer> closedOpen(int lower, int upper) {
return create(Range.closedOpen(lower, upper), DiscreteDomain.integers());
}
@@ -142,7 +138,6 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @since 23.0
*/
- @Beta
public static ContiguousSet<Long> closedOpen(long lower, long upper) {
return create(Range.closedOpen(lower, upper), DiscreteDomain.longs());
}
@@ -245,7 +240,7 @@ public abstract class ContiguousSet<C extends Comparable> extends ImmutableSorte
return new DescendingImmutableSortedSet<>(this);
}
- /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
+ /** Returns a shorthand representation of the contents such as {@code "[1..100]"}. */
@Override
public String toString() {
return range().toString();
diff --git a/guava/src/com/google/common/collect/DescendingMultiset.java b/guava/src/com/google/common/collect/DescendingMultiset.java
index 7db0fbbd4..23ff8319c 100644
--- a/guava/src/com/google/common/collect/DescendingMultiset.java
+++ b/guava/src/com/google/common/collect/DescendingMultiset.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.util.Comparator;
import java.util.Iterator;
@@ -37,7 +38,7 @@ abstract class DescendingMultiset<E extends @Nullable Object> extends Forwarding
implements SortedMultiset<E> {
abstract SortedMultiset<E> forwardMultiset();
- @CheckForNull private transient Comparator<? super E> comparator;
+ @LazyInit @CheckForNull private transient Comparator<? super E> comparator;
@Override
public Comparator<? super E> comparator() {
@@ -48,7 +49,7 @@ abstract class DescendingMultiset<E extends @Nullable Object> extends Forwarding
return result;
}
- @CheckForNull private transient NavigableSet<E> elementSet;
+ @LazyInit @CheckForNull private transient NavigableSet<E> elementSet;
@Override
public NavigableSet<E> elementSet() {
@@ -116,7 +117,7 @@ abstract class DescendingMultiset<E extends @Nullable Object> extends Forwarding
abstract Iterator<Entry<E>> entryIterator();
- @CheckForNull private transient Set<Entry<E>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<E>> entrySet;
@Override
public Set<Entry<E>> entrySet() {
diff --git a/guava/src/com/google/common/collect/DiscreteDomain.java b/guava/src/com/google/common/collect/DiscreteDomain.java
index 222ebe528..c32ea8408 100644
--- a/guava/src/com/google/common/collect/DiscreteDomain.java
+++ b/guava/src/com/google/common/collect/DiscreteDomain.java
@@ -50,6 +50,9 @@ public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code Integer}.
*
+ * <p>This method always returns the same object. That object is serializable; deserializing it
+ * results in the same object too.
+ *
* @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()})
*/
public static DiscreteDomain<Integer> integers() {
@@ -113,6 +116,9 @@ public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code Long}.
*
+ * <p>This method always returns the same object. That object is serializable; deserializing it
+ * results in the same object too.
+ *
* @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()})
*/
public static DiscreteDomain<Long> longs() {
@@ -187,6 +193,9 @@ public abstract class DiscreteDomain<C extends Comparable> {
/**
* Returns the discrete domain for values of type {@code BigInteger}.
*
+ * <p>This method always returns the same object. That object is serializable; deserializing it
+ * results in the same object too.
+ *
* @since 15.0
*/
public static DiscreteDomain<BigInteger> bigIntegers() {
diff --git a/guava/src/com/google/common/collect/EmptyContiguousSet.java b/guava/src/com/google/common/collect/EmptyContiguousSet.java
index 50d7b126a..5ae3d23f4 100644
--- a/guava/src/com/google/common/collect/EmptyContiguousSet.java
+++ b/guava/src/com/google/common/collect/EmptyContiguousSet.java
@@ -15,6 +15,9 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.Set;
@@ -142,6 +145,7 @@ final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private static final class SerializedForm<C extends Comparable> implements Serializable {
private final DiscreteDomain<C> domain;
@@ -157,14 +161,21 @@ final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm<>(domain);
}
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
@GwtIncompatible // NavigableSet
@Override
ImmutableSortedSet<C> createDescendingSet() {
- return ImmutableSortedSet.emptySet(Ordering.natural().reverse());
+ return ImmutableSortedSet.emptySet(Ordering.<C>natural().reverse());
}
}
diff --git a/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java b/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java
index 10d030fbd..8a6030182 100644
--- a/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java
+++ b/guava/src/com/google/common/collect/EmptyImmutableListMultimap.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import java.util.Collection;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
@@ -32,6 +33,17 @@ class EmptyImmutableListMultimap extends ImmutableListMultimap<Object, Object> {
super(ImmutableMap.<Object, ImmutableList<Object>>of(), 0);
}
+ /*
+ * TODO(b/242884182): Figure out why this helps produce the same class file when we compile most
+ * of common.collect a second time with the results of the first compilation on the classpath. Or
+ * just back this out once we stop doing that (which we'll do after our internal GWT setup
+ * changes).
+ */
+ @Override
+ public ImmutableMap<Object, Collection<Object>> asMap() {
+ return super.asMap();
+ }
+
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
diff --git a/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java b/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
index bd0a67aa0..087112e10 100644
--- a/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
+++ b/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import java.util.Collection;
/**
* Implementation of {@link ImmutableListMultimap} with no entries.
@@ -32,6 +33,17 @@ class EmptyImmutableSetMultimap extends ImmutableSetMultimap<Object, Object> {
super(ImmutableMap.<Object, ImmutableSet<Object>>of(), 0, null);
}
+ /*
+ * TODO(b/242884182): Figure out why this helps produce the same class file when we compile most
+ * of common.collect a second time with the results of the first compilation on the classpath. Or
+ * just back this out once we stop doing that (which we'll do after our internal GWT setup
+ * changes).
+ */
+ @Override
+ public ImmutableMap<Object, Collection<Object>> asMap() {
+ return super.asMap();
+ }
+
private Object readResolve() {
return INSTANCE; // preserve singleton property
}
diff --git a/guava/src/com/google/common/collect/EnumBiMap.java b/guava/src/com/google/common/collect/EnumBiMap.java
index 97d3c2e7c..c4b540b56 100644
--- a/guava/src/com/google/common/collect/EnumBiMap.java
+++ b/guava/src/com/google/common/collect/EnumBiMap.java
@@ -18,9 +18,11 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.collect.Platform.getDeclaringClassOrObjectForJ2cl;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -38,10 +40,25 @@ import java.util.Map;
* @since 2.0
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends AbstractBiMap<K, V> {
- private transient Class<K> keyType;
- private transient Class<V> valueType;
+ /*
+ * J2CL's EnumMap does not need the Class instance, so we can use Object.class instead. (Or we
+ * could use null, but that messes with our nullness checking, including under J2KT. We could
+ * probably work around it by changing how we annotate the J2CL EnumMap, but that's probably more
+ * trouble than just using Object.class.)
+ *
+ * Then we declare the getters for these fields as @GwtIncompatible so that no one can try to use
+ * them under J2CL—or, as an unfortunate side effect, under GWT. We do still give the fields
+ * themselves their proper values under GWT, since GWT's EnumMap does need the Class instance.
+ *
+ * Note that sometimes these fields *do* have correct values under J2CL: They will if the caller
+ * calls `create(Foo.class)`, rather than `create(map)`. That's fine; we just shouldn't rely on
+ * it.
+ */
+ transient Class<K> keyTypeOrObjectUnderJ2cl;
+ transient Class<V> valueTypeOrObjectUnderJ2cl;
/**
* Returns a new, empty {@code EnumBiMap} using the specified key and value types.
@@ -64,44 +81,48 @@ public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends Abstr
* mappings
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Map<K, V> map) {
- EnumBiMap<K, V> bimap = create(inferKeyType(map), inferValueType(map));
+ EnumBiMap<K, V> bimap =
+ create(inferKeyTypeOrObjectUnderJ2cl(map), inferValueTypeOrObjectUnderJ2cl(map));
bimap.putAll(map);
return bimap;
}
- private EnumBiMap(Class<K> keyType, Class<V> valueType) {
- super(new EnumMap<K, V>(keyType), new EnumMap<V, K>(valueType));
- this.keyType = keyType;
- this.valueType = valueType;
+ private EnumBiMap(Class<K> keyTypeOrObjectUnderJ2cl, Class<V> valueTypeOrObjectUnderJ2cl) {
+ super(
+ new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
+ this.keyTypeOrObjectUnderJ2cl = keyTypeOrObjectUnderJ2cl;
+ this.valueTypeOrObjectUnderJ2cl = valueTypeOrObjectUnderJ2cl;
}
- static <K extends Enum<K>> Class<K> inferKeyType(Map<K, ?> map) {
+ static <K extends Enum<K>> Class<K> inferKeyTypeOrObjectUnderJ2cl(Map<K, ?> map) {
if (map instanceof EnumBiMap) {
- return ((EnumBiMap<K, ?>) map).keyType();
+ return ((EnumBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
}
if (map instanceof EnumHashBiMap) {
- return ((EnumHashBiMap<K, ?>) map).keyType();
+ return ((EnumHashBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
}
checkArgument(!map.isEmpty());
- return map.keySet().iterator().next().getDeclaringClass();
+ return getDeclaringClassOrObjectForJ2cl(map.keySet().iterator().next());
}
- private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) {
+ private static <V extends Enum<V>> Class<V> inferValueTypeOrObjectUnderJ2cl(Map<?, V> map) {
if (map instanceof EnumBiMap) {
- return ((EnumBiMap<?, V>) map).valueType;
+ return ((EnumBiMap<?, V>) map).valueTypeOrObjectUnderJ2cl;
}
checkArgument(!map.isEmpty());
- return map.values().iterator().next().getDeclaringClass();
+ return getDeclaringClassOrObjectForJ2cl(map.values().iterator().next());
}
/** Returns the associated key type. */
+ @GwtIncompatible
public Class<K> keyType() {
- return keyType;
+ return keyTypeOrObjectUnderJ2cl;
}
/** Returns the associated value type. */
+ @GwtIncompatible
public Class<V> valueType() {
- return valueType;
+ return valueTypeOrObjectUnderJ2cl;
}
@Override
@@ -121,8 +142,8 @@ public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends Abstr
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
- stream.writeObject(keyType);
- stream.writeObject(valueType);
+ stream.writeObject(keyTypeOrObjectUnderJ2cl);
+ stream.writeObject(valueTypeOrObjectUnderJ2cl);
Serialization.writeMap(this, stream);
}
@@ -130,9 +151,10 @@ public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends Abstr
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
- keyType = (Class<K>) stream.readObject();
- valueType = (Class<V>) stream.readObject();
- setDelegates(new EnumMap<K, V>(keyType), new EnumMap<V, K>(valueType));
+ keyTypeOrObjectUnderJ2cl = (Class<K>) stream.readObject();
+ valueTypeOrObjectUnderJ2cl = (Class<V>) stream.readObject();
+ setDelegates(
+ new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
Serialization.populateMap(this, stream);
}
diff --git a/guava/src/com/google/common/collect/EnumHashBiMap.java b/guava/src/com/google/common/collect/EnumHashBiMap.java
index 5fbbb70c6..33b45b95c 100644
--- a/guava/src/com/google/common/collect/EnumHashBiMap.java
+++ b/guava/src/com/google/common/collect/EnumHashBiMap.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -42,10 +43,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 2.0
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
extends AbstractBiMap<K, V> {
- private transient Class<K> keyType;
+ transient Class<K> keyTypeOrObjectUnderJ2cl;
/**
* Returns a new, empty {@code EnumHashBiMap} using the specified key type.
@@ -69,16 +71,15 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
*/
public static <K extends Enum<K>, V extends @Nullable Object> EnumHashBiMap<K, V> create(
Map<K, ? extends V> map) {
- EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
+ EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyTypeOrObjectUnderJ2cl(map));
bimap.putAll(map);
return bimap;
}
private EnumHashBiMap(Class<K> keyType) {
- super(
- new EnumMap<K, V>(keyType),
- Maps.<V, K>newHashMapWithExpectedSize(keyType.getEnumConstants().length));
- this.keyType = keyType;
+ super(new EnumMap<K, V>(keyType), new HashMap<V, K>());
+ // TODO: cpovirk - Pre-size the HashMap based on the number of enum values?
+ this.keyTypeOrObjectUnderJ2cl = keyType;
}
// Overriding these 3 methods to show that values may be null (but not keys)
@@ -107,8 +108,9 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
}
/** Returns the associated key type. */
+ @GwtIncompatible
public Class<K> keyType() {
- return keyType;
+ return keyTypeOrObjectUnderJ2cl;
}
/**
@@ -118,7 +120,7 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
- stream.writeObject(keyType);
+ stream.writeObject(keyTypeOrObjectUnderJ2cl);
Serialization.writeMap(this, stream);
}
@@ -126,9 +128,13 @@ public final class EnumHashBiMap<K extends Enum<K>, V extends @Nullable Object>
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
- keyType = (Class<K>) stream.readObject();
- setDelegates(
- new EnumMap<K, V>(keyType), new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
+ keyTypeOrObjectUnderJ2cl = (Class<K>) stream.readObject();
+ /*
+ * TODO: cpovirk - Pre-size the HashMap based on the number of enum values? (But *not* based on
+ * the number of entries in the map, as that makes it easy for hostile inputs to trigger lots of
+ * allocation—not that any program should be deserializing hostile inputs to begin with!)
+ */
+ setDelegates(new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new HashMap<V, K>());
Serialization.populateMap(this, stream);
}
diff --git a/guava/src/com/google/common/collect/EnumMultiset.java b/guava/src/com/google/common/collect/EnumMultiset.java
index 778902ede..d6ced718b 100644
--- a/guava/src/com/google/common/collect/EnumMultiset.java
+++ b/guava/src/com/google/common/collect/EnumMultiset.java
@@ -21,6 +21,7 @@ import static com.google.common.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -44,6 +45,7 @@ import javax.annotation.CheckForNull;
* @since 2.0
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumMultiset<E extends Enum<E>> extends AbstractMultiset<E>
implements Serializable {
diff --git a/guava/src/com/google/common/collect/EvictingQueue.java b/guava/src/com/google/common/collect/EvictingQueue.java
index 5667dfa8c..71770b72a 100644
--- a/guava/src/com/google/common/collect/EvictingQueue.java
+++ b/guava/src/com/google/common/collect/EvictingQueue.java
@@ -19,8 +19,8 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
@@ -43,7 +43,6 @@ import java.util.Queue;
* @author Kurt Alfred Kluever
* @since 15.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serializable {
@@ -127,6 +126,7 @@ public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serial
}
@Override
+ @J2ktIncompatible // Incompatible return type change. Use inherited implementation
public Object[] toArray() {
/*
* If we could, we'd declare the no-arg `Collection.toArray()` to return "Object[] but elements
diff --git a/guava/src/com/google/common/collect/FluentIterable.java b/guava/src/com/google/common/collect/FluentIterable.java
index 11bda3bde..fd8178d7c 100644
--- a/guava/src/com/google/common/collect/FluentIterable.java
+++ b/guava/src/com/google/common/collect/FluentIterable.java
@@ -16,7 +16,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
@@ -34,6 +33,7 @@ import java.util.List;
import java.util.SortedSet;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -159,7 +159,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0 (since 18.0 as an overload of {@code of})
*/
- @Beta
public static <E extends @Nullable Object> FluentIterable<E> from(E[] elements) {
return from(Arrays.asList(elements));
}
@@ -192,7 +191,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b) {
return concatNoDefensiveCopy(a, b);
@@ -211,7 +209,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
return concatNoDefensiveCopy(a, b, c);
@@ -231,7 +228,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T> a,
Iterable<? extends T> b,
@@ -255,7 +251,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @throws NullPointerException if any of the provided iterables is {@code null}
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
Iterable<? extends T>... inputs) {
return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
@@ -275,14 +270,13 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <T extends @Nullable Object> FluentIterable<T> concat(
final Iterable<? extends Iterable<? extends T>> inputs) {
checkNotNull(inputs);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
- return Iterators.concat(Iterators.transform(inputs.iterator(), Iterables.<T>toIterator()));
+ return Iterators.concat(Iterators.transform(inputs.iterator(), Iterable::iterator));
}
};
}
@@ -315,7 +309,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <E extends @Nullable Object> FluentIterable<E> of() {
return FluentIterable.from(Collections.<E>emptyList());
}
@@ -328,7 +321,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 20.0
*/
- @Beta
public static <E extends @Nullable Object> FluentIterable<E> of(
@ParametricNullness E element, E... elements) {
return from(Lists.asList(element, elements));
@@ -397,7 +389,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 18.0
*/
- @Beta
public final FluentIterable<E> append(Iterable<? extends E> other) {
return FluentIterable.concat(getDelegate(), other);
}
@@ -410,7 +401,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 18.0
*/
- @Beta
public final FluentIterable<E> append(E... elements) {
return FluentIterable.concat(getDelegate(), Arrays.asList(elements));
}
@@ -472,8 +462,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final Optional<E> firstMatch(Predicate<? super E> predicate) {
- return Iterables.tryFind(getDelegate(), predicate);
+ public final Optional<@NonNull E> firstMatch(Predicate<? super E> predicate) {
+ return Iterables.<E>tryFind((Iterable<@NonNull E>) getDelegate(), predicate);
}
/**
@@ -520,9 +510,9 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* iterator().next()} or {@link Iterables#getFirst} instead.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final Optional<E> first() {
+ public final Optional<@NonNull E> first() {
Iterator<E> iterator = getDelegate().iterator();
- return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent();
+ return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.absent();
}
/**
@@ -537,7 +527,7 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* Iterables#getLast} instead.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final Optional<E> last() {
+ public final Optional<@NonNull E> last() {
// Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
// TODO(kevinb): Support a concurrently modified collection?
@@ -577,7 +567,7 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* iterable skips all of its elements.
*
* <p>Modifications to this fluent iterable before a call to {@code iterator()} are reflected in
- * the returned fluent iterable. That is, the its iterator skips the first {@code numberToSkip}
+ * the returned fluent iterable. That is, the iterator skips the first {@code numberToSkip}
* elements that exist when the iterator is created, not when {@code skip()} is called.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of
@@ -627,8 +617,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 12.0 as {@code toImmutableList()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableList<E> toList() {
- return ImmutableList.copyOf(getDelegate());
+ public final ImmutableList<@NonNull E> toList() {
+ return ImmutableList.copyOf((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -644,8 +634,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
- return Ordering.from(comparator).immutableSortedCopy(getDelegate());
+ public final ImmutableList<@NonNull E> toSortedList(Comparator<? super E> comparator) {
+ return Ordering.from(comparator).immutableSortedCopy((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -659,8 +649,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 12.0 as {@code toImmutableSet()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableSet<E> toSet() {
- return ImmutableSet.copyOf(getDelegate());
+ public final ImmutableSet<@NonNull E> toSet() {
+ return ImmutableSet.copyOf((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -677,8 +667,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
- return ImmutableSortedSet.copyOf(comparator, getDelegate());
+ public final ImmutableSortedSet<@NonNull E> toSortedSet(Comparator<? super E> comparator) {
+ return ImmutableSortedSet.copyOf(comparator, (Iterable<@NonNull E>) getDelegate());
}
/**
@@ -691,8 +681,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 19.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final ImmutableMultiset<E> toMultiset() {
- return ImmutableMultiset.copyOf(getDelegate());
+ public final ImmutableMultiset<@NonNull E> toMultiset() {
+ return ImmutableMultiset.copyOf((Iterable<@NonNull E>) getDelegate());
}
/**
@@ -712,8 +702,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
- return Maps.toMap(getDelegate(), valueFunction);
+ public final <V> ImmutableMap<@NonNull E, V> toMap(Function<? super E, V> valueFunction) {
+ return Maps.toMap((Iterable<@NonNull E>) getDelegate(), valueFunction);
}
/**
@@ -727,7 +717,7 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.groupingBy(keyFunction))}
* behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve
- * the order of entries).
+ * the order of entries.
*
* @param keyFunction the function used to produce the key for each value
* @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
@@ -735,8 +725,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
- return Multimaps.index(getDelegate(), keyFunction);
+ public final <K> ImmutableListMultimap<K, @NonNull E> index(Function<? super E, K> keyFunction) {
+ return Multimaps.index((Iterable<@NonNull E>) getDelegate(), keyFunction);
}
/**
@@ -770,8 +760,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* @since 14.0
*/
@SuppressWarnings("nullness") // Unsafe, but we can't do much about it now.
- public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
- return Maps.uniqueIndex(getDelegate(), keyFunction);
+ public final <K> ImmutableMap<K, @NonNull E> uniqueIndex(Function<? super E, K> keyFunction) {
+ return Maps.uniqueIndex((Iterable<@NonNull E>) getDelegate(), keyFunction);
}
/**
@@ -787,16 +777,8 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
* copied
*/
@GwtIncompatible // Array.newArray(Class, int)
- /*
- * Both the declaration of our Class<E> parameter and its usage in a call to Iterables.toArray
- * produce a nullness error: E may be a nullable type, and our nullness checker has Class's type
- * parameter bounded to non-null types. To avoid that, we'd use Class<@Nonnull E> if we could.
- * (Granted, this is only one of many nullness-checking problems that arise from letting
- * FluentIterable support null elements, and most of the other produce outright unsoundness.)
- */
- @SuppressWarnings("nullness")
- public final @Nullable E[] toArray(Class<E> type) {
- return Iterables.toArray(getDelegate(), type);
+ public final E[] toArray(Class<@NonNull E> type) {
+ return Iterables.<E>toArray(getDelegate(), type);
}
/**
@@ -834,7 +816,6 @@ public abstract class FluentIterable<E extends @Nullable Object> implements Iter
*
* @since 18.0
*/
- @Beta
public final String join(Joiner joiner) {
return joiner.join(this);
}
diff --git a/guava/src/com/google/common/collect/ForwardingBlockingDeque.java b/guava/src/com/google/common/collect/ForwardingBlockingDeque.java
index 49d4bcf6c..13b5b236e 100644
--- a/guava/src/com/google/common/collect/ForwardingBlockingDeque.java
+++ b/guava/src/com/google/common/collect/ForwardingBlockingDeque.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Collection;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;
@@ -46,6 +47,7 @@ import javax.annotation.CheckForNull;
* com.google.common.util.concurrent.ForwardingBlockingDeque} instead.
*/
@Deprecated
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingDeque<E> extends ForwardingDeque<E>
diff --git a/guava/src/com/google/common/collect/ForwardingDeque.java b/guava/src/com/google/common/collect/ForwardingDeque.java
index 571535cab..2730dad0e 100644
--- a/guava/src/com/google/common/collect/ForwardingDeque.java
+++ b/guava/src/com/google/common/collect/ForwardingDeque.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Deque;
import java.util.Iterator;
@@ -40,6 +41,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Kurt Alfred Kluever
* @since 12.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingDeque<E extends @Nullable Object> extends ForwardingQueue<E>
diff --git a/guava/src/com/google/common/collect/ForwardingList.java b/guava/src/com/google/common/collect/ForwardingList.java
index 4b4551e5e..e9b4d8e35 100644
--- a/guava/src/com/google/common/collect/ForwardingList.java
+++ b/guava/src/com/google/common/collect/ForwardingList.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
@@ -204,7 +203,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected ListIterator<E> standardListIterator(int start) {
return Lists.listIteratorImpl(this, start);
}
@@ -215,7 +213,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected List<E> standardSubList(int fromIndex, int toIndex) {
return Lists.subListImpl(this, fromIndex, toIndex);
}
@@ -227,7 +224,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected boolean standardEquals(@CheckForNull Object object) {
return Lists.equalsImpl(this, object);
}
@@ -239,7 +235,6 @@ public abstract class ForwardingList<E extends @Nullable Object> extends Forward
*
* @since 7.0
*/
- @Beta
protected int standardHashCode() {
return Lists.hashCodeImpl(this);
}
diff --git a/guava/src/com/google/common/collect/ForwardingMap.java b/guava/src/com/google/common/collect/ForwardingMap.java
index 315a4fabc..24c40f23c 100644
--- a/guava/src/com/google/common/collect/ForwardingMap.java
+++ b/guava/src/com/google/common/collect/ForwardingMap.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -163,7 +162,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 7.0
*/
- @Beta
@CheckForNull
protected V standardRemove(@CheckForNull Object key) {
Iterator<Entry<K, V>> entryIterator = entrySet().iterator();
@@ -198,7 +196,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 10.0
*/
- @Beta
protected class StandardKeySet extends Maps.KeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardKeySet() {
@@ -213,7 +210,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 7.0
*/
- @Beta
protected boolean standardContainsKey(@CheckForNull Object key) {
return Maps.containsKeyImpl(this, key);
}
@@ -227,7 +223,6 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 10.0
*/
- @Beta
protected class StandardValues extends Maps.Values<K, V> {
/** Constructor for use by subclasses. */
public StandardValues() {
@@ -255,10 +250,9 @@ public abstract class ForwardingMap<K extends @Nullable Object, V extends @Nulla
*
* @since 10.0
*/
- @Beta
protected abstract class StandardEntrySet extends Maps.EntrySet<K, V> {
/** Constructor for use by subclasses. */
- public StandardEntrySet() {}
+ protected StandardEntrySet() {}
@Override
Map<K, V> map() {
diff --git a/guava/src/com/google/common/collect/ForwardingMapEntry.java b/guava/src/com/google/common/collect/ForwardingMapEntry.java
index 6816ccbbe..2faa65152 100644
--- a/guava/src/com/google/common/collect/ForwardingMapEntry.java
+++ b/guava/src/com/google/common/collect/ForwardingMapEntry.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.util.Map;
@@ -123,7 +122,6 @@ public abstract class ForwardingMapEntry<K extends @Nullable Object, V extends @
*
* @since 7.0
*/
- @Beta
protected String standardToString() {
return getKey() + "=" + getValue();
}
diff --git a/guava/src/com/google/common/collect/ForwardingMultiset.java b/guava/src/com/google/common/collect/ForwardingMultiset.java
index 857b9aec7..d1187d4c5 100644
--- a/guava/src/com/google/common/collect/ForwardingMultiset.java
+++ b/guava/src/com/google/common/collect/ForwardingMultiset.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -138,7 +137,6 @@ public abstract class ForwardingMultiset<E extends @Nullable Object> extends For
*
* @since 7.0
*/
- @Beta
protected int standardCount(@CheckForNull Object object) {
for (Entry<?> entry : this.entrySet()) {
if (Objects.equal(entry.getElement(), object)) {
@@ -167,7 +165,6 @@ public abstract class ForwardingMultiset<E extends @Nullable Object> extends For
*
* @since 7.0
*/
- @Beta
@Override
protected boolean standardAddAll(Collection<? extends E> elementsToAdd) {
return Multisets.addAllImpl(this, elementsToAdd);
@@ -243,7 +240,6 @@ public abstract class ForwardingMultiset<E extends @Nullable Object> extends For
*
* @since 10.0
*/
- @Beta
protected class StandardElementSet extends Multisets.ElementSet<E> {
/** Constructor for use by subclasses. */
public StandardElementSet() {}
diff --git a/guava/src/com/google/common/collect/ForwardingNavigableMap.java b/guava/src/com/google/common/collect/ForwardingNavigableMap.java
index c32468da1..4cc10b57f 100644
--- a/guava/src/com/google/common/collect/ForwardingNavigableMap.java
+++ b/guava/src/com/google/common/collect/ForwardingNavigableMap.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.collect.Maps.keyOrNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import java.util.Iterator;
import java.util.NavigableMap;
@@ -207,7 +206,7 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*/
@CheckForNull
protected Entry<K, V> standardFirstEntry() {
- return Iterables.getFirst(entrySet(), null);
+ return Iterables.<@Nullable Entry<K, V>>getFirst(entrySet(), null);
}
/**
@@ -237,7 +236,7 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*/
@CheckForNull
protected Entry<K, V> standardLastEntry() {
- return Iterables.getFirst(descendingMap().entrySet(), null);
+ return Iterables.<@Nullable Entry<K, V>>getFirst(descendingMap().entrySet(), null);
}
/**
@@ -301,7 +300,6 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*
* @since 12.0
*/
- @Beta
protected class StandardDescendingMap extends Maps.DescendingMap<K, V> {
/** Constructor for use by subclasses. */
public StandardDescendingMap() {}
@@ -365,7 +363,6 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
*
* @since 12.0
*/
- @Beta
protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardNavigableKeySet() {
@@ -385,7 +382,6 @@ public abstract class ForwardingNavigableMap<K extends @Nullable Object, V exten
* descendingMap}, you may wish to override {@code descendingKeySet} to forward to this
* implementation.
*/
- @Beta
protected NavigableSet<K> standardDescendingKeySet() {
return descendingMap().navigableKeySet();
}
diff --git a/guava/src/com/google/common/collect/ForwardingNavigableSet.java b/guava/src/com/google/common/collect/ForwardingNavigableSet.java
index 6822aa87d..97f137a59 100644
--- a/guava/src/com/google/common/collect/ForwardingNavigableSet.java
+++ b/guava/src/com/google/common/collect/ForwardingNavigableSet.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import java.util.Iterator;
import java.util.NavigableSet;
@@ -181,7 +180,6 @@ public abstract class ForwardingNavigableSet<E extends @Nullable Object>
*
* @since 12.0
*/
- @Beta
protected class StandardDescendingSet extends Sets.DescendingSet<E> {
/** Constructor for use by subclasses. */
public StandardDescendingSet() {
@@ -208,7 +206,6 @@ public abstract class ForwardingNavigableSet<E extends @Nullable Object>
* {@code headSet} and {@code tailSet} methods. In many cases, you may wish to override {@link
* #subSet(Object, boolean, Object, boolean)} to forward to this implementation.
*/
- @Beta
protected NavigableSet<E> standardSubSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
diff --git a/guava/src/com/google/common/collect/ForwardingSortedMap.java b/guava/src/com/google/common/collect/ForwardingSortedMap.java
index e0882abc7..9779b97a7 100644
--- a/guava/src/com/google/common/collect/ForwardingSortedMap.java
+++ b/guava/src/com/google/common/collect/ForwardingSortedMap.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.NoSuchElementException;
@@ -103,7 +102,6 @@ public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends
*
* @since 15.0
*/
- @Beta
protected class StandardKeySet extends Maps.SortedKeySet<K, V> {
/** Constructor for use by subclasses. */
public StandardKeySet() {
@@ -130,7 +128,6 @@ public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends
* @since 7.0
*/
@Override
- @Beta
protected boolean standardContainsKey(@CheckForNull Object key) {
try {
// any CCE or NPE will be caught
@@ -150,7 +147,6 @@ public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends
*
* @since 7.0
*/
- @Beta
protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
checkArgument(unsafeCompare(comparator(), fromKey, toKey) <= 0, "fromKey must be <= toKey");
return tailMap(fromKey).headMap(toKey);
diff --git a/guava/src/com/google/common/collect/ForwardingSortedMultiset.java b/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
index 4626d3193..777735741 100644
--- a/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
+++ b/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
@@ -14,7 +14,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
@@ -44,7 +43,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
* @since 15.0
*/
-@Beta
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public abstract class ForwardingSortedMultiset<E extends @Nullable Object>
diff --git a/guava/src/com/google/common/collect/ForwardingSortedSet.java b/guava/src/com/google/common/collect/ForwardingSortedSet.java
index 32625afd1..ad7ef1223 100644
--- a/guava/src/com/google/common/collect/ForwardingSortedSet.java
+++ b/guava/src/com/google/common/collect/ForwardingSortedSet.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.collect.ForwardingSortedMap.unsafeCompare;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
@@ -106,7 +105,6 @@ public abstract class ForwardingSortedSet<E extends @Nullable Object> extends Fo
* @since 7.0
*/
@Override
- @Beta
protected boolean standardContains(@CheckForNull Object object) {
try {
// any ClassCastExceptions and NullPointerExceptions are caught
@@ -127,7 +125,6 @@ public abstract class ForwardingSortedSet<E extends @Nullable Object> extends Fo
* @since 7.0
*/
@Override
- @Beta
protected boolean standardRemove(@CheckForNull Object object) {
try {
// any ClassCastExceptions and NullPointerExceptions are caught
@@ -154,7 +151,6 @@ public abstract class ForwardingSortedSet<E extends @Nullable Object> extends Fo
*
* @since 7.0
*/
- @Beta
protected SortedSet<E> standardSubSet(
@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return tailSet(fromElement).headSet(toElement);
diff --git a/guava/src/com/google/common/collect/GeneralRange.java b/guava/src/com/google/common/collect/GeneralRange.java
index 3d7256ff8..e462b7a01 100644
--- a/guava/src/com/google/common/collect/GeneralRange.java
+++ b/guava/src/com/google/common/collect/GeneralRange.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Comparator;
import javax.annotation.CheckForNull;
@@ -122,12 +123,14 @@ final class GeneralRange<T extends @Nullable Object> implements Serializable {
* whenever they pass `true` for the matching `has*Bound` parameter.
*/
if (hasLowerBound) {
- comparator.compare(
- uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint));
+ int unused =
+ comparator.compare(
+ uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint));
}
if (hasUpperBound) {
- comparator.compare(
- uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint));
+ int unused =
+ comparator.compare(
+ uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint));
}
if (hasLowerBound && hasUpperBound) {
@@ -261,7 +264,7 @@ final class GeneralRange<T extends @Nullable Object> implements Serializable {
getUpperBoundType());
}
- @CheckForNull private transient GeneralRange<T> reverse;
+ @LazyInit @CheckForNull private transient GeneralRange<T> reverse;
/** Returns the same range relative to the reversed comparator. */
GeneralRange<T> reverse() {
diff --git a/guava/src/com/google/common/collect/HashBiMap.java b/guava/src/com/google/common/collect/HashBiMap.java
index b0a5dd50e..f6ce5d42b 100644
--- a/guava/src/com/google/common/collect/HashBiMap.java
+++ b/guava/src/com/google/common/collect/HashBiMap.java
@@ -22,6 +22,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Objects;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -29,6 +30,7 @@ import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import java.io.IOException;
+import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@@ -119,8 +121,12 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
* they are not initialized inline in the constructor, they are initialized from init(), which the
* constructor calls (as does readObject()).
*/
+ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (see above)
private transient @Nullable BiEntry<K, V>[] hashTableKToV;
+
+ @SuppressWarnings("nullness:initialization.field.uninitialized") // For J2KT (see above)
private transient @Nullable BiEntry<K, V>[] hashTableVToK;
+
@Weak @CheckForNull private transient BiEntry<K, V> firstInKeyInsertionOrder;
@Weak @CheckForNull private transient BiEntry<K, V> lastInKeyInsertionOrder;
private transient int size;
@@ -332,6 +338,7 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
return put(key, value, true);
}
+ @CanIgnoreReturnValue
@CheckForNull
private K putInverse(@ParametricNullness V value, @ParametricNullness K key, boolean force) {
int valueHash = smearedHash(value);
@@ -759,6 +766,12 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
Object writeReplace() {
return new InverseSerializedForm<>(HashBiMap.this);
}
+
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use InverseSerializedForm");
+ }
}
private static final class InverseSerializedForm<
@@ -779,12 +792,14 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
* @serialData the number of entries, first key, first value, second key, second value, and so on.
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int size = Serialization.readCount(stream);
@@ -793,5 +808,6 @@ public final class HashBiMap<K extends @Nullable Object, V extends @Nullable Obj
}
@GwtIncompatible // Not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/HashMultimap.java b/guava/src/com/google/common/collect/HashMultimap.java
index 9e4c1c223..51567cdce 100644
--- a/guava/src/com/google/common/collect/HashMultimap.java
+++ b/guava/src/com/google/common/collect/HashMultimap.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.io.IOException;
@@ -131,12 +132,14 @@ public final class HashMultimap<K extends @Nullable Object, V extends @Nullable
* key, number of values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
@@ -147,5 +150,6 @@ public final class HashMultimap<K extends @Nullable Object, V extends @Nullable
}
@GwtIncompatible // Not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/HashMultiset.java b/guava/src/com/google/common/collect/HashMultiset.java
index b91645739..357dc62c7 100644
--- a/guava/src/com/google/common/collect/HashMultiset.java
+++ b/guava/src/com/google/common/collect/HashMultiset.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -78,12 +79,14 @@ public final class HashMultiset<E extends @Nullable Object> extends AbstractMapB
* its count, and so on
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultiset(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int distinctElements = Serialization.readCount(stream);
@@ -92,5 +95,6 @@ public final class HashMultiset<E extends @Nullable Object> extends AbstractMapB
}
@GwtIncompatible // Not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/IgnoreJRERequirement.java b/guava/src/com/google/common/collect/IgnoreJRERequirement.java
new file mode 100644
index 000000000..2a1006831
--- /dev/null
+++ b/guava/src/com/google/common/collect/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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 static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/guava/src/com/google/common/collect/ImmutableAsList.java b/guava/src/com/google/common/collect/ImmutableAsList.java
index c39747931..b7c585cc2 100644
--- a/guava/src/com/google/common/collect/ImmutableAsList.java
+++ b/guava/src/com/google/common/collect/ImmutableAsList.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
@@ -60,6 +61,7 @@ abstract class ImmutableAsList<E> extends ImmutableList<E> {
/** Serialized form that leads to the same performance as the original list. */
@GwtIncompatible // serialization
+ @J2ktIncompatible
static class SerializedForm implements Serializable {
final ImmutableCollection<?> collection;
@@ -75,11 +77,13 @@ abstract class ImmutableAsList<E> extends ImmutableList<E> {
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm(delegateCollection());
diff --git a/guava/src/com/google/common/collect/ImmutableBiMap.java b/guava/src/com/google/common/collect/ImmutableBiMap.java
index 4c222c1bf..c0d3ed715 100644
--- a/guava/src/com/google/common/collect/ImmutableBiMap.java
+++ b/guava/src/com/google/common/collect/ImmutableBiMap.java
@@ -20,11 +20,13 @@ import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
@@ -51,10 +53,10 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
* and values are the result of applying the provided mapping functions to the input elements.
* Entries appear in the result {@code ImmutableBiMap} in encounter order.
*
- * <p>If the mapped keys or values contain duplicates (according to {@link Object#equals(Object)},
- * an {@code IllegalArgumentException} is thrown when the collection operation is performed. (This
- * differs from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)},
- * which throws an {@code IllegalStateException}.)
+ * <p>If the mapped keys or values contain duplicates (according to {@link
+ * Object#equals(Object)}), an {@code IllegalArgumentException} is thrown when the collection
+ * operation is performed. (This differs from the {@code Collector} returned by {@link
+ * Collectors#toMap(Function, Function)}, which throws an {@code IllegalStateException}.)
*
* @since 21.0
*/
@@ -300,7 +302,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
*
* @since 23.1
*/
- @Beta
public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<>(expectedSize);
@@ -391,7 +392,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -409,7 +409,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
super.orderEntriesByValue(valueComparator);
@@ -470,10 +469,10 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
entries = Arrays.copyOf(entries, size);
}
Arrays.sort(
- entries,
+ (Entry<K, V>[]) entries, // Entries up to size are not null
0,
size,
- Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
+ Ordering.from(valueComparator).onResultOf(Maps.valueFunction()));
}
entriesUsed = true;
return RegularImmutableBiMap.fromEntryArray(size, entries);
@@ -553,7 +552,6 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableBiMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
@SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
@@ -620,6 +618,7 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
* <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
* bimap and its inverse in sync during serialization, the way AbstractBiMap does.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
SerializedForm(ImmutableBiMap<K, V> bimap) {
super(bimap);
@@ -634,7 +633,13 @@ public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
+
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java b/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
index c59e9fdab..0ad82e917 100644
--- a/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
+++ b/guava/src/com/google/common/collect/ImmutableClassToInstanceMap.java
@@ -26,6 +26,7 @@ import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A {@link ClassToInstanceMap} whose contents will never change, with many other important
@@ -37,7 +38,9 @@ import javax.annotation.CheckForNull;
@Immutable(containerOf = "B")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
-public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B>
+// TODO(b/278589132): Remove the redundant "@NonNull" on B once it's no longer required by J2KT.
+public final class ImmutableClassToInstanceMap<B>
+ extends ForwardingMap<Class<? extends @NonNull B>, B>
implements ClassToInstanceMap<B>, Serializable {
private static final ImmutableClassToInstanceMap<Object> EMPTY =
@@ -120,7 +123,7 @@ public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<?
return this;
}
- private static <B, T extends B> T cast(Class<T> type, B value) {
+ private static <T> T cast(Class<T> type, Object value) {
return Primitives.wrap(type).cast(value);
}
@@ -154,8 +157,10 @@ public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<?
public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf(
Map<? extends Class<? extends S>, ? extends S> map) {
if (map instanceof ImmutableClassToInstanceMap) {
+ @SuppressWarnings("rawtypes") // JDT-based J2KT Java frontend does not permit the direct cast
+ Map rawMap = map;
@SuppressWarnings("unchecked") // covariant casts safe (unmodifiable)
- ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap<B>) map;
+ ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap<B>) rawMap;
return cast;
}
return new Builder<B>().putAll(map).build();
diff --git a/guava/src/com/google/common/collect/ImmutableCollection.java b/guava/src/com/google/common/collect/ImmutableCollection.java
index 314f83cce..68b175ffa 100644
--- a/guava/src/com/google/common/collect/ImmutableCollection.java
+++ b/guava/src/com/google/common/collect/ImmutableCollection.java
@@ -19,9 +19,12 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
@@ -189,6 +192,7 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
private static final Object[] EMPTY_ARRAY = {};
@Override
+ @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation
public final Object[] toArray() {
return toArray(EMPTY_ARRAY);
}
@@ -387,11 +391,17 @@ public abstract class ImmutableCollection<E> extends AbstractCollection<E> imple
return offset;
}
+ @J2ktIncompatible // serialization
Object writeReplace() {
// We serialize by default to ImmutableList, the simplest thing that works.
return new ImmutableList.SerializedForm(toArray());
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/**
* Abstract base class for builders of {@link ImmutableCollection} types.
*
diff --git a/guava/src/com/google/common/collect/ImmutableEntry.java b/guava/src/com/google/common/collect/ImmutableEntry.java
index edc25f490..f88fcc1c6 100644
--- a/guava/src/com/google/common/collect/ImmutableEntry.java
+++ b/guava/src/com/google/common/collect/ImmutableEntry.java
@@ -20,7 +20,11 @@ import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import org.checkerframework.checker.nullness.qual.Nullable;
-/** @see com.google.common.collect.Maps#immutableEntry(Object, Object) */
+/**
+ * An immutable {@code Map.Entry}, used both by {@link
+ * com.google.common.collect.Maps#immutableEntry(Object, Object)} and by other parts of {@code
+ * common.collect} as a superclass.
+ */
@GwtCompatible(serializable = true)
@ElementTypesAreNonnullByDefault
class ImmutableEntry<K extends @Nullable Object, V extends @Nullable Object>
diff --git a/guava/src/com/google/common/collect/ImmutableEnumMap.java b/guava/src/com/google/common/collect/ImmutableEnumMap.java
index d1e10f97d..ba62d9c76 100644
--- a/guava/src/com/google/common/collect/ImmutableEnumMap.java
+++ b/guava/src/com/google/common/collect/ImmutableEnumMap.java
@@ -19,7 +19,10 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMap.IteratorBasedImmutableMap;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.EnumMap;
import java.util.Spliterator;
@@ -113,13 +116,20 @@ final class ImmutableEnumMap<K extends Enum<K>, V> extends IteratorBasedImmutabl
// All callers of the constructor are restricted to <K extends Enum<K>>.
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new EnumSerializedForm<>(delegate);
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use EnumSerializedForm");
+ }
+
/*
* This class is used to serialize ImmutableEnumMap instances.
*/
+ @J2ktIncompatible // serialization
private static class EnumSerializedForm<K extends Enum<K>, V> implements Serializable {
final EnumMap<K, V> delegate;
diff --git a/guava/src/com/google/common/collect/ImmutableEnumSet.java b/guava/src/com/google/common/collect/ImmutableEnumSet.java
index 32287bdd2..5488039af 100644
--- a/guava/src/com/google/common/collect/ImmutableEnumSet.java
+++ b/guava/src/com/google/common/collect/ImmutableEnumSet.java
@@ -17,7 +17,10 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.EnumSet;
@@ -34,15 +37,14 @@ import javax.annotation.CheckForNull;
@SuppressWarnings("serial") // we're overriding default serialization
@ElementTypesAreNonnullByDefault
final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
- @SuppressWarnings("rawtypes") // necessary to compile against Java 8
- static ImmutableSet asImmutable(EnumSet set) {
+ static <E extends Enum<E>> ImmutableSet<E> asImmutable(EnumSet<E> set) {
switch (set.size()) {
case 0:
return ImmutableSet.of();
case 1:
return ImmutableSet.of(Iterables.getOnlyElement(set));
default:
- return new ImmutableEnumSet(set);
+ return new ImmutableEnumSet<E>(set);
}
}
@@ -134,13 +136,20 @@ final class ImmutableEnumSet<E extends Enum<E>> extends ImmutableSet<E> {
// All callers of the constructor are restricted to <E extends Enum<E>>.
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new EnumSerializedForm<E>(delegate);
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/*
* This class is used to serialize ImmutableEnumSet instances.
*/
+ @J2ktIncompatible // serialization
private static class EnumSerializedForm<E extends Enum<E>> implements Serializable {
final EnumSet<E> delegate;
diff --git a/guava/src/com/google/common/collect/ImmutableList.java b/guava/src/com/google/common/collect/ImmutableList.java
index bc8166507..9c60caf3f 100644
--- a/guava/src/com/google/common/collect/ImmutableList.java
+++ b/guava/src/com/google/common/collect/ImmutableList.java
@@ -25,8 +25,8 @@ import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import static com.google.common.collect.RegularImmutableList.EMPTY;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
@@ -248,8 +248,8 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
*
* <p>Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)}
* returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while
- * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one element
- * (the given list itself).
+ * {@code ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one
+ * element (the given list itself).
*
* <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
* collection that is currently being modified by another thread.
@@ -577,7 +577,7 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
- public final void sort(Comparator<? super E> c) {
+ public final void sort(@Nullable Comparator<? super E> c) {
throw new UnsupportedOperationException();
}
@@ -702,6 +702,7 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
* Serializes ImmutableLists as their logical contents. This ensures that
* implementation types do not leak into the serialized representation.
*/
+ @J2ktIncompatible // serialization
static class SerializedForm implements Serializable {
final Object[] elements;
@@ -716,11 +717,13 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
private static final long serialVersionUID = 0;
}
+ @J2ktIncompatible // serialization
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm(toArray());
}
@@ -745,7 +748,6 @@ public abstract class ImmutableList<E> extends ImmutableCollection<E>
*
* @since 23.1
*/
- @Beta
public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new ImmutableList.Builder<E>(expectedSize);
diff --git a/guava/src/com/google/common/collect/ImmutableListMultimap.java b/guava/src/com/google/common/collect/ImmutableListMultimap.java
index 0184c5bf1..b46e7ae40 100644
--- a/guava/src/com/google/common/collect/ImmutableListMultimap.java
+++ b/guava/src/com/google/common/collect/ImmutableListMultimap.java
@@ -16,10 +16,9 @@
package com.google.common.collect;
-
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
@@ -244,7 +243,6 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -347,7 +345,6 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableListMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return new Builder<K, V>().putAll(entries).build();
@@ -356,7 +353,7 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
/** Creates an ImmutableListMultimap from an asMap.entrySet. */
static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
- @Nullable Comparator<? super V> valueComparator) {
+ @CheckForNull Comparator<? super V> valueComparator) {
if (mapEntries.isEmpty()) {
return of();
}
@@ -458,12 +455,14 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
* values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int keyCount = stream.readInt();
@@ -500,5 +499,6 @@ public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
}
@GwtIncompatible // Not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/ImmutableMap.java b/guava/src/com/google/common/collect/ImmutableMap.java
index b24ed6c73..c370e5248 100644
--- a/guava/src/com/google/common/collect/ImmutableMap.java
+++ b/guava/src/com/google/common/collect/ImmutableMap.java
@@ -22,8 +22,8 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
@@ -31,6 +31,8 @@ import com.google.errorprone.annotations.DoNotMock;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.WeakOuter;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.BitSet;
@@ -359,7 +361,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
*
* @since 23.1
*/
- @Beta
public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<>(expectedSize);
@@ -485,7 +486,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
if (entries instanceof Collection) {
ensureCapacity(size + ((Collection<?>) entries).size());
@@ -507,7 +507,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
checkState(this.valueComparator == null, "valueComparator was already set");
this.valueComparator = checkNotNull(valueComparator, "valueComparator");
@@ -554,20 +553,20 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
if (entriesUsed) {
entries = Arrays.copyOf(entries, size);
}
- localEntries = entries;
+ @SuppressWarnings("nullness") // entries 0..localSize-1 are non-null
+ Entry<K, V>[] nonNullEntries = (Entry<K, V>[]) entries;
if (!throwIfDuplicateKeys) {
// We want to retain only the last-put value for any given key, before sorting.
// This could be improved, but orderEntriesByValue is rather rarely used anyway.
- @SuppressWarnings("nullness") // entries 0..size-1 are non-null
- Entry<K, V>[] nonNullEntries = (Entry<K, V>[]) localEntries;
- localEntries = lastEntryForEachKey(nonNullEntries, size);
- localSize = localEntries.length;
+ nonNullEntries = lastEntryForEachKey(nonNullEntries, size);
+ localSize = nonNullEntries.length;
}
Arrays.sort(
- localEntries,
+ nonNullEntries,
0,
localSize,
Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
+ localEntries = (@Nullable Entry<K, V>[]) nonNullEntries;
}
entriesUsed = true;
return RegularImmutableMap.fromEntryArray(localSize, localEntries, throwIfDuplicateKeys);
@@ -680,7 +679,10 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
}
} else if (map instanceof EnumMap) {
@SuppressWarnings("unchecked") // safe since map is not writable
- ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) copyOfEnumMap((EnumMap<?, ?>) map);
+ ImmutableMap<K, V> kvMap =
+ (ImmutableMap<K, V>)
+ copyOfEnumMap(
+ (EnumMap<?, ? extends V>) map); // hide K (violates bounds) from J2KT, preserve V.
return kvMap;
}
return copyOf(map.entrySet());
@@ -694,7 +696,6 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* @throws IllegalArgumentException if two entries have the same key
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
@SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
@@ -715,9 +716,9 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
}
}
- private static <K extends Enum<K>, V> ImmutableMap<K, V> copyOfEnumMap(
- EnumMap<K, ? extends V> original) {
- EnumMap<K, V> copy = new EnumMap<>(original);
+ private static <K extends Enum<K>, V> ImmutableMap<K, ? extends V> copyOfEnumMap(
+ EnumMap<?, ? extends V> original) {
+ EnumMap<K, V> copy = new EnumMap<>((EnumMap<K, ? extends V>) original);
for (Entry<K, V> entry : copy.entrySet()) {
checkEntryNotNull(entry.getKey(), entry.getValue());
}
@@ -872,8 +873,9 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
+ @CheckForNull
public final V merge(
- K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+ K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
throw new UnsupportedOperationException();
}
@@ -1191,6 +1193,7 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* reconstructed using public factory methods. This ensures that the implementation types remain
* as implementation details.
*/
+ @J2ktIncompatible // serialization
static class SerializedForm<K, V> implements Serializable {
// This object retains references to collections returned by keySet() and value(). This saves
// bytes when the both the map and its keySet or value collection are written to the same
@@ -1270,7 +1273,13 @@ public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
* method. Publicly-accessible subclasses must override this method and should return a subclass
* of SerializedForm whose readResolve() method returns objects of the subclass type.
*/
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/guava/src/com/google/common/collect/ImmutableMapEntry.java b/guava/src/com/google/common/collect/ImmutableMapEntry.java
index ac483d8fd..7c90b3f2a 100644
--- a/guava/src/com/google/common/collect/ImmutableMapEntry.java
+++ b/guava/src/com/google/common/collect/ImmutableMapEntry.java
@@ -80,7 +80,7 @@ class ImmutableMapEntry<K, V> extends ImmutableEntry<K, V> {
static class NonTerminalImmutableMapEntry<K, V> extends ImmutableMapEntry<K, V> {
/*
* Yes, we sometimes set nextInKeyBucket to null, even for this "non-terminal" entry. We don't
- * do that with a plain NonTerminalImmutableMapEntry, but we do do it with the BiMap-specific
+ * do that with a plain NonTerminalImmutableMapEntry, but we do it with the BiMap-specific
* subclass below. That's because the Entry might be non-terminal in the key bucket but terminal
* in the value bucket (or vice versa).
*/
diff --git a/guava/src/com/google/common/collect/ImmutableMapEntrySet.java b/guava/src/com/google/common/collect/ImmutableMapEntrySet.java
index 6f5503af5..46df158b0 100644
--- a/guava/src/com/google/common/collect/ImmutableMapEntrySet.java
+++ b/guava/src/com/google/common/collect/ImmutableMapEntrySet.java
@@ -18,6 +18,9 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Map.Entry;
import java.util.Spliterator;
@@ -115,12 +118,20 @@ abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet.CachingAsList<Ent
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new EntrySetSerializedForm<>(map());
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use EntrySetSerializedForm");
+ }
+
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
private static class EntrySetSerializedForm<K, V> implements Serializable {
final ImmutableMap<K, V> map;
diff --git a/guava/src/com/google/common/collect/ImmutableMapKeySet.java b/guava/src/com/google/common/collect/ImmutableMapKeySet.java
index d10ee10e7..6d1b51671 100644
--- a/guava/src/com/google/common/collect/ImmutableMapKeySet.java
+++ b/guava/src/com/google/common/collect/ImmutableMapKeySet.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.Spliterator;
import java.util.function.Consumer;
@@ -78,6 +79,7 @@ final class ImmutableMapKeySet<K, V> extends IndexedImmutableSet<K> {
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
+ @J2ktIncompatible
@SuppressWarnings("unused")
private static class KeySetSerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
diff --git a/guava/src/com/google/common/collect/ImmutableMapValues.java b/guava/src/com/google/common/collect/ImmutableMapValues.java
index 702191c64..8884c1af6 100644
--- a/guava/src/com/google/common/collect/ImmutableMapValues.java
+++ b/guava/src/com/google/common/collect/ImmutableMapValues.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.Map.Entry;
import java.util.Spliterator;
@@ -103,6 +104,7 @@ final class ImmutableMapValues<K, V> extends ImmutableCollection<V> {
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
+ @J2ktIncompatible
@SuppressWarnings("unused")
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
diff --git a/guava/src/com/google/common/collect/ImmutableMultimap.java b/guava/src/com/google/common/collect/ImmutableMultimap.java
index d16e1bc56..f1f654645 100644
--- a/guava/src/com/google/common/collect/ImmutableMultimap.java
+++ b/guava/src/com/google/common/collect/ImmutableMultimap.java
@@ -21,14 +21,16 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.Maps.immutableEntry;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
@@ -193,7 +195,6 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
for (Entry<? extends K, ? extends V> entry : entries) {
put(entry);
@@ -331,7 +332,6 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return ImmutableListMultimap.copyOf(entries);
@@ -344,6 +344,7 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
// holder class makes sure they are not initialized unless an instance is
// deserialized.
@GwtIncompatible // java serialization is not supported
+ @J2ktIncompatible
static class FieldSettersHolder {
static final Serialization.FieldSetter<ImmutableMultimap> MAP_FIELD_SETTER =
Serialization.getFieldSetter(ImmutableMultimap.class, "map");
@@ -682,13 +683,21 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
}
@GwtIncompatible
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new KeysSerializedForm(ImmutableMultimap.this);
}
+
+ @GwtIncompatible
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use KeysSerializedForm");
+ }
}
@GwtIncompatible
+ @J2ktIncompatible
private static final class KeysSerializedForm implements Serializable {
final ImmutableMultimap<?, ?> multimap;
@@ -772,8 +781,10 @@ public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V
return true;
}
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/ImmutableMultiset.java b/guava/src/com/google/common/collect/ImmutableMultiset.java
index b05ab3fe0..cdc9f405a 100644
--- a/guava/src/com/google/common/collect/ImmutableMultiset.java
+++ b/guava/src/com/google/common/collect/ImmutableMultiset.java
@@ -21,11 +21,14 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -402,15 +405,23 @@ public abstract class ImmutableMultiset<E> extends ImmutableMultisetGwtSerializa
}
@GwtIncompatible
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
}
- private static final long serialVersionUID = 0;
+ @GwtIncompatible
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use EntrySetSerializedForm");
+ }
+
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
@GwtIncompatible
+ @J2ktIncompatible
static class EntrySetSerializedForm<E> implements Serializable {
final ImmutableMultiset<E> multiset;
@@ -424,11 +435,18 @@ public abstract class ImmutableMultiset<E> extends ImmutableMultisetGwtSerializa
}
@GwtIncompatible
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm(this);
}
+ @GwtIncompatible
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
@@ -614,6 +632,7 @@ public abstract class ImmutableMultiset<E> extends ImmutableMultisetGwtSerializa
}
}
+ @J2ktIncompatible
static final class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
diff --git a/guava/src/com/google/common/collect/ImmutableRangeMap.java b/guava/src/com/google/common/collect/ImmutableRangeMap.java
index e1979ab65..72444245f 100644
--- a/guava/src/com/google/common/collect/ImmutableRangeMap.java
+++ b/guava/src/com/google/common/collect/ImmutableRangeMap.java
@@ -18,13 +18,15 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
@@ -44,7 +46,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K, V>, Serializable {
@@ -258,7 +259,7 @@ public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
- public final void putAll(RangeMap<K, V> rangeMap) {
+ public final void putAll(RangeMap<K, ? extends V> rangeMap) {
throw new UnsupportedOperationException();
}
@@ -439,5 +440,10 @@ public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K
return new SerializedForm<>(asMapOfRanges());
}
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/ImmutableRangeSet.java b/guava/src/com/google/common/collect/ImmutableRangeSet.java
index f279aae0c..afd421cd7 100644
--- a/guava/src/com/google/common/collect/ImmutableRangeSet.java
+++ b/guava/src/com/google/common/collect/ImmutableRangeSet.java
@@ -22,14 +22,16 @@ import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER
import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
@@ -46,7 +48,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ImmutableRangeSet<C extends Comparable> extends AbstractRangeSet<C>
@@ -517,7 +518,7 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
* such a set can be performed efficiently, but others (such as {@link Set#hashCode} or {@link
* Collections#frequency}) can cause major performance problems.
*
- * <p>The returned set's {@link Object#toString} method returns a short-hand form of the set's
+ * <p>The returned set's {@link Object#toString} method returns a shorthand form of the set's
* contents, such as {@code "[1..100]}"}.
*
* @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if
@@ -554,7 +555,7 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
this.domain = domain;
}
- @CheckForNull private transient Integer size;
+ @LazyInit @CheckForNull private transient Integer size;
@Override
public int size() {
@@ -690,9 +691,15 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new AsSetSerializedForm<C>(ranges, domain);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
private static class AsSetSerializedForm<C extends Comparable> implements Serializable {
@@ -839,7 +846,13 @@ public final class ImmutableRangeSet<C extends Comparable> extends AbstractRange
}
}
+ @J2ktIncompatible // java.io.ObjectInputStream
Object writeReplace() {
return new SerializedForm<C>(ranges);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/guava/src/com/google/common/collect/ImmutableSet.java b/guava/src/com/google/common/collect/ImmutableSet.java
index 73d5b09bf..f4912a328 100644
--- a/guava/src/com/google/common/collect/ImmutableSet.java
+++ b/guava/src/com/google/common/collect/ImmutableSet.java
@@ -21,14 +21,16 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.Arrays;
@@ -404,6 +406,7 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
* static factories. This is necessary to ensure that the existence of a
* particular implementation type is an implementation detail.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm implements Serializable {
final Object[] elements;
@@ -419,10 +422,16 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm(toArray());
}
+ @J2ktIncompatible // serialization
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
@@ -443,7 +452,6 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
*
* @since 23.1
*/
- @Beta
public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
checkNonnegative(expectedSize, "expectedSize");
return new Builder<E>(expectedSize);
@@ -549,6 +557,7 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
return this;
}
+ @CanIgnoreReturnValue
Builder<E> combine(Builder<E> other) {
requireNonNull(impl);
requireNonNull(other.impl);
@@ -717,7 +726,7 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
*/
private static final class RegularSetBuilderImpl<E> extends SetBuilderImpl<E> {
// null until at least two elements are present
- private @Nullable Object @Nullable [] hashTable;
+ @CheckForNull private @Nullable Object[] hashTable;
private int maxRunBeforeFallback;
private int expandTableThreshold;
private int hashCode;
@@ -857,7 +866,7 @@ public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements
/**
* We attempt to detect deliberate hash flooding attempts. If one is detected, we fall back to a
- * wrapper around j.u.HashSet, which has built in flooding protection. MAX_RUN_MULTIPLIER was
+ * wrapper around j.u.HashSet, which has built-in flooding protection. MAX_RUN_MULTIPLIER was
* determined experimentally to match our desired probability of false positives.
*/
// NB: yes, this is surprisingly high, but that's what the experiments said was necessary
diff --git a/guava/src/com/google/common/collect/ImmutableSetMultimap.java b/guava/src/com/google/common/collect/ImmutableSetMultimap.java
index 52d6e55c3..4887ae79b 100644
--- a/guava/src/com/google/common/collect/ImmutableSetMultimap.java
+++ b/guava/src/com/google/common/collect/ImmutableSetMultimap.java
@@ -18,9 +18,9 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
@@ -278,7 +278,6 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -401,7 +400,6 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableSetMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return new Builder<K, V>().putAll(entries).build();
@@ -581,6 +579,7 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
* values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(valueComparator());
@@ -595,12 +594,14 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
}
@GwtIncompatible // java serialization
+ @J2ktIncompatible
private static final class SetFieldSettersHolder {
static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
// Serialization type safety is at the caller's mercy.
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
@@ -645,5 +646,6 @@ public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
}
@GwtIncompatible // not needed in emulated source.
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/ImmutableSortedMap.java b/guava/src/com/google/common/collect/ImmutableSortedMap.java
index ab971937d..f38922e43 100644
--- a/guava/src/com/google/common/collect/ImmutableSortedMap.java
+++ b/guava/src/com/google/common/collect/ImmutableSortedMap.java
@@ -22,10 +22,12 @@ import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.Maps.keyOrNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Comparator;
@@ -89,9 +91,9 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* keys and values are the result of applying the provided mapping functions to the input
* elements.
*
- * <p>If the mapped keys contain duplicates (according to the comparator), the the values are
- * merged using the specified merging function. Entries will appear in the encounter order of the
- * first occurrence of the key.
+ * <p>If the mapped keys contain duplicates (according to the comparator), the values are merged
+ * using the specified merging function. Entries will appear in the encounter order of the first
+ * occurrence of the key.
*
* @since 21.0
*/
@@ -403,7 +405,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @throws IllegalArgumentException if any two keys are equal according to the comparator
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
// Hack around K not being a subtype of Comparable.
@@ -421,7 +422,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @throws IllegalArgumentException if any two keys are equal according to the comparator
* @since 19.0
*/
- @Beta
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries,
Comparator<? super K> comparator) {
@@ -535,14 +535,11 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
entryArray,
0,
size,
- new Comparator<@Nullable Entry<K, V>>() {
- @Override
- public int compare(@CheckForNull Entry<K, V> e1, @CheckForNull Entry<K, V> e2) {
- // requireNonNull is safe because the first `size` elements have been filled in.
- requireNonNull(e1);
- requireNonNull(e2);
- return comparator.compare(e1.getKey(), e2.getKey());
- }
+ (e1, e2) -> {
+ // requireNonNull is safe because the first `size` elements have been filled in.
+ requireNonNull(e1);
+ requireNonNull(e2);
+ return comparator.compare(e1.getKey(), e2.getKey());
});
// requireNonNull is safe because the first `size` elements have been filled in.
Entry<K, V> firstEntry = requireNonNull(entryArray[0]);
@@ -594,7 +591,7 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* their natural ordering.
*/
public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
- return new Builder<>(Ordering.natural().reverse());
+ return new Builder<>(Ordering.<K>natural().reverse());
}
/**
@@ -679,7 +676,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @since 19.0
*/
@CanIgnoreReturnValue
- @Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
@@ -693,7 +689,6 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* @deprecated Unsupported by ImmutableSortedMap.Builder.
*/
@CanIgnoreReturnValue
- @Beta
@Override
@Deprecated
@DoNotCall("Always throws UnsupportedOperationException")
@@ -1109,16 +1104,18 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
@Override
public ImmutableSortedMap<K, V> descendingMap() {
- // TODO(kevinb): the descendingMap is never actually cached at all. Either it should be or the
- // code below simplified.
+ // TODO(kevinb): The descendingMap is never actually cached at all. Either:
+ //
+ // - Cache it, and annotate the field with @LazyInit.
+ // - Simplify the code below, and consider eliminating the field (b/287198172), which is also
+ // set by one of the constructors.
ImmutableSortedMap<K, V> result = descendingMap;
if (result == null) {
if (isEmpty()) {
- return result = emptyMap(Ordering.from(comparator()).reverse());
+ return emptyMap(Ordering.from(comparator()).reverse());
} else {
- return result =
- new ImmutableSortedMap<>(
- (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this);
+ return new ImmutableSortedMap<>(
+ (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this);
}
}
return result;
@@ -1139,6 +1136,7 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
* are reconstructed using public factory methods. This ensures that the implementation types
* remain as implementation details.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
private final Comparator<? super K> comparator;
@@ -1156,10 +1154,16 @@ public final class ImmutableSortedMap<K, V> extends ImmutableSortedMapFauxveride
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<>(this);
}
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
diff --git a/guava/src/com/google/common/collect/ImmutableSortedMultiset.java b/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
index 0638df04e..d2991bce9 100644
--- a/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
+++ b/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
@@ -18,9 +18,12 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -417,7 +420,7 @@ public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultiset
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>.
*/
public static <E extends Comparable<?>> Builder<E> reverseOrder() {
- return new Builder<E>(Ordering.natural().reverse());
+ return new Builder<E>(Ordering.<E>natural().reverse());
}
/**
@@ -563,6 +566,7 @@ public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultiset
}
}
+ @J2ktIncompatible // serialization
private static final class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final E[] elements;
@@ -593,7 +597,13 @@ public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultiset
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<E>(this);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
}
diff --git a/guava/src/com/google/common/collect/ImmutableSortedSet.java b/guava/src/com/google/common/collect/ImmutableSortedSet.java
index 20d007271..c730fa496 100644
--- a/guava/src/com/google/common/collect/ImmutableSortedSet.java
+++ b/guava/src/com/google/common/collect/ImmutableSortedSet.java
@@ -22,6 +22,7 @@ import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.concurrent.LazyInit;
@@ -359,8 +360,8 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
* elements are in the first {@code k} positions of {@code contents}, and {@code contents[i] ==
* null} for {@code k <= i < n}.
*
- * <p>If {@code k == contents.length}, then {@code contents} may no longer be safe for
- * modification.
+ * <p>This method takes ownership of {@code contents}; do not modify {@code contents} after this
+ * returns.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code contents} is null
*/
@@ -695,21 +696,21 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
@Override
@CheckForNull
public E lower(E e) {
- return Iterators.getNext(headSet(e, false).descendingIterator(), null);
+ return Iterators.<@Nullable E>getNext(headSet(e, false).descendingIterator(), null);
}
/** @since 12.0 */
@Override
@CheckForNull
public E floor(E e) {
- return Iterators.getNext(headSet(e, true).descendingIterator(), null);
+ return Iterators.<@Nullable E>getNext(headSet(e, true).descendingIterator(), null);
}
/** @since 12.0 */
@Override
@CheckForNull
public E ceiling(E e) {
- return Iterables.getFirst(tailSet(e, true), null);
+ return Iterables.<@Nullable E>getFirst(tailSet(e, true), null);
}
/** @since 12.0 */
@@ -717,7 +718,7 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
@Override
@CheckForNull
public E higher(E e) {
- return Iterables.getFirst(tailSet(e, false), null);
+ return Iterables.<@Nullable E>getFirst(tailSet(e, false), null);
}
@Override
@@ -825,6 +826,7 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
* only. This is necessary to ensure that the existence of a particular
* implementation type is an implementation detail.
*/
+ @J2ktIncompatible // serialization
private static class SerializedForm<E> implements Serializable {
final Comparator<? super E> comparator;
final Object[] elements;
@@ -842,11 +844,13 @@ public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxveride
private static final long serialVersionUID = 0;
}
+ @J2ktIncompatible // serialization
private void readObject(ObjectInputStream unused) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new SerializedForm<E>(comparator, toArray());
}
diff --git a/guava/src/com/google/common/collect/ImmutableTable.java b/guava/src/com/google/common/collect/ImmutableTable.java
index 033c271e6..62cae079f 100644
--- a/guava/src/com/google/common/collect/ImmutableTable.java
+++ b/guava/src/com/google/common/collect/ImmutableTable.java
@@ -19,10 +19,14 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.DoNotMock;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
@@ -502,4 +506,12 @@ public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V>
final Object writeReplace() {
return createSerializedForm();
}
+
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
+ private static final long serialVersionUID = 0xcafebabe;
}
diff --git a/guava/src/com/google/common/collect/Interner.java b/guava/src/com/google/common/collect/Interner.java
index bfc2035f1..8b48fcded 100644
--- a/guava/src/com/google/common/collect/Interner.java
+++ b/guava/src/com/google/common/collect/Interner.java
@@ -17,7 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
/**
@@ -32,6 +32,7 @@ import com.google.errorprone.annotations.DoNotMock;
* @since 3.0
*/
@DoNotMock("Use Interners.new*Interner")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface Interner<E> {
@@ -47,6 +48,5 @@ public interface Interner<E> {
*
* @throws NullPointerException if {@code sample} is null
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Consider removing this?
E intern(E sample);
}
diff --git a/guava/src/com/google/common/collect/Interners.java b/guava/src/com/google/common/collect/Interners.java
index 10ae27463..449806b43 100644
--- a/guava/src/com/google/common/collect/Interners.java
+++ b/guava/src/com/google/common/collect/Interners.java
@@ -17,6 +17,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
@@ -30,6 +31,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 3.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Interners {
diff --git a/guava/src/com/google/common/collect/Iterables.java b/guava/src/com/google/common/collect/Iterables.java
index 7928b15d6..eef28a4fd 100644
--- a/guava/src/com/google/common/collect/Iterables.java
+++ b/guava/src/com/google/common/collect/Iterables.java
@@ -20,7 +20,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkRemove;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
@@ -40,6 +39,7 @@ import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -286,12 +286,8 @@ public final class Iterables {
* @return a newly-allocated array into which all the elements of the iterable have been copied
*/
@GwtIncompatible // Array.newInstance(Class, int)
- /*
- * If we could express Class<@Nonnull T>, we could generalize the type parameter to <T extends
- * @Nullable Object>, and then we could accept an Iterable<? extends T> and return a plain T[]
- * instead of a @Nullable T[].
- */
- public static <T> @Nullable T[] toArray(Iterable<? extends @Nullable T> iterable, Class<T> type) {
+ public static <T extends @Nullable Object> T[] toArray(
+ Iterable<? extends T> iterable, Class<@NonNull T> type) {
return toArray(iterable, ObjectArrays.newArray(type, 0));
}
@@ -997,10 +993,13 @@ public final class Iterables {
* Returns a view of the supplied iterable that wraps each generated {@link Iterator} through
* {@link Iterators#consumingIterator(Iterator)}.
*
- * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will get entries from
- * {@link Queue#remove()} since {@link Queue}'s iteration order is undefined. Calling {@link
- * Iterator#hasNext()} on a generated iterator from the returned iterable may cause an item to be
- * immediately dequeued for return on a subsequent call to {@link Iterator#next()}.
+ * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will instead use {@link
+ * Queue#isEmpty} and {@link Queue#remove()}, since {@link Queue}'s iteration order is undefined.
+ * Calling {@link Iterator#hasNext()} on a generated iterator from the returned iterable may cause
+ * an item to be immediately dequeued for return on a subsequent call to {@link Iterator#next()}.
+ *
+ * <p>Whether the input {@code iterable} is a {@link Queue} or not, the returned {@code Iterable}
+ * is not thread-safe.
*
* @param iterable the iterable to wrap
* @return a view of the supplied iterable that wraps each generated iterator through {@link
@@ -1060,7 +1059,6 @@ public final class Iterables {
*
* @since 11.0
*/
- @Beta
public static <T extends @Nullable Object> Iterable<T> mergeSorted(
final Iterable<? extends Iterable<? extends T>> iterables,
final Comparator<? super T> comparator) {
@@ -1071,21 +1069,9 @@ public final class Iterables {
@Override
public Iterator<T> iterator() {
return Iterators.mergeSorted(
- Iterables.transform(iterables, Iterables.<T>toIterator()), comparator);
+ Iterables.transform(iterables, Iterable::iterator), comparator);
}
};
return new UnmodifiableIterable<>(iterable);
}
-
- // TODO(user): Is this the best place for this? Move to fluent functions?
- // Useful as a public method?
- static <T extends @Nullable Object>
- Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() {
- return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
- @Override
- public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
- return iterable.iterator();
- }
- };
- }
}
diff --git a/guava/src/com/google/common/collect/Iterators.java b/guava/src/com/google/common/collect/Iterators.java
index 2f9fd3b4a..0699202fe 100644
--- a/guava/src/com/google/common/collect/Iterators.java
+++ b/guava/src/com/google/common/collect/Iterators.java
@@ -24,7 +24,6 @@ import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
@@ -48,6 +47,7 @@ import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -345,10 +345,10 @@ public final class Iterators {
* @return a newly-allocated array into which all the elements of the iterator have been copied
*/
@GwtIncompatible // Array.newInstance(Class, int)
- // For discussion of this signature, see the corresponding overload of *Iterables*.toArray.
- public static <T> @Nullable T[] toArray(Iterator<? extends @Nullable T> iterator, Class<T> type) {
- List<@Nullable T> list = Lists.newArrayList(iterator);
- return Iterables.toArray(list, type);
+ public static <T extends @Nullable Object> T[] toArray(
+ Iterator<? extends T> iterator, Class<@NonNull T> type) {
+ List<T> list = Lists.newArrayList(iterator);
+ return Iterables.<T>toArray(list, type);
}
/**
@@ -988,7 +988,8 @@ public final class Iterators {
* {@code iterator} as it is returned.
*
* <p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator
- * will fail on the first call to {@code next}.
+ * will fail on the first call to {@code next}. The returned {@link Iterator} is also not
+ * thread-safe.
*
* @param iterator the iterator to remove and return elements from
* @return an iterator that removes and returns elements from the supplied iterator
@@ -1294,7 +1295,6 @@ public final class Iterators {
*
* @since 11.0
*/
- @Beta
public static <T extends @Nullable Object> UnmodifiableIterator<T> mergeSorted(
Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) {
checkNotNull(iterators, "iterators");
diff --git a/guava/src/com/google/common/collect/JdkBackedImmutableMultiset.java b/guava/src/com/google/common/collect/JdkBackedImmutableMultiset.java
index faf22b343..41d95f045 100644
--- a/guava/src/com/google/common/collect/JdkBackedImmutableMultiset.java
+++ b/guava/src/com/google/common/collect/JdkBackedImmutableMultiset.java
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Ints;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.util.Collection;
import java.util.Map;
import javax.annotation.CheckForNull;
@@ -66,7 +67,7 @@ final class JdkBackedImmutableMultiset<E> extends ImmutableMultiset<E> {
return delegateMap.getOrDefault(element, 0);
}
- @CheckForNull private transient ImmutableSet<E> elementSet;
+ @LazyInit @CheckForNull private transient ImmutableSet<E> elementSet;
@Override
public ImmutableSet<E> elementSet() {
diff --git a/guava/src/com/google/common/collect/LinkedHashMultimap.java b/guava/src/com/google/common/collect/LinkedHashMultimap.java
index 8076cf870..78afd3268 100644
--- a/guava/src/com/google/common/collect/LinkedHashMultimap.java
+++ b/guava/src/com/google/common/collect/LinkedHashMultimap.java
@@ -23,6 +23,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -172,8 +173,8 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
* always call succeedsIn*() to initialize them immediately thereafter.
*
* The exception is the *InValueSet fields of multimapHeaderEntry, which are never set. (That
- * works out fine as long as we continue to be careful not to try delete them or iterate past
- * them.)
+ * works out fine as long as we continue to be careful not to try to delete them or iterate
+ * past them.)
*
* We could consider "lying" and omitting @CheckNotNull from all these fields. Normally, I'm not
* a fan of that: What if we someday implement (presumably to be enabled during tests only)
@@ -187,7 +188,7 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
* hopefully could avoid implementing Entry or ValueSetLink at all. (But note that that approach
* requires us to define extra classes -- unfortunate under Android.) *Then* we could consider
* lying about the fields below on the grounds that we always initialize them just after the
- * constructor -- an example of the kind of lying that our hypotheticaly bytecode rewriter would
+ * constructor -- an example of the kind of lying that our hypothetical bytecode rewriter would
* already have to deal with, thanks to DI frameworks that perform field and method injection,
* frameworks like Android that define post-construct hooks like Activity.onCreate, etc.
*/
@@ -616,6 +617,7 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
* and the entries in order
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(keySet().size());
@@ -630,6 +632,7 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
multimapHeaderEntry = ValueEntry.newHeader();
@@ -658,5 +661,6 @@ public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nul
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 1;
}
diff --git a/guava/src/com/google/common/collect/LinkedHashMultiset.java b/guava/src/com/google/common/collect/LinkedHashMultiset.java
index 5ee2015e9..21e290467 100644
--- a/guava/src/com/google/common/collect/LinkedHashMultiset.java
+++ b/guava/src/com/google/common/collect/LinkedHashMultiset.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -86,12 +87,14 @@ public final class LinkedHashMultiset<E extends @Nullable Object>
* its count, and so on
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultiset(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int distinctElements = Serialization.readCount(stream);
@@ -100,5 +103,6 @@ public final class LinkedHashMultiset<E extends @Nullable Object>
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/LinkedListMultimap.java b/guava/src/com/google/common/collect/LinkedListMultimap.java
index a69243469..d88564ca5 100644
--- a/guava/src/com/google/common/collect/LinkedListMultimap.java
+++ b/guava/src/com/google/common/collect/LinkedListMultimap.java
@@ -24,6 +24,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
@@ -213,7 +214,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
/**
* Adds a new node for the specified key-value pair before the specified {@code nextSibling}
* element, or at the end of the list if {@code nextSibling} is null. Note: if {@code nextSibling}
- * is specified, it MUST be for an node for the same {@code key}!
+ * is specified, it MUST be for a node for the same {@code key}!
*/
@CanIgnoreReturnValue
private Node<K, V> addNode(
@@ -678,7 +679,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
*/
@CanIgnoreReturnValue
@Override
- public List<V> removeAll(@Nullable Object key) {
+ public List<V> removeAll(@CheckForNull Object key) {
/*
* Safe because all we do is remove values for the key, not add them. (If we wanted to make sure
* to call getCopy and removeAllNodes only with a true K, then we could check containsKey first.
@@ -863,6 +864,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
* from the entries() ordering
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
@@ -873,6 +875,7 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyToKeyList = Maps.newLinkedHashMap();
@@ -887,5 +890,6 @@ public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/Lists.java b/guava/src/com/google/common/collect/Lists.java
index 55dc73e37..0816b754a 100644
--- a/guava/src/com/google/common/collect/Lists.java
+++ b/guava/src/com/google/common/collect/Lists.java
@@ -25,9 +25,9 @@ import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
@@ -251,6 +251,7 @@ public final class Lists {
* @return a new, empty {@code CopyOnWriteArrayList}
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArrayList
public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
return new CopyOnWriteArrayList<>();
@@ -263,6 +264,7 @@ public final class Lists {
* @return a new {@code CopyOnWriteArrayList} containing those elements
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArrayList
public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
Iterable<? extends E> elements) {
@@ -338,7 +340,7 @@ public final class Lists {
return (index == 0) ? first : rest[index - 1];
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
/** @see Lists#asList(Object, Object, Object[]) */
@@ -374,7 +376,7 @@ public final class Lists {
}
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
}
/**
@@ -554,8 +556,8 @@ public final class Lists {
* can be overkill. That's why we forward this call directly to the backing list.
*/
@Override
- public void clear() {
- fromList.clear();
+ protected void removeRange(int fromIndex, int toIndex) {
+ fromList.subList(fromIndex, toIndex).clear();
}
@Override
@@ -601,9 +603,13 @@ public final class Lists {
this.function = checkNotNull(function);
}
+ /**
+ * The default implementation inherited is based on iteration and removal of each element which
+ * can be overkill. That's why we forward this call directly to the backing list.
+ */
@Override
- public void clear() {
- fromList.clear();
+ protected void removeRange(int fromIndex, int toIndex) {
+ fromList.subList(fromIndex, toIndex).clear();
}
@Override
@@ -627,6 +633,8 @@ public final class Lists {
};
}
+ // TODO: cpovirk - Why override `isEmpty` here but not in TransformingSequentialList?
+
@Override
public boolean isEmpty() {
return fromList.isEmpty();
@@ -728,7 +736,6 @@ public final class Lists {
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
- @Beta
public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
@@ -1104,7 +1111,7 @@ public final class Lists {
return backingList.listIterator(index);
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
};
} else {
wrapper =
@@ -1114,7 +1121,7 @@ public final class Lists {
return backingList.listIterator(index);
}
- private static final long serialVersionUID = 0;
+ @J2ktIncompatible private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
diff --git a/guava/src/com/google/common/collect/MapMaker.java b/guava/src/com/google/common/collect/MapMaker.java
index a2612c1bd..4fb4ec824 100644
--- a/guava/src/com/google/common/collect/MapMaker.java
+++ b/guava/src/com/google/common/collect/MapMaker.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Equivalence;
import com.google.common.base.MoreObjects;
@@ -85,6 +86,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 2.0
*/
+@J2ktIncompatible
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class MapMaker {
diff --git a/guava/src/com/google/common/collect/MapMakerInternalMap.java b/guava/src/com/google/common/collect/MapMakerInternalMap.java
index 3725d9723..c64d81eb3 100644
--- a/guava/src/com/google/common/collect/MapMakerInternalMap.java
+++ b/guava/src/com/google/common/collect/MapMakerInternalMap.java
@@ -18,15 +18,18 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.collect.MapMaker.Dummy;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
+import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@@ -47,7 +50,7 @@ import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
-import org.checkerframework.checker.nullness.qual.Nullable;
+import javax.annotation.CheckForNull;
/**
* The concurrent hash map implementation built by {@link MapMaker}.
@@ -64,6 +67,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Doug Lea ({@code ConcurrentHashMap})
*/
// TODO(kak): Consider removing @CanIgnoreReturnValue from this class.
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings({
"GuardedBy", // TODO(b/35466881): Fix or suppress.
@@ -130,8 +134,6 @@ class MapMakerInternalMap<
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
- static final long CLEANUP_EXECUTOR_DELAY_SECS = 60;
-
// Fields
/**
@@ -193,7 +195,7 @@ class MapMakerInternalMap<
}
for (int i = 0; i < this.segments.length; ++i) {
- this.segments[i] = createSegment(segmentSize, MapMaker.UNSET_INT);
+ this.segments[i] = createSegment(segmentSize);
}
}
@@ -290,18 +292,18 @@ class MapMakerInternalMap<
Strength valueStrength();
/** Returns a freshly created segment, typed at the {@code S} type. */
- S newSegment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity, int maxSegmentSize);
+ S newSegment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity);
/**
* Returns a freshly created entry, typed at the {@code E} type, for the given {@code segment}.
*/
- E newEntry(S segment, K key, int hash, @Nullable E next);
+ E newEntry(S segment, K key, int hash, @CheckForNull E next);
/**
* Returns a freshly created entry, typed at the {@code E} type, for the given {@code segment},
* that is a copy of the given {@code entry}.
*/
- E copy(S segment, E entry, @Nullable E newNext);
+ E copy(S segment, E entry, @CheckForNull E newNext);
/**
* Sets the value of the given {@code entry} in the given {@code segment} to be the given {@code
@@ -343,27 +345,26 @@ class MapMakerInternalMap<
implements InternalEntry<K, V, E> {
final K key;
final int hash;
- final @Nullable E next;
- AbstractStrongKeyEntry(K key, int hash, @Nullable E next) {
+ AbstractStrongKeyEntry(K key, int hash) {
this.key = key;
this.hash = hash;
- this.next = next;
}
@Override
- public K getKey() {
- return this.key;
+ public final K getKey() {
+ return key;
}
@Override
- public int getHash() {
+ public final int getHash() {
return hash;
}
@Override
+ @CheckForNull
public E getNext() {
- return next;
+ return null;
}
}
@@ -375,12 +376,6 @@ class MapMakerInternalMap<
interface WeakValueEntry<K, V, E extends InternalEntry<K, V, E>> extends InternalEntry<K, V, E> {
/** Gets the weak value reference held by entry. */
WeakValueReference<K, V, E> getValueReference();
-
- /**
- * Clears the weak value reference held by the entry. Should be used when the entry's value is
- * overwritten.
- */
- void clearValue();
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
@@ -390,29 +385,34 @@ class MapMakerInternalMap<
}
/** Concrete implementation of {@link InternalEntry} for strong keys and strong values. */
- static final class StrongKeyStrongValueEntry<K, V>
+ static class StrongKeyStrongValueEntry<K, V>
extends AbstractStrongKeyEntry<K, V, StrongKeyStrongValueEntry<K, V>>
implements StrongValueEntry<K, V, StrongKeyStrongValueEntry<K, V>> {
- private volatile @Nullable V value = null;
+ @CheckForNull private volatile V value = null;
- StrongKeyStrongValueEntry(K key, int hash, @Nullable StrongKeyStrongValueEntry<K, V> next) {
- super(key, hash, next);
+ private StrongKeyStrongValueEntry(K key, int hash) {
+ super(key, hash);
}
@Override
- public @Nullable V getValue() {
+ @CheckForNull
+ public final V getValue() {
return value;
}
- void setValue(V value) {
- this.value = value;
- }
+ private static final class LinkedStrongKeyStrongValueEntry<K, V>
+ extends StrongKeyStrongValueEntry<K, V> {
+ private final StrongKeyStrongValueEntry<K, V> next;
+
+ LinkedStrongKeyStrongValueEntry(K key, int hash, StrongKeyStrongValueEntry<K, V> next) {
+ super(key, hash);
+ this.next = next;
+ }
- StrongKeyStrongValueEntry<K, V> copy(StrongKeyStrongValueEntry<K, V> newNext) {
- StrongKeyStrongValueEntry<K, V> newEntry =
- new StrongKeyStrongValueEntry<>(this.key, this.hash, newNext);
- newEntry.value = this.value;
- return newEntry;
+ @Override
+ public StrongKeyStrongValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for strong keys and strong values. */
@@ -441,17 +441,19 @@ class MapMakerInternalMap<
MapMakerInternalMap<
K, V, StrongKeyStrongValueEntry<K, V>, StrongKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new StrongKeyStrongValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new StrongKeyStrongValueSegment<>(map, initialCapacity);
}
@Override
public StrongKeyStrongValueEntry<K, V> copy(
StrongKeyStrongValueSegment<K, V> segment,
StrongKeyStrongValueEntry<K, V> entry,
- @Nullable StrongKeyStrongValueEntry<K, V> newNext) {
- return entry.copy(newNext);
+ @CheckForNull StrongKeyStrongValueEntry<K, V> newNext) {
+ StrongKeyStrongValueEntry<K, V> newEntry =
+ newEntry(segment, entry.key, entry.hash, newNext);
+ newEntry.value = entry.value;
+ return newEntry;
}
@Override
@@ -459,7 +461,7 @@ class MapMakerInternalMap<
StrongKeyStrongValueSegment<K, V> segment,
StrongKeyStrongValueEntry<K, V> entry,
V value) {
- entry.setValue(value);
+ entry.value = value;
}
@Override
@@ -467,49 +469,49 @@ class MapMakerInternalMap<
StrongKeyStrongValueSegment<K, V> segment,
K key,
int hash,
- @Nullable StrongKeyStrongValueEntry<K, V> next) {
- return new StrongKeyStrongValueEntry<>(key, hash, next);
+ @CheckForNull StrongKeyStrongValueEntry<K, V> next) {
+ return next == null
+ ? new StrongKeyStrongValueEntry<>(key, hash)
+ : new LinkedStrongKeyStrongValueEntry<>(key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for strong keys and weak values. */
- static final class StrongKeyWeakValueEntry<K, V>
+ static class StrongKeyWeakValueEntry<K, V>
extends AbstractStrongKeyEntry<K, V, StrongKeyWeakValueEntry<K, V>>
implements WeakValueEntry<K, V, StrongKeyWeakValueEntry<K, V>> {
private volatile WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> valueReference =
unsetWeakValueReference();
- StrongKeyWeakValueEntry(K key, int hash, @Nullable StrongKeyWeakValueEntry<K, V> next) {
- super(key, hash, next);
+ private StrongKeyWeakValueEntry(K key, int hash) {
+ super(key, hash);
}
@Override
- public V getValue() {
+ @CheckForNull
+ public final V getValue() {
return valueReference.get();
}
@Override
- public void clearValue() {
- valueReference.clear();
+ public final WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> getValueReference() {
+ return valueReference;
}
- void setValue(V value, ReferenceQueue<V> queueForValues) {
- WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> previous = this.valueReference;
- this.valueReference = new WeakValueReferenceImpl<>(queueForValues, value, this);
- previous.clear();
- }
+ private static final class LinkedStrongKeyWeakValueEntry<K, V>
+ extends StrongKeyWeakValueEntry<K, V> {
+ private final StrongKeyWeakValueEntry<K, V> next;
- StrongKeyWeakValueEntry<K, V> copy(
- ReferenceQueue<V> queueForValues, StrongKeyWeakValueEntry<K, V> newNext) {
- StrongKeyWeakValueEntry<K, V> newEntry = new StrongKeyWeakValueEntry<>(key, hash, newNext);
- newEntry.valueReference = valueReference.copyFor(queueForValues, newEntry);
- return newEntry;
- }
+ LinkedStrongKeyWeakValueEntry(K key, int hash, StrongKeyWeakValueEntry<K, V> next) {
+ super(key, hash);
+ this.next = next;
+ }
- @Override
- public WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> getValueReference() {
- return valueReference;
+ @Override
+ public StrongKeyWeakValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for strong keys and weak values. */
@@ -537,26 +539,30 @@ class MapMakerInternalMap<
public StrongKeyWeakValueSegment<K, V> newSegment(
MapMakerInternalMap<K, V, StrongKeyWeakValueEntry<K, V>, StrongKeyWeakValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new StrongKeyWeakValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new StrongKeyWeakValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public StrongKeyWeakValueEntry<K, V> copy(
StrongKeyWeakValueSegment<K, V> segment,
StrongKeyWeakValueEntry<K, V> entry,
- @Nullable StrongKeyWeakValueEntry<K, V> newNext) {
+ @CheckForNull StrongKeyWeakValueEntry<K, V> newNext) {
if (Segment.isCollected(entry)) {
return null;
}
- return entry.copy(segment.queueForValues, newNext);
+ StrongKeyWeakValueEntry<K, V> newEntry = newEntry(segment, entry.key, entry.hash, newNext);
+ newEntry.valueReference = entry.valueReference.copyFor(segment.queueForValues, newEntry);
+ return newEntry;
}
@Override
public void setValue(
StrongKeyWeakValueSegment<K, V> segment, StrongKeyWeakValueEntry<K, V> entry, V value) {
- entry.setValue(value, segment.queueForValues);
+ WeakValueReference<K, V, StrongKeyWeakValueEntry<K, V>> previous = entry.valueReference;
+ entry.valueReference = new WeakValueReferenceImpl<>(segment.queueForValues, value, entry);
+ previous.clear();
}
@Override
@@ -564,29 +570,41 @@ class MapMakerInternalMap<
StrongKeyWeakValueSegment<K, V> segment,
K key,
int hash,
- @Nullable StrongKeyWeakValueEntry<K, V> next) {
- return new StrongKeyWeakValueEntry<>(key, hash, next);
+ @CheckForNull StrongKeyWeakValueEntry<K, V> next) {
+ return next == null
+ ? new StrongKeyWeakValueEntry<>(key, hash)
+ : new LinkedStrongKeyWeakValueEntry<>(key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for strong keys and {@link Dummy} values. */
- static final class StrongKeyDummyValueEntry<K>
+ static class StrongKeyDummyValueEntry<K>
extends AbstractStrongKeyEntry<K, Dummy, StrongKeyDummyValueEntry<K>>
implements StrongValueEntry<K, Dummy, StrongKeyDummyValueEntry<K>> {
- StrongKeyDummyValueEntry(K key, int hash, @Nullable StrongKeyDummyValueEntry<K> next) {
- super(key, hash, next);
+
+ private StrongKeyDummyValueEntry(K key, int hash) {
+ super(key, hash);
}
@Override
- public Dummy getValue() {
+ public final Dummy getValue() {
return Dummy.VALUE;
}
- void setValue(Dummy value) {}
+ private static final class LinkedStrongKeyDummyValueEntry<K>
+ extends StrongKeyDummyValueEntry<K> {
+ private final StrongKeyDummyValueEntry<K> next;
- StrongKeyDummyValueEntry<K> copy(StrongKeyDummyValueEntry<K> newNext) {
- return new StrongKeyDummyValueEntry<K>(this.key, this.hash, newNext);
+ LinkedStrongKeyDummyValueEntry(K key, int hash, StrongKeyDummyValueEntry<K> next) {
+ super(key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public StrongKeyDummyValueEntry<K> getNext() {
+ return next;
+ }
}
/**
@@ -617,17 +635,16 @@ class MapMakerInternalMap<
public StrongKeyDummyValueSegment<K> newSegment(
MapMakerInternalMap<K, Dummy, StrongKeyDummyValueEntry<K>, StrongKeyDummyValueSegment<K>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new StrongKeyDummyValueSegment<K>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new StrongKeyDummyValueSegment<K>(map, initialCapacity);
}
@Override
public StrongKeyDummyValueEntry<K> copy(
StrongKeyDummyValueSegment<K> segment,
StrongKeyDummyValueEntry<K> entry,
- @Nullable StrongKeyDummyValueEntry<K> newNext) {
- return entry.copy(newNext);
+ @CheckForNull StrongKeyDummyValueEntry<K> newNext) {
+ return newEntry(segment, entry.key, entry.hash, newNext);
}
@Override
@@ -639,8 +656,10 @@ class MapMakerInternalMap<
StrongKeyDummyValueSegment<K> segment,
K key,
int hash,
- @Nullable StrongKeyDummyValueEntry<K> next) {
- return new StrongKeyDummyValueEntry<K>(key, hash, next);
+ @CheckForNull StrongKeyDummyValueEntry<K> next) {
+ return next == null
+ ? new StrongKeyDummyValueEntry<K>(key, hash)
+ : new LinkedStrongKeyDummyValueEntry<>(key, hash, next);
}
}
}
@@ -649,49 +668,56 @@ class MapMakerInternalMap<
abstract static class AbstractWeakKeyEntry<K, V, E extends InternalEntry<K, V, E>>
extends WeakReference<K> implements InternalEntry<K, V, E> {
final int hash;
- final @Nullable E next;
- AbstractWeakKeyEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable E next) {
+ AbstractWeakKeyEntry(ReferenceQueue<K> queue, K key, int hash) {
super(key, queue);
this.hash = hash;
- this.next = next;
}
@Override
- public K getKey() {
+ public final K getKey() {
return get();
}
@Override
- public int getHash() {
+ public final int getHash() {
return hash;
}
@Override
+ @CheckForNull
public E getNext() {
- return next;
+ return null;
}
}
/** Concrete implementation of {@link InternalEntry} for weak keys and {@link Dummy} values. */
- static final class WeakKeyDummyValueEntry<K>
+ static class WeakKeyDummyValueEntry<K>
extends AbstractWeakKeyEntry<K, Dummy, WeakKeyDummyValueEntry<K>>
implements StrongValueEntry<K, Dummy, WeakKeyDummyValueEntry<K>> {
- WeakKeyDummyValueEntry(
- ReferenceQueue<K> queue, K key, int hash, @Nullable WeakKeyDummyValueEntry<K> next) {
- super(queue, key, hash, next);
+
+ private WeakKeyDummyValueEntry(ReferenceQueue<K> queue, K key, int hash) {
+ super(queue, key, hash);
}
@Override
- public Dummy getValue() {
+ public final Dummy getValue() {
return Dummy.VALUE;
}
- void setValue(Dummy value) {}
+ private static final class LinkedWeakKeyDummyValueEntry<K> extends WeakKeyDummyValueEntry<K> {
+ private final WeakKeyDummyValueEntry<K> next;
- WeakKeyDummyValueEntry<K> copy(
- ReferenceQueue<K> queueForKeys, WeakKeyDummyValueEntry<K> newNext) {
- return new WeakKeyDummyValueEntry<K>(queueForKeys, getKey(), this.hash, newNext);
+ private LinkedWeakKeyDummyValueEntry(
+ ReferenceQueue<K> queue, K key, int hash, WeakKeyDummyValueEntry<K> next) {
+ super(queue, key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public WeakKeyDummyValueEntry<K> getNext() {
+ return next;
+ }
}
/**
@@ -721,21 +747,22 @@ class MapMakerInternalMap<
@Override
public WeakKeyDummyValueSegment<K> newSegment(
MapMakerInternalMap<K, Dummy, WeakKeyDummyValueEntry<K>, WeakKeyDummyValueSegment<K>> map,
- int initialCapacity,
- int maxSegmentSize) {
- return new WeakKeyDummyValueSegment<K>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new WeakKeyDummyValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public WeakKeyDummyValueEntry<K> copy(
WeakKeyDummyValueSegment<K> segment,
WeakKeyDummyValueEntry<K> entry,
- @Nullable WeakKeyDummyValueEntry<K> newNext) {
- if (entry.getKey() == null) {
+ @CheckForNull WeakKeyDummyValueEntry<K> newNext) {
+ K key = entry.getKey();
+ if (key == null) {
// key collected
return null;
}
- return entry.copy(segment.queueForKeys, newNext);
+ return newEntry(segment, key, entry.hash, newNext);
}
@Override
@@ -747,38 +774,44 @@ class MapMakerInternalMap<
WeakKeyDummyValueSegment<K> segment,
K key,
int hash,
- @Nullable WeakKeyDummyValueEntry<K> next) {
- return new WeakKeyDummyValueEntry<K>(segment.queueForKeys, key, hash, next);
+ @CheckForNull WeakKeyDummyValueEntry<K> next) {
+ return next == null
+ ? new WeakKeyDummyValueEntry<>(segment.queueForKeys, key, hash)
+ : new LinkedWeakKeyDummyValueEntry<>(segment.queueForKeys, key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for weak keys and strong values. */
- static final class WeakKeyStrongValueEntry<K, V>
+ static class WeakKeyStrongValueEntry<K, V>
extends AbstractWeakKeyEntry<K, V, WeakKeyStrongValueEntry<K, V>>
implements StrongValueEntry<K, V, WeakKeyStrongValueEntry<K, V>> {
- private volatile @Nullable V value = null;
+ @CheckForNull private volatile V value = null;
- WeakKeyStrongValueEntry(
- ReferenceQueue<K> queue, K key, int hash, @Nullable WeakKeyStrongValueEntry<K, V> next) {
- super(queue, key, hash, next);
+ private WeakKeyStrongValueEntry(ReferenceQueue<K> queue, K key, int hash) {
+ super(queue, key, hash);
}
@Override
- public @Nullable V getValue() {
+ @CheckForNull
+ public final V getValue() {
return value;
}
- void setValue(V value) {
- this.value = value;
- }
+ private static final class LinkedWeakKeyStrongValueEntry<K, V>
+ extends WeakKeyStrongValueEntry<K, V> {
+ private final WeakKeyStrongValueEntry<K, V> next;
- WeakKeyStrongValueEntry<K, V> copy(
- ReferenceQueue<K> queueForKeys, WeakKeyStrongValueEntry<K, V> newNext) {
- WeakKeyStrongValueEntry<K, V> newEntry =
- new WeakKeyStrongValueEntry<>(queueForKeys, getKey(), this.hash, newNext);
- newEntry.setValue(value);
- return newEntry;
+ private LinkedWeakKeyStrongValueEntry(
+ ReferenceQueue<K> queue, K key, int hash, WeakKeyStrongValueEntry<K, V> next) {
+ super(queue, key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public WeakKeyStrongValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for weak keys and strong values. */
@@ -806,27 +839,30 @@ class MapMakerInternalMap<
public WeakKeyStrongValueSegment<K, V> newSegment(
MapMakerInternalMap<K, V, WeakKeyStrongValueEntry<K, V>, WeakKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- return new WeakKeyStrongValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new WeakKeyStrongValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public WeakKeyStrongValueEntry<K, V> copy(
WeakKeyStrongValueSegment<K, V> segment,
WeakKeyStrongValueEntry<K, V> entry,
- @Nullable WeakKeyStrongValueEntry<K, V> newNext) {
- if (entry.getKey() == null) {
+ @CheckForNull WeakKeyStrongValueEntry<K, V> newNext) {
+ K key = entry.getKey();
+ if (key == null) {
// key collected
return null;
}
- return entry.copy(segment.queueForKeys, newNext);
+ WeakKeyStrongValueEntry<K, V> newEntry = newEntry(segment, key, entry.hash, newNext);
+ newEntry.value = entry.value;
+ return newEntry;
}
@Override
public void setValue(
WeakKeyStrongValueSegment<K, V> segment, WeakKeyStrongValueEntry<K, V> entry, V value) {
- entry.setValue(value);
+ entry.value = value;
}
@Override
@@ -834,53 +870,49 @@ class MapMakerInternalMap<
WeakKeyStrongValueSegment<K, V> segment,
K key,
int hash,
- @Nullable WeakKeyStrongValueEntry<K, V> next) {
- return new WeakKeyStrongValueEntry<>(segment.queueForKeys, key, hash, next);
+ @CheckForNull WeakKeyStrongValueEntry<K, V> next) {
+ return next == null
+ ? new WeakKeyStrongValueEntry<>(segment.queueForKeys, key, hash)
+ : new LinkedWeakKeyStrongValueEntry<>(segment.queueForKeys, key, hash, next);
}
}
}
/** Concrete implementation of {@link InternalEntry} for weak keys and weak values. */
- static final class WeakKeyWeakValueEntry<K, V>
+ static class WeakKeyWeakValueEntry<K, V>
extends AbstractWeakKeyEntry<K, V, WeakKeyWeakValueEntry<K, V>>
implements WeakValueEntry<K, V, WeakKeyWeakValueEntry<K, V>> {
private volatile WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> valueReference =
unsetWeakValueReference();
- WeakKeyWeakValueEntry(
- ReferenceQueue<K> queue, K key, int hash, @Nullable WeakKeyWeakValueEntry<K, V> next) {
- super(queue, key, hash, next);
+ WeakKeyWeakValueEntry(ReferenceQueue<K> queue, K key, int hash) {
+ super(queue, key, hash);
}
@Override
- public V getValue() {
+ public final V getValue() {
return valueReference.get();
}
- WeakKeyWeakValueEntry<K, V> copy(
- ReferenceQueue<K> queueForKeys,
- ReferenceQueue<V> queueForValues,
- WeakKeyWeakValueEntry<K, V> newNext) {
- WeakKeyWeakValueEntry<K, V> newEntry =
- new WeakKeyWeakValueEntry<>(queueForKeys, getKey(), this.hash, newNext);
- newEntry.valueReference = valueReference.copyFor(queueForValues, newEntry);
- return newEntry;
- }
-
@Override
- public void clearValue() {
- valueReference.clear();
+ public final WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> getValueReference() {
+ return valueReference;
}
- void setValue(V value, ReferenceQueue<V> queueForValues) {
- WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> previous = this.valueReference;
- this.valueReference = new WeakValueReferenceImpl<>(queueForValues, value, this);
- previous.clear();
- }
+ private static final class LinkedWeakKeyWeakValueEntry<K, V>
+ extends WeakKeyWeakValueEntry<K, V> {
+ private final WeakKeyWeakValueEntry<K, V> next;
- @Override
- public WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> getValueReference() {
- return valueReference;
+ LinkedWeakKeyWeakValueEntry(
+ ReferenceQueue<K> queue, K key, int hash, WeakKeyWeakValueEntry<K, V> next) {
+ super(queue, key, hash);
+ this.next = next;
+ }
+
+ @Override
+ public WeakKeyWeakValueEntry<K, V> getNext() {
+ return next;
+ }
}
/** Concrete implementation of {@link InternalEntryHelper} for weak keys and weak values. */
@@ -907,30 +939,35 @@ class MapMakerInternalMap<
@Override
public WeakKeyWeakValueSegment<K, V> newSegment(
MapMakerInternalMap<K, V, WeakKeyWeakValueEntry<K, V>, WeakKeyWeakValueSegment<K, V>> map,
- int initialCapacity,
- int maxSegmentSize) {
- return new WeakKeyWeakValueSegment<>(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ return new WeakKeyWeakValueSegment<>(map, initialCapacity);
}
@Override
+ @CheckForNull
public WeakKeyWeakValueEntry<K, V> copy(
WeakKeyWeakValueSegment<K, V> segment,
WeakKeyWeakValueEntry<K, V> entry,
- @Nullable WeakKeyWeakValueEntry<K, V> newNext) {
- if (entry.getKey() == null) {
+ @CheckForNull WeakKeyWeakValueEntry<K, V> newNext) {
+ K key = entry.getKey();
+ if (key == null) {
// key collected
return null;
}
if (Segment.isCollected(entry)) {
return null;
}
- return entry.copy(segment.queueForKeys, segment.queueForValues, newNext);
+ WeakKeyWeakValueEntry<K, V> newEntry = newEntry(segment, key, entry.hash, newNext);
+ newEntry.valueReference = entry.valueReference.copyFor(segment.queueForValues, newEntry);
+ return newEntry;
}
@Override
public void setValue(
WeakKeyWeakValueSegment<K, V> segment, WeakKeyWeakValueEntry<K, V> entry, V value) {
- entry.setValue(value, segment.queueForValues);
+ WeakValueReference<K, V, WeakKeyWeakValueEntry<K, V>> previous = entry.valueReference;
+ entry.valueReference = new WeakValueReferenceImpl<>(segment.queueForValues, value, entry);
+ previous.clear();
}
@Override
@@ -938,8 +975,10 @@ class MapMakerInternalMap<
WeakKeyWeakValueSegment<K, V> segment,
K key,
int hash,
- @Nullable WeakKeyWeakValueEntry<K, V> next) {
- return new WeakKeyWeakValueEntry<>(segment.queueForKeys, key, hash, next);
+ @CheckForNull WeakKeyWeakValueEntry<K, V> next) {
+ return next == null
+ ? new WeakKeyWeakValueEntry<>(segment.queueForKeys, key, hash)
+ : new LinkedWeakKeyWeakValueEntry<>(segment.queueForKeys, key, hash, next);
}
}
}
@@ -950,7 +989,7 @@ class MapMakerInternalMap<
* Returns the current value being referenced, or {@code null} if there is none (e.g. because
* either it got collected, or {@link #clear} was called, or it wasn't set in the first place).
*/
- @Nullable
+ @CheckForNull
V get();
/** Returns the entry which contains this {@link WeakValueReference}. */
@@ -961,7 +1000,7 @@ class MapMakerInternalMap<
/**
* Returns a freshly created {@link WeakValueReference} for the given {@code entry} (and on the
- * given {@code queue} with the same value as this {@link WeakValueReference}.
+ * given {@code queue}) with the same value as this {@link WeakValueReference}.
*/
WeakValueReference<K, V, E> copyFor(ReferenceQueue<V> queue, E entry);
}
@@ -998,11 +1037,12 @@ class MapMakerInternalMap<
}
/**
- * A singleton {@link WeakValueReference} used to denote an unset value in a entry with weak
+ * A singleton {@link WeakValueReference} used to denote an unset value in an entry with weak
* values.
*/
static final WeakValueReference<Object, Object, DummyInternalEntry> UNSET_WEAK_VALUE_REFERENCE =
new WeakValueReference<Object, Object, DummyInternalEntry>() {
+ @CheckForNull
@Override
public DummyInternalEntry getEntry() {
return null;
@@ -1011,6 +1051,7 @@ class MapMakerInternalMap<
@Override
public void clear() {}
+ @CheckForNull
@Override
public Object get() {
return null;
@@ -1110,14 +1151,15 @@ class MapMakerInternalMap<
return segments[(hash >>> segmentShift) & segmentMask];
}
- Segment<K, V, E, S> createSegment(int initialCapacity, int maxSegmentSize) {
- return entryHelper.newSegment(this, initialCapacity, maxSegmentSize);
+ Segment<K, V, E, S> createSegment(int initialCapacity) {
+ return entryHelper.newSegment(this, initialCapacity);
}
/**
* Gets the value from an entry. Returns {@code null} if the entry is invalid, partially-collected
* or computing.
*/
+ @CheckForNull
V getLiveValue(E entry) {
if (entry.getKey() == null) {
return null;
@@ -1192,10 +1234,7 @@ class MapMakerInternalMap<
int threshold;
/** The per-segment table. */
- volatile @Nullable AtomicReferenceArray<E> table;
-
- /** The maximum size of this map. MapMaker.UNSET_INT if there is no maximum. */
- final int maxSegmentSize;
+ @CheckForNull volatile AtomicReferenceArray<E> table;
/**
* A counter of the number of reads since the last write, used to drain queues on a small
@@ -1203,9 +1242,8 @@ class MapMakerInternalMap<
*/
final AtomicInteger readCount = new AtomicInteger();
- Segment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity, int maxSegmentSize) {
+ Segment(MapMakerInternalMap<K, V, E, S> map, int initialCapacity) {
this.map = map;
- this.maxSegmentSize = maxSegmentSize;
initTable(newEntryArray(initialCapacity));
}
@@ -1230,6 +1268,7 @@ class MapMakerInternalMap<
}
/** Returns a copy of the given {@code entry}. */
+ @CheckForNull
E copyEntry(E original, E newNext) {
return this.map.entryHelper.copy(self(), original, newNext);
}
@@ -1240,10 +1279,6 @@ class MapMakerInternalMap<
void initTable(AtomicReferenceArray<E> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
- if (this.threshold == maxSegmentSize) {
- // prevent spurious expansion before eviction
- this.threshold++;
- }
this.table = newTable;
}
@@ -1254,7 +1289,7 @@ class MapMakerInternalMap<
* implementation type.
*
* <p>This method is provided as a convenience for tests. Otherwise they'd need to be
- * knowledgable about all the implementation details of our type system trickery.
+ * knowledgeable about all the implementation details of our type system trickery.
*/
abstract E castForTesting(InternalEntry<K, V, ?> entry);
@@ -1300,7 +1335,7 @@ class MapMakerInternalMap<
}
/** Unsafely returns a copy of the given entry. */
- E copyForTesting(InternalEntry<K, V, ?> entry, @Nullable InternalEntry<K, V, ?> newNext) {
+ E copyForTesting(InternalEntry<K, V, ?> entry, @CheckForNull InternalEntry<K, V, ?> newNext) {
return this.map.entryHelper.copy(self(), castForTesting(entry), castForTesting(newNext));
}
@@ -1310,7 +1345,7 @@ class MapMakerInternalMap<
}
/** Unsafely returns a fresh entry. */
- E newEntryForTesting(K key, int hash, @Nullable InternalEntry<K, V, ?> next) {
+ E newEntryForTesting(K key, int hash, @CheckForNull InternalEntry<K, V, ?> next) {
return this.map.entryHelper.newEntry(self(), key, hash, castForTesting(next));
}
@@ -1321,6 +1356,7 @@ class MapMakerInternalMap<
}
/** Unsafely removes the given entry from the given chain in this segment's hash table. */
+ @CheckForNull
E removeFromChainForTesting(InternalEntry<K, V, ?> first, InternalEntry<K, V, ?> entry) {
return removeFromChain(castForTesting(first), castForTesting(entry));
}
@@ -1328,7 +1364,7 @@ class MapMakerInternalMap<
/**
* Unsafely returns the value of the given entry if it's still live, or {@code null} otherwise.
*/
- @Nullable
+ @CheckForNull
V getLiveValueForTesting(InternalEntry<K, V, ?> entry) {
return getLiveValue(castForTesting(entry));
}
@@ -1379,6 +1415,7 @@ class MapMakerInternalMap<
}
/** Returns first entry of bin for given hash. */
+ @CheckForNull
E getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<E> table = this.table;
@@ -1387,6 +1424,7 @@ class MapMakerInternalMap<
// Specialized implementations of map methods
+ @CheckForNull
E getEntry(Object key, int hash) {
if (count != 0) { // read-volatile
for (E e = getFirst(hash); e != null; e = e.getNext()) {
@@ -1409,10 +1447,12 @@ class MapMakerInternalMap<
return null;
}
+ @CheckForNull
E getLiveEntry(Object key, int hash) {
return getEntry(key, hash);
}
+ @CheckForNull
V get(Object key, int hash) {
try {
E e = getLiveEntry(key, hash);
@@ -1472,6 +1512,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
@@ -1645,6 +1686,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
V replace(K key, int hash, V newValue) {
lock();
try {
@@ -1686,6 +1728,7 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
@CanIgnoreReturnValue
V remove(Object key, int hash) {
lock();
@@ -1800,6 +1843,7 @@ class MapMakerInternalMap<
* @return the new first entry for the table
*/
@GuardedBy("this")
+ @CheckForNull
E removeFromChain(E first, E entry) {
int newCount = count;
E newFirst = entry.getNext();
@@ -1943,7 +1987,7 @@ class MapMakerInternalMap<
* Gets the value from an entry. Returns {@code null} if the entry is invalid or
* partially-collected.
*/
- @Nullable
+ @CheckForNull
V getLiveValue(E entry) {
if (entry.getKey() == null) {
tryDrainReferenceQueues();
@@ -2001,9 +2045,8 @@ class MapMakerInternalMap<
MapMakerInternalMap<
K, V, StrongKeyStrongValueEntry<K, V>, StrongKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2013,7 +2056,9 @@ class MapMakerInternalMap<
@SuppressWarnings("unchecked")
@Override
- public StrongKeyStrongValueEntry<K, V> castForTesting(InternalEntry<K, V, ?> entry) {
+ @CheckForNull
+ public StrongKeyStrongValueEntry<K, V> castForTesting(
+ @CheckForNull InternalEntry<K, V, ?> entry) {
return (StrongKeyStrongValueEntry<K, V>) entry;
}
}
@@ -2026,9 +2071,8 @@ class MapMakerInternalMap<
StrongKeyWeakValueSegment(
MapMakerInternalMap<K, V, StrongKeyWeakValueEntry<K, V>, StrongKeyWeakValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2043,7 +2087,9 @@ class MapMakerInternalMap<
@SuppressWarnings("unchecked")
@Override
- public StrongKeyWeakValueEntry<K, V> castForTesting(InternalEntry<K, V, ?> entry) {
+ @CheckForNull
+ public StrongKeyWeakValueEntry<K, V> castForTesting(
+ @CheckForNull InternalEntry<K, V, ?> entry) {
return (StrongKeyWeakValueEntry<K, V>) entry;
}
@@ -2089,9 +2135,8 @@ class MapMakerInternalMap<
StrongKeyDummyValueSegment(
MapMakerInternalMap<K, Dummy, StrongKeyDummyValueEntry<K>, StrongKeyDummyValueSegment<K>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2114,9 +2159,8 @@ class MapMakerInternalMap<
WeakKeyStrongValueSegment(
MapMakerInternalMap<K, V, WeakKeyStrongValueEntry<K, V>, WeakKeyStrongValueSegment<K, V>>
map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2154,9 +2198,8 @@ class MapMakerInternalMap<
WeakKeyWeakValueSegment(
MapMakerInternalMap<K, V, WeakKeyWeakValueEntry<K, V>, WeakKeyWeakValueSegment<K, V>> map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2176,7 +2219,8 @@ class MapMakerInternalMap<
@SuppressWarnings("unchecked")
@Override
- public WeakKeyWeakValueEntry<K, V> castForTesting(InternalEntry<K, V, ?> entry) {
+ @CheckForNull
+ public WeakKeyWeakValueEntry<K, V> castForTesting(@CheckForNull InternalEntry<K, V, ?> entry) {
return (WeakKeyWeakValueEntry<K, V>) entry;
}
@@ -2224,9 +2268,8 @@ class MapMakerInternalMap<
WeakKeyDummyValueSegment(
MapMakerInternalMap<K, Dummy, WeakKeyDummyValueEntry<K>, WeakKeyDummyValueSegment<K>> map,
- int initialCapacity,
- int maxSegmentSize) {
- super(map, initialCapacity, maxSegmentSize);
+ int initialCapacity) {
+ super(map, initialCapacity);
}
@Override
@@ -2333,8 +2376,9 @@ class MapMakerInternalMap<
return Ints.saturatedCast(sum);
}
+ @CheckForNull
@Override
- public V get(@Nullable Object key) {
+ public V get(@CheckForNull Object key) {
if (key == null) {
return null;
}
@@ -2346,7 +2390,8 @@ class MapMakerInternalMap<
* Returns the internal entry for the specified key. The entry may be computing or partially
* collected. Does not impact recency ordering.
*/
- E getEntry(@Nullable Object key) {
+ @CheckForNull
+ E getEntry(@CheckForNull Object key) {
if (key == null) {
return null;
}
@@ -2355,7 +2400,7 @@ class MapMakerInternalMap<
}
@Override
- public boolean containsKey(@Nullable Object key) {
+ public boolean containsKey(@CheckForNull Object key) {
if (key == null) {
return false;
}
@@ -2364,7 +2409,7 @@ class MapMakerInternalMap<
}
@Override
- public boolean containsValue(@Nullable Object value) {
+ public boolean containsValue(@CheckForNull Object value) {
if (value == null) {
return false;
}
@@ -2401,6 +2446,7 @@ class MapMakerInternalMap<
return false;
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V put(K key, V value) {
@@ -2410,6 +2456,7 @@ class MapMakerInternalMap<
return segmentFor(hash).put(key, hash, value, false);
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V putIfAbsent(K key, V value) {
@@ -2426,9 +2473,10 @@ class MapMakerInternalMap<
}
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
- public V remove(@Nullable Object key) {
+ public V remove(@CheckForNull Object key) {
if (key == null) {
return null;
}
@@ -2438,7 +2486,7 @@ class MapMakerInternalMap<
@CanIgnoreReturnValue
@Override
- public boolean remove(@Nullable Object key, @Nullable Object value) {
+ public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
if (key == null || value == null) {
return false;
}
@@ -2448,7 +2496,7 @@ class MapMakerInternalMap<
@CanIgnoreReturnValue
@Override
- public boolean replace(K key, @Nullable V oldValue, V newValue) {
+ public boolean replace(K key, @CheckForNull V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
@@ -2458,6 +2506,7 @@ class MapMakerInternalMap<
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
+ @CheckForNull
@CanIgnoreReturnValue
@Override
public V replace(K key, V value) {
@@ -2474,7 +2523,7 @@ class MapMakerInternalMap<
}
}
- transient @Nullable Set<K> keySet;
+ @LazyInit @CheckForNull transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -2482,7 +2531,7 @@ class MapMakerInternalMap<
return (ks != null) ? ks : (keySet = new KeySet());
}
- transient @Nullable Collection<V> values;
+ @LazyInit @CheckForNull transient Collection<V> values;
@Override
public Collection<V> values() {
@@ -2490,7 +2539,7 @@ class MapMakerInternalMap<
return (vs != null) ? vs : (values = new Values());
}
- transient @Nullable Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -2504,11 +2553,11 @@ class MapMakerInternalMap<
int nextSegmentIndex;
int nextTableIndex;
- @Nullable Segment<K, V, E, S> currentSegment;
- @Nullable AtomicReferenceArray<E> currentTable;
- @Nullable E nextEntry;
- @Nullable WriteThroughEntry nextExternal;
- @Nullable WriteThroughEntry lastReturned;
+ @CheckForNull Segment<K, V, E, S> currentSegment;
+ @CheckForNull AtomicReferenceArray<E> currentTable;
+ @CheckForNull E nextEntry;
+ @CheckForNull WriteThroughEntry nextExternal;
+ @CheckForNull WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
@@ -2648,7 +2697,7 @@ class MapMakerInternalMap<
}
@Override
- public boolean equals(@Nullable Object object) {
+ public boolean equals(@CheckForNull Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
@@ -2840,6 +2889,11 @@ class MapMakerInternalMap<
this);
}
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream in) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializationProxy");
+ }
+
/**
* The actual object that gets serialized. Unfortunately, readResolve() doesn't get called when a
* circular dependency is present, so the proxy must be able to behave as the map itself.
@@ -2886,6 +2940,7 @@ class MapMakerInternalMap<
}
@SuppressWarnings("deprecation") // serialization of deprecated feature
+ @J2ktIncompatible // java.io.ObjectInputStream
MapMaker readMapMaker(ObjectInputStream in) throws IOException {
int size = in.readInt();
return new MapMaker()
@@ -2897,6 +2952,7 @@ class MapMakerInternalMap<
}
@SuppressWarnings("unchecked")
+ @J2ktIncompatible // java.io.ObjectInputStream
void readEntries(ObjectInputStream in) throws IOException, ClassNotFoundException {
while (true) {
K key = (K) in.readObject();
@@ -2932,6 +2988,7 @@ class MapMakerInternalMap<
writeMapTo(out);
}
+ @J2ktIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MapMaker mapMaker = readMapMaker(in);
diff --git a/guava/src/com/google/common/collect/Maps.java b/guava/src/com/google/common/collect/Maps.java
index 6265f5dce..173447caf 100644
--- a/guava/src/com/google/common/collect/Maps.java
+++ b/guava/src/com/google/common/collect/Maps.java
@@ -22,11 +22,12 @@ import static com.google.common.base.Predicates.compose;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
+import static java.util.Collections.singletonMap;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
@@ -37,6 +38,7 @@ import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
@@ -71,6 +73,7 @@ import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -153,6 +156,7 @@ public final class Maps {
* @since 14.0
*/
@GwtCompatible(serializable = true)
+ @J2ktIncompatible
public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
Map<K, ? extends V> map) {
if (map instanceof ImmutableEnumMap) {
@@ -168,9 +172,8 @@ public final class Maps {
K key1 = entry1.getKey();
V value1 = entry1.getValue();
checkEntryNotNull(key1, value1);
- Class<K> clazz = key1.getDeclaringClass();
- EnumMap<K, V> enumMap = new EnumMap<>(clazz);
- enumMap.put(key1, value1);
+ // Do something that works for j2cl, where we can't call getDeclaredClass():
+ EnumMap<K, V> enumMap = new EnumMap<>(singletonMap(key1, value1));
while (entryItr.hasNext()) {
Entry<K, ? extends V> entry = entryItr.next();
K key = entry.getKey();
@@ -195,6 +198,7 @@ public final class Maps {
*
* @since 21.0
*/
+ @J2ktIncompatible
public static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
java.util.function.Function<? super T, ? extends K> keyFunction,
@@ -213,6 +217,7 @@ public final class Maps {
*
* @since 21.0
*/
+ @J2ktIncompatible
public static <T extends @Nullable Object, K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
java.util.function.Function<? super T, ? extends K> keyFunction,
@@ -284,10 +289,19 @@ public final class Maps {
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
- // This is the calculation used in JDK8 to resize when a putAll
- // happens; it seems to be the most conservative calculation we
- // can make. 0.75 is the default load factor.
- return (int) ((float) expectedSize / 0.75F + 1.0F);
+ // This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap
+ // ends up being used to compute a "threshold" size, beyond which the internal table
+ // will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where
+ // loadFactor is 0.75 by default. So with the calculation here we ensure that the
+ // threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code
+ // path when the first operation on the new map is putAll(otherMap). There, prior to
+ // https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug
+ // meant that sometimes a too-large threshold is calculated. However, this new threshold is
+ // independent of the initial capacity, except that it won't be lower than the threshold
+ // computed from that capacity. Because the internal table is only allocated on the first
+ // write, we won't see copying because of the new threshold. So it is always OK to use the
+ // calculation here.
+ return (int) Math.ceil(expectedSize / 0.75);
}
return Integer.MAX_VALUE; // any large value
}
@@ -469,28 +483,15 @@ public final class Maps {
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
- @SuppressWarnings("unchecked")
public static <K extends @Nullable Object, V extends @Nullable Object>
MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
+ @SuppressWarnings("unchecked")
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
return difference(sortedLeft, right);
}
- /*
- * This cast is safe: The Equivalence-accepting overload of difference() (which we call below)
- * has a weird signature because Equivalence is itself a little weird. Still, we know that
- * Equivalence.equals() can handle all inputs, and we know that the resulting MapDifference will
- * contain only Ks and Vs (as opposed to possibly containing @Nullable objects even when K and V
- * are *not* @Nullable).
- *
- * An alternative to suppressing the warning would be to inline the body of the other
- * difference() method into this one.
- */
- @SuppressWarnings("nullness")
- MapDifference<K, V> result =
- (MapDifference<K, V>) difference(left, right, Equivalence.equals());
- return result;
+ return difference(left, right, Equivalence.equals());
}
/**
@@ -507,36 +508,11 @@ public final class Maps {
* @return the difference between the two maps
* @since 10.0
*/
- /*
- * This method should really be annotated to accept maps with @Nullable value types. Fortunately,
- * no existing Google callers appear to pass null values (much less pass null values *and* run a
- * nullness checker).
- *
- * Still, if we decide that we want to make that work, we'd need to introduce a new type parameter
- * for the Equivalence input type:
- *
- * <E, K extends @Nullable Object, V extends @Nullable E> ... difference(..., Equivalence<E> ...)
- *
- * Maybe we should, even though it will break source compatibility.
- *
- * Alternatively, this is a case in which it would be useful to be able to express Equivalence<?
- * super @Nonnull T>).
- *
- * As things stand now, though, we have to either:
- *
- * - require non-null inputs so that we can guarantee non-null outputs
- *
- * - accept nullable inputs but force users to cope with nullable outputs
- *
- * And the non-null option is far more useful to existing users.
- *
- * (Vaguely related: Another thing we could consider is an overload that accepts a BiPredicate:
- * https://github.com/google/guava/issues/3913)
- */
- public static <K extends @Nullable Object, V> MapDifference<K, V> difference(
- Map<? extends K, ? extends V> left,
- Map<? extends K, ? extends V> right,
- Equivalence<? super V> valueEquivalence) {
+ public static <K extends @Nullable Object, V extends @Nullable Object>
+ MapDifference<K, V> difference(
+ Map<? extends K, ? extends V> left,
+ Map<? extends K, ? extends V> right,
+ Equivalence<? super @NonNull V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newLinkedHashMap();
@@ -576,26 +552,14 @@ public final class Maps {
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator);
- /*
- * V is a possibly nullable type, but we decided to declare Equivalence with a type parameter
- * that is restricted to non-nullable types. Still, this code is safe: We made that decision
- * about Equivalence not because Equivalence is null-hostile but because *every* Equivalence can
- * handle null inputs -- and thus it would be meaningless for the type system to distinguish
- * between "an Equivalence for nullable Foo" and "an Equivalence for non-nullable Foo."
- *
- * (And the unchecked cast is safe because Equivalence is contravariant.)
- */
- @SuppressWarnings({"nullness", "unchecked"})
- Equivalence<V> equalsEquivalence = (Equivalence<V>) Equivalence.equals();
-
- doDifference(left, right, equalsEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
+ doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K extends @Nullable Object, V extends @Nullable Object> void doDifference(
Map<? extends K, ? extends V> left,
Map<? extends K, ? extends V> right,
- Equivalence<? super V> valueEquivalence,
+ Equivalence<? super @NonNull V> valueEquivalence,
Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight,
Map<K, V> onBoth,
@@ -1329,14 +1293,26 @@ public final class Maps {
* ...
* ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue);
*
- * Map<String, Color> colorForName =
- * uniqueIndex(allColors, toStringFunction());
+ * ImmutableMap<String, Color> colorForName =
+ * uniqueIndex(allColors, c -> c.toString());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterable, Function) Multimaps.index}.
*
+ * <p><b>Note:</b> on Java 8 and later, it is usually better to use streams. For example:
+ *
+ * <pre>{@code
+ * import static com.google.common.collect.ImmutableMap.toImmutableMap;
+ * ...
+ * ImmutableMap<String, Color> colorForName =
+ * allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c));
+ * }</pre>
+ *
+ * <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys
+ * and values in the map are.
+ *
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
@@ -1349,7 +1325,12 @@ public final class Maps {
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
- // TODO(lowasser): consider presizing the builder if values is a Collection
+ if (values instanceof Collection) {
+ return uniqueIndex(
+ values.iterator(),
+ keyFunction,
+ ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size()));
+ }
return uniqueIndex(values.iterator(), keyFunction);
}
@@ -1385,8 +1366,12 @@ public final class Maps {
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
+ return uniqueIndex(values, keyFunction, ImmutableMap.builder());
+ }
+
+ private static <K, V> ImmutableMap<K, V> uniqueIndex(
+ Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) {
checkNotNull(keyFunction);
- ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
@@ -1410,6 +1395,7 @@ public final class Maps {
* @throws ClassCastException if any key in {@code properties} is not a {@code String}
* @throws NullPointerException if any key or value in {@code properties} is null
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.Properties
public static ImmutableMap<String, String> fromProperties(Properties properties) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
@@ -1481,7 +1467,7 @@ public final class Maps {
/**
* Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation
- * throws an {@link UnsupportedOperationException}. This also has the side-effect of redefining
+ * throws an {@link UnsupportedOperationException}. This also has the side effect of redefining
* {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation
* of equals.
*
@@ -1522,7 +1508,7 @@ public final class Maps {
};
}
- /** @see Multimaps#unmodifiableEntries */
+ /** The implementation of {@link Multimaps#unmodifiableEntries}. */
static class UnmodifiableEntries<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
@@ -1544,15 +1530,14 @@ public final class Maps {
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override
- public Object[] toArray() {
+ public @Nullable Object[] toArray() {
/*
- * standardToArray returns `@Nullable Object[]` rather than `Object[]` but only because it can
+ * standardToArray returns `@Nullable Object[]` rather than `Object[]` but because it can
* be used with collections that may contain null. This collection never contains nulls, so we
- * can treat it as a plain `Object[]`.
+ * could return `Object[]`. But this class is private and J2KT cannot change return types in
+ * overrides, so we declare `@Nullable Object[]` as the return type.
*/
- @SuppressWarnings("nullness")
- Object[] result = standardToArray();
- return result;
+ return standardToArray();
}
@Override
@@ -1562,7 +1547,7 @@ public final class Maps {
}
}
- /** @see Maps#unmodifiableEntrySet(Set) */
+ /** The implementation of {@link Maps#unmodifiableEntrySet(Set)}. */
static class UnmodifiableEntrySet<K extends @Nullable Object, V extends @Nullable Object>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
@@ -1692,13 +1677,15 @@ public final class Maps {
return new UnmodifiableBiMap<>(bimap, null);
}
- /** @see Maps#unmodifiableBiMap(BiMap) */
+ /**
+ * @see Maps#unmodifiableBiMap(BiMap)
+ */
private static class UnmodifiableBiMap<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
- @RetainedWith @CheckForNull BiMap<V, K> inverse;
- @CheckForNull transient Set<V> values;
+ @LazyInit @RetainedWith @CheckForNull BiMap<V, K> inverse;
+ @LazyInit @CheckForNull transient Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @CheckForNull BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
@@ -1763,8 +1750,9 @@ public final class Maps {
}
@Override
+ @CheckForNull
public V merge(
- K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+ K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
throw new UnsupportedOperationException();
}
@@ -2103,6 +2091,7 @@ public final class Maps {
* @throws NullPointerException if the key or value is null and this transformer does not accept
* null arguments
*/
+ @ParametricNullness
V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value);
}
@@ -3668,12 +3657,13 @@ public final class Maps {
}
@Override
+ @CheckForNull
public V merge(
- K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+ K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
throw new UnsupportedOperationException();
}
- @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
+ @LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
@Override
public NavigableMap<K, V> descendingMap() {
@@ -3803,7 +3793,7 @@ public final class Maps {
*/
abstract Set<Entry<K, V>> createEntrySet();
- @CheckForNull private transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -3811,7 +3801,7 @@ public final class Maps {
return (result == null) ? entrySet = createEntrySet() : result;
}
- @CheckForNull private transient Set<K> keySet;
+ @LazyInit @CheckForNull private transient Set<K> keySet;
@Override
public Set<K> keySet() {
@@ -3823,7 +3813,7 @@ public final class Maps {
return new KeySet<>(this);
}
- @CheckForNull private transient Collection<V> values;
+ @LazyInit @CheckForNull private transient Collection<V> values;
@Override
public Collection<V> values() {
@@ -4385,7 +4375,7 @@ public final class Maps {
return forward();
}
- @CheckForNull private transient Comparator<? super K> comparator;
+ @LazyInit @CheckForNull private transient Comparator<? super K> comparator;
@SuppressWarnings("unchecked")
@Override
@@ -4495,7 +4485,7 @@ public final class Maps {
return forward();
}
- @CheckForNull private transient Set<Entry<K, V>> entrySet;
+ @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
@Override
public Set<Entry<K, V>> entrySet() {
@@ -4526,7 +4516,7 @@ public final class Maps {
return navigableKeySet();
}
- @CheckForNull private transient NavigableSet<K> navigableKeySet;
+ @LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet;
@Override
public NavigableSet<K> navigableKeySet() {
@@ -4610,7 +4600,6 @@ public final class Maps {
*
* @since 20.0
*/
- @Beta
@GwtIncompatible // NavigableMap
public static <K extends Comparable<? super K>, V extends @Nullable Object>
NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) {
diff --git a/guava/src/com/google/common/collect/MinMaxPriorityQueue.java b/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
index 181b3fbb5..877d6bc0b 100644
--- a/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
+++ b/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
@@ -23,8 +23,8 @@ import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -98,7 +98,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Torbjorn Gannholm
* @since 8.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
@@ -108,7 +107,7 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
* initial contents, and an initial expected size of 11.
*/
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() {
- return new Builder<Comparable>(Ordering.natural()).create();
+ return new Builder<Comparable<E>>(Ordering.natural()).create();
}
/**
@@ -162,7 +161,6 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
* Queue<Integer>} but not a {@code Queue<Object>}).
* @since 8.0
*/
- @Beta
public static final class Builder<B> {
/*
* TODO(kevinb): when the dust settles, see if we still need this or can
@@ -518,14 +516,17 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
}
/**
- * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap: a min-heap and a
+ * Each instance of MinMaxPriorityQueue encapsulates two instances of Heap: a min-heap and a
* max-heap. Conceptually, these might each have their own array for storage, but for efficiency's
* sake they are stored interleaved on alternate heap levels in the same array (MMPQ.queue).
*/
@WeakOuter
private class Heap {
final Ordering<E> ordering;
- @Weak Heap otherHeap; // always initialized immediately after construction
+
+ @SuppressWarnings("nullness:initialization.field.uninitialized")
+ @Weak
+ Heap otherHeap; // always initialized immediately after construction
Heap(Ordering<E> ordering) {
this.ordering = ordering;
@@ -644,17 +645,18 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
int parentIndex = getParentIndex(index);
E parentElement = elementData(parentIndex);
if (parentIndex != 0) {
- // This is a guard for the case of the childless uncle.
- // Since the end of the array is actually the middle of the heap,
- // a smaller childless uncle can become a child of x when we
- // bubble up alternate levels, violating the invariant.
+ /*
+ * This is a guard for the case of the childless aunt node. Since the end of the array is
+ * actually the middle of the heap, a smaller childless aunt node can become a child of x
+ * when we bubble up alternate levels, violating the invariant.
+ */
int grandparentIndex = getParentIndex(parentIndex);
- int uncleIndex = getRightChildIndex(grandparentIndex);
- if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
- E uncleElement = elementData(uncleIndex);
- if (ordering.compare(uncleElement, parentElement) < 0) {
- parentIndex = uncleIndex;
- parentElement = uncleElement;
+ int auntIndex = getRightChildIndex(grandparentIndex);
+ if (auntIndex != parentIndex && getLeftChildIndex(auntIndex) >= size) {
+ E auntElement = elementData(auntIndex);
+ if (ordering.compare(auntElement, parentElement) < 0) {
+ parentIndex = auntIndex;
+ parentElement = auntElement;
}
}
}
@@ -667,26 +669,30 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
return index;
}
+ // About the term "aunt node": it's better to leave gender out of it, but for this the English
+ // language has nothing for us. Except for the whimsical neologism "pibling" (!) which we
+ // obviously could not expect to increase anyone's understanding of the code.
+
/**
* Swap {@code actualLastElement} with the conceptually correct last element of the heap.
* Returns the index that {@code actualLastElement} now resides in.
*
* <p>Since the last element of the array is actually in the middle of the sorted structure, a
- * childless uncle node could be smaller, which would corrupt the invariant if this element
- * becomes the new parent of the uncle. In that case, we first switch the last element with its
- * uncle, before returning.
+ * childless aunt node could be smaller, which would corrupt the invariant if this element
+ * becomes the new parent of the aunt node. In that case, we first switch the last element with
+ * its aunt node, before returning.
*/
int swapWithConceptuallyLastElement(E actualLastElement) {
int parentIndex = getParentIndex(size);
if (parentIndex != 0) {
int grandparentIndex = getParentIndex(parentIndex);
- int uncleIndex = getRightChildIndex(grandparentIndex);
- if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
- E uncleElement = elementData(uncleIndex);
- if (ordering.compare(uncleElement, actualLastElement) < 0) {
- queue[uncleIndex] = actualLastElement;
- queue[size] = uncleElement;
- return uncleIndex;
+ int auntIndex = getRightChildIndex(grandparentIndex);
+ if (auntIndex != parentIndex && getLeftChildIndex(auntIndex) >= size) {
+ E auntElement = elementData(auntIndex);
+ if (ordering.compare(auntElement, actualLastElement) < 0) {
+ queue[auntIndex] = actualLastElement;
+ queue[size] = auntElement;
+ return auntIndex;
}
}
}
@@ -911,6 +917,7 @@ public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {
}
@Override
+ @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation
public Object[] toArray() {
Object[] copyTo = new Object[size];
System.arraycopy(queue, 0, copyTo, 0, size);
diff --git a/guava/src/com/google/common/collect/MoreCollectors.java b/guava/src/com/google/common/collect/MoreCollectors.java
index 5a84a4628..3c57ea0a9 100644
--- a/guava/src/com/google/common/collect/MoreCollectors.java
+++ b/guava/src/com/google/common/collect/MoreCollectors.java
@@ -25,6 +25,7 @@ import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collector;
+import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -93,7 +94,7 @@ public final class MoreCollectors {
private static final class ToOptionalState {
static final int MAX_EXTRAS = 4;
- @Nullable Object element;
+ @CheckForNull Object element;
List<Object> extras;
ToOptionalState() {
diff --git a/guava/src/com/google/common/collect/Multimap.java b/guava/src/com/google/common/collect/Multimap.java
index 0f8385191..45b15db51 100644
--- a/guava/src/com/google/common/collect/Multimap.java
+++ b/guava/src/com/google/common/collect/Multimap.java
@@ -135,13 +135,16 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* <h3>Implementations</h3>
*
- * <p>As always, prefer the immutable implementations, {@link ImmutableListMultimap} and {@link
- * ImmutableSetMultimap}. General-purpose mutable implementations are listed above under "All Known
- * Implementing Classes". You can also create a <i>custom</i> multimap, backed by any {@code Map}
- * and {@link Collection} types, using the {@link Multimaps#newMultimap Multimaps.newMultimap}
- * family of methods. Finally, another popular way to obtain a multimap is using {@link
- * Multimaps#index Multimaps.index}. See the {@link Multimaps} class for these and other static
- * utilities related to multimaps.
+ * <ul>
+ * <li>{@link ImmutableListMultimap}
+ * <li>{@link ImmutableSetMultimap}
+ * <li>Configure your own mutable multimap with {@link MultimapBuilder}
+ * <li>{@link LinkedListMultimap} (for one unusual kind of mutable {@code Multimap})
+ * </ul>
+ *
+ * Guava contains a number of other multimap implementations, such as {@link ArrayListMultimap}. In
+ * new code, we recommend using {@link MultimapBuilder} instead: It provides better control of how
+ * keys and values are stored.
*
* <h3>Other Notes</h3>
*
diff --git a/guava/src/com/google/common/collect/MultimapBuilder.java b/guava/src/com/google/common/collect/MultimapBuilder.java
index 3d6278aae..8218da6b4 100644
--- a/guava/src/com/google/common/collect/MultimapBuilder.java
+++ b/guava/src/com/google/common/collect/MultimapBuilder.java
@@ -37,17 +37,14 @@ import java.util.TreeSet;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
- * A builder for a multimap implementation that allows customization of the backing map and value
- * collection implementations used in a particular multimap.
- *
- * <p>This can be used to easily configure multimap data structure implementations not provided
- * explicitly in {@code com.google.common.collect}, for example:
+ * An immutable builder for {@link Multimap} instances, letting you independently select the desired
+ * behaviors (for example, ordering) of the backing map and value-collections. Example:
*
* <pre>{@code
- * ListMultimap<String, Integer> treeListMultimap =
- * MultimapBuilder.treeKeys().arrayListValues().build();
- * SetMultimap<Integer, MyEnum> hashEnumMultimap =
- * MultimapBuilder.hashKeys().enumSetValues(MyEnum.class).build();
+ * ListMultimap<UserId, ErrorResponse> errorsByUser =
+ * MultimapBuilder.linkedHashKeys().arrayListValues().build();
+ * SortedSetMultimap<String, Method> methodsForName =
+ * MultimapBuilder.treeKeys().treeSetValues(this::compareMethods).build();
* }</pre>
*
* <p>{@code MultimapBuilder} instances are immutable. Invoking a configuration method has no effect
diff --git a/guava/src/com/google/common/collect/Multimaps.java b/guava/src/com/google/common/collect/Multimaps.java
index 22e457ca4..c614764c5 100644
--- a/guava/src/com/google/common/collect/Multimaps.java
+++ b/guava/src/com/google/common/collect/Multimaps.java
@@ -22,9 +22,9 @@ import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
@@ -158,7 +158,6 @@ public final class Multimaps {
*
* @since 21.0
*/
- @Beta
public static <
T extends @Nullable Object,
K extends @Nullable Object,
@@ -270,8 +269,11 @@ public final class Multimaps {
// can't use Serialization writeMultimap and populateMultimap methods since
// there's no way to generate the empty backing map.
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -279,6 +281,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -288,6 +291,7 @@ public final class Multimaps {
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -351,8 +355,11 @@ public final class Multimaps {
return factory.get();
}
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -360,6 +367,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -369,6 +377,7 @@ public final class Multimaps {
}
@GwtIncompatible // java serialization not supported
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -454,8 +463,11 @@ public final class Multimaps {
}
}
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -463,6 +475,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -472,6 +485,7 @@ public final class Multimaps {
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -543,8 +557,11 @@ public final class Multimaps {
return valueComparator;
}
- /** @serialData the factory and the backing map */
+ /**
+ * @serialData the factory and the backing map
+ */
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(factory);
@@ -552,6 +569,7 @@ public final class Multimaps {
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -562,6 +580,7 @@ public final class Multimaps {
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -684,13 +703,7 @@ public final class Multimaps {
map =
Collections.unmodifiableMap(
Maps.transformValues(
- delegate.asMap(),
- new Function<Collection<V>, Collection<V>>() {
- @Override
- public Collection<V> apply(Collection<V> collection) {
- return unmodifiableValueCollection(collection);
- }
- }));
+ delegate.asMap(), collection -> unmodifiableValueCollection(collection)));
}
return result;
}
@@ -1046,7 +1059,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
@SuppressWarnings("unchecked")
// safe by specification of ListMultimap.asMap()
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, List<V>> asMap(
@@ -1060,7 +1072,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
@SuppressWarnings("unchecked")
// safe by specification of SetMultimap.asMap()
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, Set<V>> asMap(
@@ -1074,7 +1085,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
@SuppressWarnings("unchecked")
// safe by specification of SortedSetMultimap.asMap()
public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, SortedSet<V>> asMap(
@@ -1088,7 +1098,6 @@ public final class Multimaps {
*
* @since 15.0
*/
- @Beta
public static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, Collection<V>> asMap(Multimap<K, V> multimap) {
return multimap.asMap();
@@ -1505,14 +1514,7 @@ public final class Multimaps {
@Override
Map<K, Collection<V2>> createAsMap() {
- return Maps.transformEntries(
- fromMultimap.asMap(),
- new EntryTransformer<K, Collection<V1>, Collection<V2>>() {
- @Override
- public Collection<V2> transformEntry(@ParametricNullness K key, Collection<V1> value) {
- return transform(key, value);
- }
- });
+ return Maps.transformEntries(fromMultimap.asMap(), (key, value) -> transform(key, value));
}
@Override
@@ -1894,14 +1896,7 @@ public final class Multimaps {
@Override
public Iterator<Entry<K, Collection<V>>> iterator() {
- return Maps.asMapEntryIterator(
- multimap.keySet(),
- new Function<K, Collection<V>>() {
- @Override
- public Collection<V> apply(@ParametricNullness K key) {
- return multimap.get(key);
- }
- });
+ return Maps.asMapEntryIterator(multimap.keySet(), key -> multimap.get(key));
}
@Override
diff --git a/guava/src/com/google/common/collect/Multiset.java b/guava/src/com/google/common/collect/Multiset.java
index ca56a7453..997c467ff 100644
--- a/guava/src/com/google/common/collect/Multiset.java
+++ b/guava/src/com/google/common/collect/Multiset.java
@@ -18,7 +18,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CompatibleWith;
@@ -72,8 +71,17 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* element (in a way that affects its {@link Object#equals} behavior) while it is contained in a
* multiset. Undefined behavior and bugs will result.
*
- * <p>Common implementations include {@link ImmutableMultiset}, {@link HashMultiset}, and {@link
- * ConcurrentHashMultiset}.
+ * <h3>Implementations</h3>
+ *
+ * <ul>
+ * <li>{@link ImmutableMultiset}
+ * <li>{@link ImmutableSortedMultiset}
+ * <li>{@link HashMultiset}
+ * <li>{@link LinkedHashMultiset}
+ * <li>{@link TreeMultiset}
+ * <li>{@link EnumMultiset}
+ * <li>{@link ConcurrentHashMultiset}
+ * </ul>
*
* <p>If your values may be zero, negative, or outside the range of an int, you may wish to use
* {@link com.google.common.util.concurrent.AtomicLongMap} instead. Note, however, that unlike
@@ -339,7 +347,6 @@ public interface Multiset<E extends @Nullable Object> extends Collection<E> {
*
* @since 21.0
*/
- @Beta
default void forEachEntry(ObjIntConsumer<? super E> action) {
checkNotNull(action);
entrySet().forEach(entry -> action.accept(entry.getElement(), entry.getCount()));
diff --git a/guava/src/com/google/common/collect/Multisets.java b/guava/src/com/google/common/collect/Multisets.java
index 71fe61434..fcc674472 100644
--- a/guava/src/com/google/common/collect/Multisets.java
+++ b/guava/src/com/google/common/collect/Multisets.java
@@ -22,7 +22,6 @@ import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
@@ -31,6 +30,7 @@ import com.google.common.collect.Multiset.Entry;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@@ -135,7 +135,7 @@ public final class Multisets {
return (Multiset<E>) delegate;
}
- @CheckForNull transient Set<E> elementSet;
+ @LazyInit @CheckForNull transient Set<E> elementSet;
Set<E> createElementSet() {
return Collections.<E>unmodifiableSet(delegate.elementSet());
@@ -147,7 +147,7 @@ public final class Multisets {
return (es == null) ? elementSet = createElementSet() : es;
}
- @CheckForNull transient Set<Multiset.Entry<E>> entrySet;
+ @LazyInit @CheckForNull transient Set<Multiset.Entry<E>> entrySet;
@SuppressWarnings("unchecked")
@Override
@@ -229,7 +229,6 @@ public final class Multisets {
* @return an unmodifiable view of the multiset
* @since 11.0
*/
- @Beta
public static <E extends @Nullable Object> SortedMultiset<E> unmodifiableSortedMultiset(
SortedMultiset<E> sortedMultiset) {
// it's in its own file so it can be emulated for GWT
@@ -304,7 +303,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> filter(
Multiset<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredMultiset) {
@@ -411,7 +409,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> union(
final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
checkNotNull(multiset1);
@@ -541,7 +538,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> sum(
final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) {
checkNotNull(multiset1);
@@ -619,7 +615,6 @@ public final class Multisets {
*
* @since 14.0
*/
- @Beta
public static <E extends @Nullable Object> Multiset<E> difference(
final Multiset<E> multiset1, final Multiset<?> multiset2) {
checkNotNull(multiset1);
@@ -1159,12 +1154,11 @@ public final class Multisets {
}
/**
- * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is
- * highest count first, with ties broken by the iteration order of the original multiset.
+ * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts
+ * the highest count first, with ties broken by the iteration order of the original multiset.
*
* @since 11.0
*/
- @Beta
public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) {
Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray(new Entry[0]);
Arrays.sort(entries, DecreasingCount.INSTANCE);
diff --git a/guava/src/com/google/common/collect/MutableClassToInstanceMap.java b/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
index 83fbe9447..98b402614 100644
--- a/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
+++ b/guava/src/com/google/common/collect/MutableClassToInstanceMap.java
@@ -19,8 +19,11 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
@@ -29,6 +32,7 @@ import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -39,24 +43,23 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#classtoinstancemap">{@code
* ClassToInstanceMap}</a>.
*
- * <p>This implementation <i>does</i> support null values, despite how it is annotated; see
- * discussion at {@link ClassToInstanceMap}.
- *
* @author Kevin Bourrillion
* @since 2.0
*/
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings("serial") // using writeReplace instead of standard serialization
@ElementTypesAreNonnullByDefault
-public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B>
+public final class MutableClassToInstanceMap<B extends @Nullable Object>
+ extends ForwardingMap<Class<? extends @NonNull B>, B>
implements ClassToInstanceMap<B>, Serializable {
/**
* Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link HashMap} using the
* default initial capacity and load factor.
*/
- public static <B> MutableClassToInstanceMap<B> create() {
- return new MutableClassToInstanceMap<B>(new HashMap<Class<? extends B>, B>());
+ public static <B extends @Nullable Object> MutableClassToInstanceMap<B> create() {
+ return new MutableClassToInstanceMap<B>(new HashMap<Class<? extends @NonNull B>, B>());
}
/**
@@ -64,60 +67,65 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
* backingMap}. The caller surrenders control of the backing map, and thus should not allow any
* direct references to it to remain accessible.
*/
- public static <B> MutableClassToInstanceMap<B> create(Map<Class<? extends B>, B> backingMap) {
+ public static <B extends @Nullable Object> MutableClassToInstanceMap<B> create(
+ Map<Class<? extends @NonNull B>, B> backingMap) {
return new MutableClassToInstanceMap<B>(backingMap);
}
- private final Map<Class<? extends B>, B> delegate;
+ private final Map<Class<? extends @NonNull B>, B> delegate;
- private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) {
+ private MutableClassToInstanceMap(Map<Class<? extends @NonNull B>, B> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
- protected Map<Class<? extends B>, B> delegate() {
+ protected Map<Class<? extends @NonNull B>, B> delegate() {
return delegate;
}
/**
* Wraps the {@code setValue} implementation of an {@code Entry} to enforce the class constraint.
*/
- private static <B> Entry<Class<? extends B>, B> checkedEntry(
- final Entry<Class<? extends B>, B> entry) {
- return new ForwardingMapEntry<Class<? extends B>, B>() {
+ private static <B extends @Nullable Object> Entry<Class<? extends @NonNull B>, B> checkedEntry(
+ final Entry<Class<? extends @NonNull B>, B> entry) {
+ return new ForwardingMapEntry<Class<? extends @NonNull B>, B>() {
@Override
- protected Entry<Class<? extends B>, B> delegate() {
+ protected Entry<Class<? extends @NonNull B>, B> delegate() {
return entry;
}
@Override
- public B setValue(B value) {
- return super.setValue(cast(getKey(), value));
+ @ParametricNullness
+ public B setValue(@ParametricNullness B value) {
+ cast(getKey(), value);
+ return super.setValue(value);
}
};
}
@Override
- public Set<Entry<Class<? extends B>, B>> entrySet() {
- return new ForwardingSet<Entry<Class<? extends B>, B>>() {
+ public Set<Entry<Class<? extends @NonNull B>, B>> entrySet() {
+ return new ForwardingSet<Entry<Class<? extends @NonNull B>, B>>() {
@Override
- protected Set<Entry<Class<? extends B>, B>> delegate() {
+ protected Set<Entry<Class<? extends @NonNull B>, B>> delegate() {
return MutableClassToInstanceMap.this.delegate().entrySet();
}
@Override
- public Spliterator<Entry<Class<? extends B>, B>> spliterator() {
+ public Spliterator<Entry<Class<? extends @NonNull B>, B>> spliterator() {
return CollectSpliterators.map(
delegate().spliterator(), MutableClassToInstanceMap::checkedEntry);
}
@Override
- public Iterator<Entry<Class<? extends B>, B>> iterator() {
- return new TransformedIterator<Entry<Class<? extends B>, B>, Entry<Class<? extends B>, B>>(
+ public Iterator<Entry<Class<? extends @NonNull B>, B>> iterator() {
+ return new TransformedIterator<
+ Entry<Class<? extends @NonNull B>, B>, Entry<Class<? extends @NonNull B>, B>>(
delegate().iterator()) {
@Override
- Entry<Class<? extends B>, B> transform(Entry<Class<? extends B>, B> from) {
+ Entry<Class<? extends @NonNull B>, B> transform(
+ Entry<Class<? extends @NonNull B>, B> from) {
return checkedEntry(from);
}
};
@@ -147,14 +155,15 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
@Override
@CanIgnoreReturnValue
@CheckForNull
- public B put(Class<? extends B> key, B value) {
- return super.put(key, cast(key, value));
+ public B put(Class<? extends @NonNull B> key, @ParametricNullness B value) {
+ cast(key, value);
+ return super.put(key, value);
}
@Override
- public void putAll(Map<? extends Class<? extends B>, ? extends B> map) {
- Map<Class<? extends B>, B> copy = new LinkedHashMap<>(map);
- for (Entry<? extends Class<? extends B>, B> entry : copy.entrySet()) {
+ public void putAll(Map<? extends Class<? extends @NonNull B>, ? extends B> map) {
+ Map<Class<? extends @NonNull B>, B> copy = new LinkedHashMap<>(map);
+ for (Entry<? extends Class<? extends @NonNull B>, B> entry : copy.entrySet()) {
cast(entry.getKey(), entry.getValue());
}
super.putAll(copy);
@@ -163,19 +172,19 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
@CanIgnoreReturnValue
@Override
@CheckForNull
- public <T extends B> T putInstance(Class<T> type, T value) {
+ public <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value) {
return cast(type, put(type, value));
}
@Override
@CheckForNull
- public <T extends B> T getInstance(Class<T> type) {
+ public <T extends @NonNull B> T getInstance(Class<T> type) {
return cast(type, get(type));
}
@CanIgnoreReturnValue
@CheckForNull
- private static <B, T extends B> T cast(Class<T> type, @CheckForNull B value) {
+ private static <T> T cast(Class<T> type, @CheckForNull Object value) {
return Primitives.wrap(type).cast(value);
}
@@ -183,11 +192,15 @@ public final class MutableClassToInstanceMap<B> extends ForwardingMap<Class<? ex
return new SerializedForm(delegate());
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/** Serialized form of the map, to avoid serializing the constraint. */
- private static final class SerializedForm<B> implements Serializable {
- private final Map<Class<? extends B>, B> backingMap;
+ private static final class SerializedForm<B extends @Nullable Object> implements Serializable {
+ private final Map<Class<? extends @NonNull B>, B> backingMap;
- SerializedForm(Map<Class<? extends B>, B> backingMap) {
+ SerializedForm(Map<Class<? extends @NonNull B>, B> backingMap) {
this.backingMap = backingMap;
}
diff --git a/guava/src/com/google/common/collect/NaturalOrdering.java b/guava/src/com/google/common/collect/NaturalOrdering.java
index 8cb8aef9a..dae531270 100644
--- a/guava/src/com/google/common/collect/NaturalOrdering.java
+++ b/guava/src/com/google/common/collect/NaturalOrdering.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -30,8 +31,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
final class NaturalOrdering extends Ordering<Comparable<?>> implements Serializable {
static final NaturalOrdering INSTANCE = new NaturalOrdering();
- @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsFirst;
- @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsLast;
+ // TODO: b/287198172 - Consider eagerly initializing these (but think about serialization).
+ @LazyInit @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsFirst;
+ @LazyInit @CheckForNull private transient Ordering<@Nullable Comparable<?>> nullsLast;
@Override
public int compare(Comparable<?> left, Comparable<?> right) {
diff --git a/guava/src/com/google/common/collect/NullsFirstOrdering.java b/guava/src/com/google/common/collect/NullsFirstOrdering.java
index ce8be2fa3..c451ea8c0 100644
--- a/guava/src/com/google/common/collect/NullsFirstOrdering.java
+++ b/guava/src/com/google/common/collect/NullsFirstOrdering.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** An ordering that treats {@code null} as less than all other values. */
@@ -50,18 +51,18 @@ final class NullsFirstOrdering<T extends @Nullable Object> extends Ordering<@Nul
@SuppressWarnings("nullness") // should be safe, but not sure if we can avoid the warning
public <S extends @Nullable T> Ordering<S> reverse() {
// ordering.reverse() might be optimized, so let it do its thing
- return ordering.reverse().nullsLast();
+ return ordering.<T>reverse().<@NonNull S>nullsLast();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override
- public <S extends T> Ordering<@Nullable S> nullsFirst() {
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsFirst() {
return (Ordering<@Nullable S>) this;
}
@Override
- public <S extends T> Ordering<@Nullable S> nullsLast() {
- return ordering.<S>nullsLast();
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsLast() {
+ return ordering.<@NonNull S>nullsLast();
}
@Override
diff --git a/guava/src/com/google/common/collect/NullsLastOrdering.java b/guava/src/com/google/common/collect/NullsLastOrdering.java
index 6f8f74cdd..88917852e 100644
--- a/guava/src/com/google/common/collect/NullsLastOrdering.java
+++ b/guava/src/com/google/common/collect/NullsLastOrdering.java
@@ -19,6 +19,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** An ordering that treats {@code null} as greater than all other values. */
@@ -50,17 +51,17 @@ final class NullsLastOrdering<T extends @Nullable Object> extends Ordering<@Null
@SuppressWarnings("nullness") // should be safe, but not sure if we can avoid the warning
public <S extends @Nullable T> Ordering<S> reverse() {
// ordering.reverse() might be optimized, so let it do its thing
- return ordering.reverse().nullsFirst();
+ return ordering.<T>reverse().<@NonNull S>nullsFirst();
}
@Override
- public <S extends T> Ordering<@Nullable S> nullsFirst() {
- return ordering.<S>nullsFirst();
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsFirst() {
+ return ordering.<@NonNull S>nullsFirst();
}
@SuppressWarnings("unchecked") // still need the right way to explain this
@Override
- public <S extends T> Ordering<@Nullable S> nullsLast() {
+ public <S extends @Nullable T> Ordering<@Nullable S> nullsLast() {
return (Ordering<@Nullable S>) this;
}
diff --git a/guava/src/com/google/common/collect/ObjectArrays.java b/guava/src/com/google/common/collect/ObjectArrays.java
index d3b048da7..1a2df3b3e 100644
--- a/guava/src/com/google/common/collect/ObjectArrays.java
+++ b/guava/src/com/google/common/collect/ObjectArrays.java
@@ -24,6 +24,7 @@ import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -34,6 +35,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
+@SuppressWarnings("AvoidObjectArrays")
public final class ObjectArrays {
private ObjectArrays() {}
@@ -46,7 +48,7 @@ public final class ObjectArrays {
*/
@GwtIncompatible // Array.newInstance(Class, int)
@SuppressWarnings("unchecked")
- public static <T> T[] newArray(Class<T> type, int length) {
+ public static <T extends @Nullable Object> T[] newArray(Class<@NonNull T> type, int length) {
return (T[]) Array.newInstance(type, length);
}
@@ -68,7 +70,8 @@ public final class ObjectArrays {
* @param type the component type of the returned array
*/
@GwtIncompatible // Array.newInstance(Class, int)
- public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
+ public static <T extends @Nullable Object> T[] concat(
+ T[] first, T[] second, Class<@NonNull T> type) {
T[] result = newArray(type, first.length + second.length);
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
diff --git a/guava/src/com/google/common/collect/Ordering.java b/guava/src/com/google/common/collect/Ordering.java
index 9bf180fc2..cca04f6e7 100644
--- a/guava/src/com/google/common/collect/Ordering.java
+++ b/guava/src/com/google/common/collect/Ordering.java
@@ -20,9 +20,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -39,6 +39,7 @@ import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -172,6 +173,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* to pass it in here. Instead, simply subclass {@code Ordering} and implement its {@code compare}
* method directly.
*
+ * <p>The returned object is serializable if {@code comparator} is serializable.
+ *
* <p><b>Java 8 users:</b> this class is now obsolete as explained in the class documentation, so
* there is no need to use this method.
*
@@ -313,14 +316,17 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* @since 2.0
*/
// TODO(kevinb): copy to Comparators, etc.
+ @J2ktIncompatible // MapMaker
public static Ordering<@Nullable Object> arbitrary() {
return ArbitraryOrderingHolder.ARBITRARY_ORDERING;
}
+ @J2ktIncompatible // MapMaker
private static class ArbitraryOrderingHolder {
static final Ordering<@Nullable Object> ARBITRARY_ORDERING = new ArbitraryOrdering();
}
+ @J2ktIncompatible // MapMaker
@VisibleForTesting
static class ArbitraryOrdering extends Ordering<@Nullable Object> {
@@ -411,6 +417,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* Returns an ordering that treats {@code null} as less than all other values and uses {@code
* this} to compare non-null values.
*
+ * <p>The returned object is serializable if this object is serializable.
+ *
* <p><b>Java 8 users:</b> Use {@code Comparator.nullsFirst(thisComparator)} instead.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
@@ -424,6 +432,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* Returns an ordering that treats {@code null} as greater than all other values and uses this
* ordering to compare non-null values.
*
+ * <p>The returned object is serializable if this object is serializable.
+ *
* <p><b>Java 8 users:</b> Use {@code Comparator.nullsLast(thisComparator)} instead.
*/
// type parameter <S> lets us avoid the extra <String> in statements like:
@@ -464,6 +474,9 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p>An ordering produced by this method, or a chain of calls to this method, is equivalent to
* one created using {@link Ordering#compound(Iterable)} on the same component comparators.
*
+ * <p>The returned object is serializable if this object and {@code secondaryComparator} are both
+ * serializable.
+ *
* <p><b>Java 8 users:</b> Use {@code thisComparator.thenComparing(secondaryComparator)} instead.
* Depending on what {@code secondaryComparator} is, one of the other overloads of {@code
* thenComparing} may be even more useful.
@@ -482,6 +495,8 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p>The returned ordering is equivalent to that produced using {@code
* Ordering.from(comp1).compound(comp2).compound(comp3) . . .}.
*
+ * <p>The returned object is serializable if each of the {@code comparators} is serializable.
+ *
* <p><b>Warning:</b> Supplying an argument with undefined iteration order, such as a {@link
* HashSet}, will produce non-deterministic results.
*
@@ -530,7 +545,6 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
// Regular instance methods
- @CanIgnoreReturnValue // TODO(kak): Consider removing this
@Override
public abstract int compare(@ParametricNullness T left, @ParametricNullness T right);
@@ -567,7 +581,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p><b>Java 8 users:</b> If {@code iterable} is a {@link Collection}, use {@code
* Collections.min(collection, thisComparator)} instead. Otherwise, use {@code
* Streams.stream(iterable).min(thisComparator).get()} instead. Note that these alternatives do
- * not guarantee which tied minimum element is returned)
+ * not guarantee which tied minimum element is returned.
*
* @param iterable the iterable whose minimum element is to be determined
* @throws NoSuchElementException if {@code iterable} is empty
@@ -658,7 +672,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* <p><b>Java 8 users:</b> If {@code iterable} is a {@link Collection}, use {@code
* Collections.max(collection, thisComparator)} instead. Otherwise, use {@code
* Streams.stream(iterable).max(thisComparator).get()} instead. Note that these alternatives do
- * not guarantee which tied maximum element is returned)
+ * not guarantee which tied maximum element is returned.
*
* @param iterable the iterable whose maximum element is to be determined
* @throws NoSuchElementException if {@code iterable} is empty
@@ -809,7 +823,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) {
// TODO(kevinb): see if delegation is hurting performance noticeably
// TODO(kevinb): if we change this implementation, add full unit tests.
- return reverse().leastOf(iterable, k);
+ return this.<E>reverse().leastOf(iterable, k);
}
/**
@@ -829,7 +843,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* @since 14.0
*/
public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) {
- return reverse().leastOf(iterator, k);
+ return this.<E>reverse().leastOf(iterator, k);
}
/**
@@ -871,8 +885,7 @@ public abstract class Ordering<T extends @Nullable Object> implements Comparator
* @since 3.0
*/
// TODO(kevinb): rerun benchmarks including new options
- @SuppressWarnings("nullness") // unsafe, but there's not much we can do about it now
- public <E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) {
+ public <E extends @NonNull T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) {
return ImmutableList.sortedCopyOf(this, elements);
}
diff --git a/guava/src/com/google/common/collect/ParametricNullness.java b/guava/src/com/google/common/collect/ParametricNullness.java
index 94b1bcd3a..207c05262 100644
--- a/guava/src/com/google/common/collect/ParametricNullness.java
+++ b/guava/src/com/google/common/collect/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/collect/Platform.java b/guava/src/com/google/common/collect/Platform.java
index b1d6b2f43..3f118764e 100644
--- a/guava/src/com/google/common/collect/Platform.java
+++ b/guava/src/com/google/common/collect/Platform.java
@@ -17,7 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
-import java.lang.reflect.Array;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
@@ -98,13 +98,8 @@ final class Platform {
* ObjectArrays, which is the main caller of this method.)
*/
static <T extends @Nullable Object> T[] newArray(T[] reference, int length) {
- Class<?> type = reference.getClass().getComponentType();
-
- // the cast is safe because
- // result.getClass() == reference.getClass().getComponentType()
- @SuppressWarnings("unchecked")
- T[] result = (T[]) Array.newInstance(type, length);
- return result;
+ T[] empty = reference.length == 0 ? reference : Arrays.copyOf(reference, 0);
+ return Arrays.copyOf(empty, length);
}
/** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */
@@ -126,10 +121,15 @@ final class Platform {
* GWT). This is sometimes acceptable, when only server-side code could generate enough volume
* that reclamation becomes important.
*/
+ @J2ktIncompatible
static MapMaker tryWeakKeys(MapMaker mapMaker) {
return mapMaker.weakKeys();
}
+ static <E extends Enum<E>> Class<E> getDeclaringClassOrObjectForJ2cl(E e) {
+ return e.getDeclaringClass();
+ }
+
static int reduceIterationsIfGwt(int iterations) {
return iterations;
}
@@ -138,26 +138,5 @@ final class Platform {
return exponent;
}
- static void checkGwtRpcEnabled() {
- String propertyName = "guava.gwt.emergency_reenable_rpc";
-
- if (!Boolean.parseBoolean(System.getProperty(propertyName, "false"))) {
- throw new UnsupportedOperationException(
- com.google.common.base.Strings.lenientFormat(
- "We are removing GWT-RPC support for Guava types. You can temporarily reenable"
- + " support by setting the system property %s to true. For more about system"
- + " properties, see %s. For more about Guava's GWT-RPC support, see %s.",
- propertyName,
- "https://stackoverflow.com/q/5189914/28465",
- "https://groups.google.com/d/msg/guava-announce/zHZTFg7YF3o/rQNnwdHeEwAJ"));
- }
- logger.log(
- java.util.logging.Level.WARNING,
- "Later in 2020, we will remove GWT-RPC support for Guava types. You are seeing this"
- + " warning because you are sending a Guava type over GWT-RPC, which will break. You"
- + " can identify which type by looking at the class name in the attached stack trace.",
- new Throwable());
- }
-
private Platform() {}
}
diff --git a/guava/src/com/google/common/collect/Queues.java b/guava/src/com/google/common/collect/Queues.java
index a140102fd..58dc85e8f 100644
--- a/guava/src/com/google/common/collect/Queues.java
+++ b/guava/src/com/google/common/collect/Queues.java
@@ -14,9 +14,9 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayDeque;
@@ -52,6 +52,7 @@ public final class Queues {
* Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity and nonfair access
* policy.
*/
+ @J2ktIncompatible
@GwtIncompatible // ArrayBlockingQueue
public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) {
return new ArrayBlockingQueue<E>(capacity);
@@ -86,6 +87,7 @@ public final class Queues {
// ConcurrentLinkedQueue
/** Creates an empty {@code ConcurrentLinkedQueue}. */
+ @J2ktIncompatible
@GwtIncompatible // ConcurrentLinkedQueue
public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() {
return new ConcurrentLinkedQueue<E>();
@@ -95,6 +97,7 @@ public final class Queues {
* Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, in
* the order they are returned by the iterable's iterator.
*/
+ @J2ktIncompatible
@GwtIncompatible // ConcurrentLinkedQueue
public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue(
Iterable<? extends E> elements) {
@@ -113,6 +116,7 @@ public final class Queues {
*
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingDeque
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() {
return new LinkedBlockingDeque<E>();
@@ -124,6 +128,7 @@ public final class Queues {
* @throws IllegalArgumentException if {@code capacity} is less than 1
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingDeque
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) {
return new LinkedBlockingDeque<E>(capacity);
@@ -136,6 +141,7 @@ public final class Queues {
*
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingDeque
public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
@@ -149,6 +155,7 @@ public final class Queues {
// LinkedBlockingQueue
/** Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingQueue
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() {
return new LinkedBlockingQueue<E>();
@@ -159,6 +166,7 @@ public final class Queues {
*
* @throws IllegalArgumentException if {@code capacity} is less than 1
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingQueue
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) {
return new LinkedBlockingQueue<E>(capacity);
@@ -172,6 +180,7 @@ public final class Queues {
* @param elements the elements that the queue should contain, in order
* @return a new {@code LinkedBlockingQueue} containing those elements
*/
+ @J2ktIncompatible
@GwtIncompatible // LinkedBlockingQueue
public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
@@ -193,6 +202,7 @@ public final class Queues {
* @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
* in 15.0)
*/
+ @J2ktIncompatible
@GwtIncompatible // PriorityBlockingQueue
public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() {
return new PriorityBlockingQueue<E>();
@@ -207,6 +217,7 @@ public final class Queues {
* @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
* in 15.0)
*/
+ @J2ktIncompatible
@GwtIncompatible // PriorityBlockingQueue
public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(
Iterable<? extends E> elements) {
@@ -253,6 +264,7 @@ public final class Queues {
// SynchronousQueue
/** Creates an empty {@code SynchronousQueue} with nonfair access policy. */
+ @J2ktIncompatible
@GwtIncompatible // SynchronousQueue
public static <E> SynchronousQueue<E> newSynchronousQueue() {
return new SynchronousQueue<E>();
@@ -270,8 +282,8 @@ public final class Queues {
* @throws InterruptedException if interrupted while waiting
* @since 28.0
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // BlockingQueue
public static <E> int drain(
BlockingQueue<E> q, Collection<? super E> buffer, int numElements, java.time.Duration timeout)
@@ -292,8 +304,8 @@ public final class Queues {
* @return the number of elements transferred
* @throws InterruptedException if interrupted while waiting
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // BlockingQueue
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <E> int drain(
@@ -340,8 +352,8 @@ public final class Queues {
* @return the number of elements transferred
* @since 28.0
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // BlockingQueue
public static <E> int drainUninterruptibly(
BlockingQueue<E> q,
@@ -365,8 +377,8 @@ public final class Queues {
* @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
* @return the number of elements transferred
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // BlockingQueue
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <E> int drainUninterruptibly(
diff --git a/guava/src/com/google/common/collect/Range.java b/guava/src/com/google/common/collect/Range.java
index 2a5d464dc..fa6607dd8 100644
--- a/guava/src/com/google/common/collect/Range.java
+++ b/guava/src/com/google/common/collect/Range.java
@@ -23,6 +23,7 @@ import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
+import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
@@ -105,6 +106,7 @@ import javax.annotation.CheckForNull;
* <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}.
* Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having
* property <i>P</i>. See, for example, the definition of {@link #intersection intersection}.
+ * <li>A {@code Range} is serializable if it has no bounds, or if each bound is serializable.
* </ul>
*
* <h3>Further reading</h3>
@@ -118,6 +120,7 @@ import javax.annotation.CheckForNull;
*/
@GwtCompatible
@SuppressWarnings("rawtypes")
+@Immutable(containerOf = "C")
@ElementTypesAreNonnullByDefault
public final class Range<C extends Comparable> extends RangeGwtSerializationDependencies
implements Predicate<C>, Serializable {
@@ -333,7 +336,7 @@ public final class Range<C extends Comparable> extends RangeGwtSerializationDepe
if (values instanceof SortedSet) {
SortedSet<C> set = (SortedSet<C>) values;
Comparator<?> comparator = set.comparator();
- if (Ordering.natural().equals(comparator) || comparator == null) {
+ if (Ordering.<C>natural().equals(comparator) || comparator == null) {
return closed(set.first(), set.last());
}
}
@@ -342,8 +345,8 @@ public final class Range<C extends Comparable> extends RangeGwtSerializationDepe
C max = min;
while (valueIterator.hasNext()) {
C value = checkNotNull(valueIterator.next());
- min = Ordering.natural().min(min, value);
- max = Ordering.natural().max(max, value);
+ min = Ordering.<C>natural().min(min, value);
+ max = Ordering.<C>natural().max(max, value);
}
return closed(min, max);
}
diff --git a/guava/src/com/google/common/collect/RangeMap.java b/guava/src/com/google/common/collect/RangeMap.java
index 99e7b97d5..7185ee6d1 100644
--- a/guava/src/com/google/common/collect/RangeMap.java
+++ b/guava/src/com/google/common/collect/RangeMap.java
@@ -16,7 +16,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Collection;
@@ -37,7 +36,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@DoNotMock("Use ImmutableRangeMap or TreeRangeMap")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
@@ -103,7 +101,7 @@ public interface RangeMap<K extends Comparable, V> {
void putCoalescing(Range<K> range, V value);
/** Puts all the associations from {@code rangeMap} into this range map (optional operation). */
- void putAll(RangeMap<K, V> rangeMap);
+ void putAll(RangeMap<K, ? extends V> rangeMap);
/** Removes all associations from this range map (optional operation). */
void clear();
diff --git a/guava/src/com/google/common/collect/RangeSet.java b/guava/src/com/google/common/collect/RangeSet.java
index 79fbab159..9138c5d98 100644
--- a/guava/src/com/google/common/collect/RangeSet.java
+++ b/guava/src/com/google/common/collect/RangeSet.java
@@ -14,7 +14,6 @@
package com.google.common.collect;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.util.NoSuchElementException;
@@ -49,7 +48,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@DoNotMock("Use ImmutableRangeSet or TreeRangeSet")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
diff --git a/guava/src/com/google/common/collect/RegularContiguousSet.java b/guava/src/com/google/common/collect/RegularContiguousSet.java
index 787606eb1..9c2e5a26f 100644
--- a/guava/src/com/google/common/collect/RegularContiguousSet.java
+++ b/guava/src/com/google/common/collect/RegularContiguousSet.java
@@ -22,6 +22,9 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import javax.annotation.CheckForNull;
@@ -181,8 +184,8 @@ final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C>
if (other.isEmpty()) {
return other;
} else {
- C lowerEndpoint = Ordering.natural().max(this.first(), other.first());
- C upperEndpoint = Ordering.natural().min(this.last(), other.last());
+ C lowerEndpoint = Ordering.<C>natural().max(this.first(), other.first());
+ C upperEndpoint = Ordering.<C>natural().min(this.last(), other.last());
return (lowerEndpoint.compareTo(upperEndpoint) <= 0)
? ContiguousSet.create(Range.closed(lowerEndpoint, upperEndpoint), domain)
: new EmptyContiguousSet<C>(domain);
@@ -221,6 +224,7 @@ final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C>
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
private static final class SerializedForm<C extends Comparable> implements Serializable {
final Range<C> range;
final DiscreteDomain<C> domain;
@@ -236,10 +240,17 @@ final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C>
}
@GwtIncompatible // serialization
+ @J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm<>(range, domain);
}
+ @GwtIncompatible // serialization
+ @J2ktIncompatible
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/RegularImmutableBiMap.java b/guava/src/com/google/common/collect/RegularImmutableBiMap.java
index b8bca9580..333b80177 100644
--- a/guava/src/com/google/common/collect/RegularImmutableBiMap.java
+++ b/guava/src/com/google/common/collect/RegularImmutableBiMap.java
@@ -25,11 +25,14 @@ import static com.google.common.collect.RegularImmutableMap.checkNoConflictInKey
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableBiMapEntry;
import com.google.common.collect.RegularImmutableMap.BucketOverflowException;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -292,11 +295,18 @@ class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
}
@Override
+ @J2ktIncompatible // serialization
Object writeReplace() {
return new InverseSerializedForm<>(RegularImmutableBiMap.this);
}
+
+ @J2ktIncompatible // java.io.ObjectInputStream
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use InverseSerializedForm");
+ }
}
+ @J2ktIncompatible // serialization
private static class InverseSerializedForm<K, V> implements Serializable {
private final ImmutableBiMap<K, V> forward;
diff --git a/guava/src/com/google/common/collect/RegularImmutableMap.java b/guava/src/com/google/common/collect/RegularImmutableMap.java
index f0f2031b9..42649109a 100644
--- a/guava/src/com/google/common/collect/RegularImmutableMap.java
+++ b/guava/src/com/google/common/collect/RegularImmutableMap.java
@@ -24,6 +24,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableMapEntry;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -149,7 +150,10 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// Make sure we are not overwriting the original entries array, in case we later do
// buildOrThrow(). We would want an exception to include two values for the duplicate key.
if (entries == entryArray) {
- entries = entries.clone();
+ // Temporary variable is necessary to defeat bad smartcast (entries adopting the type of
+ // entryArray) in the Kotlin translation.
+ Entry<K, V>[] originalEntries = entries;
+ entries = originalEntries.clone();
}
}
entries[entryIndex] = effectiveEntry;
@@ -228,7 +232,8 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
* flooding attack
*/
@CanIgnoreReturnValue
- static <K, V> @Nullable ImmutableMapEntry<K, V> checkNoConflictInKeyBucket(
+ @CheckForNull
+ static <K, V> ImmutableMapEntry<K, V> checkNoConflictInKeyBucket(
Object key,
Object newValue,
@CheckForNull ImmutableMapEntry<K, V> keyBucketHead,
@@ -343,6 +348,7 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
+ @J2ktIncompatible
@SuppressWarnings("unused")
private static class SerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
@@ -355,6 +361,7 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
return map.keySet();
}
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
}
@@ -389,6 +396,7 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
+ @J2ktIncompatible
@SuppressWarnings("unused")
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
@@ -401,11 +409,13 @@ final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
return map.values();
}
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
+ @J2ktIncompatible // serialization
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/Serialization.java b/guava/src/com/google/common/collect/Serialization.java
index 4ab53f2d7..e12e84cd2 100644
--- a/guava/src/com/google/common/collect/Serialization.java
+++ b/guava/src/com/google/common/collect/Serialization.java
@@ -17,6 +17,7 @@
package com.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -34,6 +35,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jared Levy
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
final class Serialization {
private Serialization() {}
diff --git a/guava/src/com/google/common/collect/Sets.java b/guava/src/com/google/common/collect/Sets.java
index c8cdc38ca..da3814881 100644
--- a/guava/src/com/google/common/collect/Sets.java
+++ b/guava/src/com/google/common/collect/Sets.java
@@ -20,15 +20,16 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
@@ -53,6 +54,7 @@ import java.util.function.Consumer;
import java.util.stream.Collector;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -439,6 +441,7 @@ public final class Sets {
* @return a new, empty {@code CopyOnWriteArraySet}
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
return new CopyOnWriteArraySet<E>();
@@ -451,6 +454,7 @@ public final class Sets {
* @return a new {@code CopyOnWriteArraySet} containing those elements
* @since 12.0
*/
+ @J2ktIncompatible
@GwtIncompatible // CopyOnWriteArraySet
public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(
Iterable<? extends E> elements) {
@@ -476,6 +480,8 @@ public final class Sets {
* @throws IllegalArgumentException if {@code collection} is not an {@code EnumSet} instance and
* contains no elements
*/
+ @J2ktIncompatible
+ @GwtIncompatible
public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) {
if (collection instanceof EnumSet) {
return EnumSet.complementOf((EnumSet<E>) collection);
@@ -496,6 +502,7 @@ public final class Sets {
* @return a new, modifiable {@code EnumSet} initially containing all the values of the enum not
* present in the given collection
*/
+ @GwtIncompatible
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection, Class<E> type) {
checkNotNull(collection);
@@ -504,6 +511,7 @@ public final class Sets {
: makeComplementByHand(collection, type);
}
+ @GwtIncompatible
private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
Collection<E> collection, Class<E> type) {
EnumSet<E> result = EnumSet.allOf(type);
@@ -567,8 +575,8 @@ public final class Sets {
* that is inconsistent with {@link Object#equals(Object)}.
*/
@SuppressWarnings("nullness") // Unsafe, but we can't fix it now.
- public ImmutableSet<E> immutableCopy() {
- return ImmutableSet.copyOf(this);
+ public ImmutableSet<@NonNull E> immutableCopy() {
+ return ImmutableSet.copyOf((SetView<@NonNull E>) this);
}
/**
@@ -770,9 +778,13 @@ public final class Sets {
}
@Override
- @SuppressWarnings("nullness") // see supertype
- public ImmutableSet<E> immutableCopy() {
- return new ImmutableSet.Builder<E>().addAll(set1).addAll(set2).build();
+ @SuppressWarnings({"nullness", "unchecked"}) // see supertype
+ public ImmutableSet<@NonNull E> immutableCopy() {
+ ImmutableSet.Builder<@NonNull E> builder =
+ new ImmutableSet.Builder<@NonNull E>()
+ .addAll((Iterable<@NonNull E>) set1)
+ .addAll((Iterable<@NonNull E>) set2);
+ return (ImmutableSet<@NonNull E>) builder.build();
}
};
}
@@ -1647,7 +1659,6 @@ public final class Sets {
* @throws NullPointerException if {@code set} is or contains {@code null}
* @since 23.0
*/
- @Beta
public static <E> Set<Set<E>> combinations(Set<E> set, final int size) {
final ImmutableMap<E, Integer> index = Maps.indexMap(set);
checkNonnegative(size, "size");
@@ -1786,6 +1797,8 @@ public final class Sets {
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
+ * <p><b>Java 8 users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}.
+ *
* @param set the navigable set for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified navigable set
* @since 12.0
@@ -1871,7 +1884,7 @@ public final class Sets {
throw new UnsupportedOperationException();
}
- @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
+ @LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet;
@Override
public NavigableSet<E> descendingSet() {
@@ -1952,6 +1965,8 @@ public final class Sets {
* <p>The returned navigable set will be serializable if the specified navigable set is
* serializable.
*
+ * <p><b>Java 8 users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}.
+ *
* @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set.
* @return a synchronized view of the specified navigable set.
* @since 13.0
@@ -2149,7 +2164,6 @@ public final class Sets {
*
* @since 20.0
*/
- @Beta
@GwtIncompatible // NavigableSet
public static <K extends Comparable<? super K>> NavigableSet<K> subSet(
NavigableSet<K> set, Range<K> range) {
diff --git a/guava/src/com/google/common/collect/SortedLists.java b/guava/src/com/google/common/collect/SortedLists.java
index 0ebaab20f..245d01821 100644
--- a/guava/src/com/google/common/collect/SortedLists.java
+++ b/guava/src/com/google/common/collect/SortedLists.java
@@ -16,7 +16,6 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.Collections;
@@ -35,7 +34,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
*/
@GwtCompatible
-@Beta
@ElementTypesAreNonnullByDefault
final class SortedLists {
private SortedLists() {}
diff --git a/guava/src/com/google/common/collect/SortedMultiset.java b/guava/src/com/google/common/collect/SortedMultiset.java
index 7cc512d8e..87969b52c 100644
--- a/guava/src/com/google/common/collect/SortedMultiset.java
+++ b/guava/src/com/google/common/collect/SortedMultiset.java
@@ -92,8 +92,8 @@ public interface SortedMultiset<E extends @Nullable Object>
/**
* {@inheritDoc}
*
- * <p>The {@code entrySet}'s iterator returns entries in ascending element order according to the
- * this multiset's comparator.
+ * <p>The {@code entrySet}'s iterator returns entries in ascending element order according to this
+ * multiset's comparator.
*/
@Override
Set<Entry<E>> entrySet();
diff --git a/guava/src/com/google/common/collect/StandardTable.java b/guava/src/com/google/common/collect/StandardTable.java
index 06defb0eb..6ec3c6b23 100644
--- a/guava/src/com/google/common/collect/StandardTable.java
+++ b/guava/src/com/google/common/collect/StandardTable.java
@@ -34,6 +34,7 @@ import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import com.google.common.collect.Maps.ViewCachingAbstractMap;
import com.google.common.collect.Sets.ImprovedAbstractSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.Collection;
@@ -674,7 +675,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
return rowMap().keySet();
}
- @CheckForNull private transient Set<C> columnKeySet;
+ @LazyInit @CheckForNull private transient Set<C> columnKeySet;
/**
* {@inheritDoc}
@@ -805,7 +806,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
return super.values();
}
- @CheckForNull private transient Map<R, Map<C, V>> rowMap;
+ @LazyInit @CheckForNull private transient Map<R, Map<C, V>> rowMap;
@Override
public Map<R, Map<C, V>> rowMap() {
@@ -887,7 +888,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
}
}
- @CheckForNull private transient ColumnMap columnMap;
+ @LazyInit @CheckForNull private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, V>> columnMap() {
@@ -982,7 +983,7 @@ class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializa
public boolean removeAll(Collection<?> c) {
/*
* We can't inherit the normal implementation (which calls
- * Sets.removeAllImpl(Set, *Collection*) because, under some
+ * Sets.removeAllImpl(Set, *Collection*)) because, under some
* circumstances, it attempts to call columnKeySet().iterator().remove,
* which is unsupported.
*/
diff --git a/guava/src/com/google/common/collect/Streams.java b/guava/src/com/google/common/collect/Streams.java
index cd7a07c34..0b6e88ce2 100644
--- a/guava/src/com/google/common/collect/Streams.java
+++ b/guava/src/com/google/common/collect/Streams.java
@@ -74,7 +74,6 @@ public final class Streams {
*
* @deprecated There is no reason to use this; just invoke {@code collection.stream()} directly.
*/
- @Beta
@Deprecated
@InlineMe(replacement = "collection.stream()")
public static <T extends @Nullable Object> Stream<T> stream(Collection<T> collection) {
@@ -85,7 +84,6 @@ public final class Streams {
* Returns a sequential {@link Stream} of the remaining contents of {@code iterator}. Do not use
* {@code iterator} directly after passing it to this method.
*/
- @Beta
public static <T extends @Nullable Object> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
}
@@ -94,7 +92,6 @@ public final class Streams {
* If a value is present in {@code optional}, returns a stream containing only that element,
* otherwise returns an empty stream.
*/
- @Beta
public static <T> Stream<T> stream(com.google.common.base.Optional<T> optional) {
return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
}
diff --git a/guava/src/com/google/common/collect/Synchronized.java b/guava/src/com/google/common/collect/Synchronized.java
index 29fe61a89..b1422e316 100644
--- a/guava/src/com/google/common/collect/Synchronized.java
+++ b/guava/src/com/google/common/collect/Synchronized.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.j2objc.annotations.RetainedWith;
import java.io.IOException;
@@ -104,6 +105,7 @@ final class Synchronized {
// following writeObject() handles the SynchronizedObject members.
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
synchronized (mutex) {
stream.defaultWriteObject();
@@ -111,6 +113,7 @@ final class Synchronized {
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
@@ -444,7 +447,7 @@ final class Synchronized {
}
@Override
- public void sort(Comparator<? super E> c) {
+ public void sort(@Nullable Comparator<? super E> c) {
synchronized (mutex) {
delegate().sort(c);
}
@@ -516,7 +519,7 @@ final class Synchronized {
}
@Override
- public int add(E e, int n) {
+ public int add(@ParametricNullness E e, int n) {
synchronized (mutex) {
return delegate().add(e, n);
}
@@ -530,14 +533,14 @@ final class Synchronized {
}
@Override
- public int setCount(E element, int count) {
+ public int setCount(@ParametricNullness E element, int count) {
synchronized (mutex) {
return delegate().setCount(element, count);
}
}
@Override
- public boolean setCount(E element, int oldCount, int newCount) {
+ public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) {
synchronized (mutex) {
return delegate().setCount(element, oldCount, newCount);
}
@@ -645,21 +648,21 @@ final class Synchronized {
}
@Override
- public Collection<V> get(K key) {
+ public Collection<V> get(@ParametricNullness K key) {
synchronized (mutex) {
return typePreservingCollection(delegate().get(key), mutex);
}
}
@Override
- public boolean put(K key, V value) {
+ public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
- public boolean putAll(K key, Iterable<? extends V> values) {
+ public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().putAll(key, values);
}
@@ -673,7 +676,7 @@ final class Synchronized {
}
@Override
- public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
+ public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
@@ -986,16 +989,15 @@ final class Synchronized {
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override
- public Object[] toArray() {
+ public @Nullable Object[] toArray() {
synchronized (mutex) {
/*
* toArrayImpl returns `@Nullable Object[]` rather than `Object[]` but only because it can
* be used with collections that may contain null. This collection never contains nulls, so
- * we can treat it as a plain `Object[]`.
+ * we could return `Object[]`. But this class is private and J2KT cannot change return types
+ * in overrides, so we declare `@Nullable Object[]` as the return type.
*/
- @SuppressWarnings("nullness")
- Object[] result = (Object[]) ObjectArrays.toArrayImpl(delegate());
- return result;
+ return ObjectArrays.toArrayImpl(delegate());
}
}
@@ -1203,8 +1205,9 @@ final class Synchronized {
}
@Override
+ @CheckForNull
public V merge(
- K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+ K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> remappingFunction) {
synchronized (mutex) {
return delegate().merge(key, value, remappingFunction);
}
@@ -1376,7 +1379,7 @@ final class Synchronized {
@Override
@CheckForNull
- public V forcePut(K key, V value) {
+ public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
synchronized (mutex) {
return delegate().forcePut(key, value);
}
@@ -2136,7 +2139,10 @@ final class Synchronized {
@Override
@CheckForNull
- public V put(R rowKey, C columnKey, V value) {
+ public V put(
+ @ParametricNullness R rowKey,
+ @ParametricNullness C columnKey,
+ @ParametricNullness V value) {
synchronized (mutex) {
return delegate().put(rowKey, columnKey, value);
}
@@ -2158,14 +2164,14 @@ final class Synchronized {
}
@Override
- public Map<C, V> row(R rowKey) {
+ public Map<C, V> row(@ParametricNullness R rowKey) {
synchronized (mutex) {
return map(delegate().row(rowKey), mutex);
}
}
@Override
- public Map<R, V> column(C columnKey) {
+ public Map<R, V> column(@ParametricNullness C columnKey) {
synchronized (mutex) {
return map(delegate().column(columnKey), mutex);
}
diff --git a/guava/src/com/google/common/collect/Table.java b/guava/src/com/google/common/collect/Table.java
index 3c9e7ec7a..05ceb1af8 100644
--- a/guava/src/com/google/common/collect/Table.java
+++ b/guava/src/com/google/common/collect/Table.java
@@ -45,6 +45,16 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* not be modifiable. When modification isn't supported, those methods will throw an {@link
* UnsupportedOperationException}.
*
+ * <h3>Implementations</h3>
+ *
+ * <ul>
+ * <li>{@link ImmutableTable}
+ * <li>{@link HashBasedTable}
+ * <li>{@link TreeBasedTable}
+ * <li>{@link ArrayTable}
+ * <li>{@link Tables#newCustomTable Tables.newCustomTable}
+ * </ul>
+ *
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>.
*
diff --git a/guava/src/com/google/common/collect/Tables.java b/guava/src/com/google/common/collect/Tables.java
index 9c58611d4..525c05355 100644
--- a/guava/src/com/google/common/collect/Tables.java
+++ b/guava/src/com/google/common/collect/Tables.java
@@ -20,7 +20,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
@@ -67,7 +66,6 @@ public final class Tables {
*
* @since 21.0
*/
- @Beta
public static <
T extends @Nullable Object,
R extends @Nullable Object,
@@ -317,7 +315,7 @@ public final class Tables {
}
// Will cast TRANSPOSE_CELL to a type that always succeeds
- private static final Function<Cell<?, ?, ?>, Cell<?, ?, ?>> TRANSPOSE_CELL =
+ private static final Function TRANSPOSE_CELL =
new Function<Cell<?, ?, ?>, Cell<?, ?, ?>>() {
@Override
public Cell<?, ?, ?> apply(Cell<?, ?, ?> cell) {
@@ -328,13 +326,16 @@ public final class Tables {
@SuppressWarnings("unchecked")
@Override
Iterator<Cell<C, R, V>> cellIterator() {
- return Iterators.transform(original.cellSet().iterator(), (Function) TRANSPOSE_CELL);
+ return Iterators.transform(
+ original.cellSet().iterator(), (Function<Cell<R, C, V>, Cell<C, R, V>>) TRANSPOSE_CELL);
}
@SuppressWarnings("unchecked")
@Override
Spliterator<Cell<C, R, V>> cellSpliterator() {
- return CollectSpliterators.map(original.cellSet().spliterator(), (Function) TRANSPOSE_CELL);
+ return CollectSpliterators.map(
+ original.cellSet().spliterator(),
+ (Function<Cell<R, C, V>, Cell<C, R, V>>) TRANSPOSE_CELL);
}
}
@@ -376,7 +377,6 @@ public final class Tables {
* @throws IllegalArgumentException if {@code backingMap} is not empty
* @since 10.0
*/
- @Beta
public static <R, C, V> Table<R, C, V> newCustomTable(
Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
checkArgument(backingMap.isEmpty());
@@ -406,7 +406,6 @@ public final class Tables {
*
* @since 10.0
*/
- @Beta
public static <
R extends @Nullable Object,
C extends @Nullable Object,
@@ -664,7 +663,6 @@ public final class Tables {
* @return an unmodifiable view of the specified table
* @since 11.0
*/
- @Beta
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
RowSortedTable<R, C, V> unmodifiableRowSortedTable(
RowSortedTable<R, ? extends C, ? extends V> table) {
diff --git a/guava/src/com/google/common/collect/TopKSelector.java b/guava/src/com/google/common/collect/TopKSelector.java
index 20b17fdef..f819f84a3 100644
--- a/guava/src/com/google/common/collect/TopKSelector.java
+++ b/guava/src/com/google/common/collect/TopKSelector.java
@@ -281,7 +281,9 @@ final class TopKSelector<
bufferSize = k;
threshold = buffer[k - 1];
}
+ // Up to bufferSize, all elements of buffer are real Ts (not null unless T includes null)
+ T[] topK = Arrays.copyOf(castBuffer, bufferSize);
// we have to support null elements, so no ImmutableList for us
- return Collections.unmodifiableList(Arrays.asList(Arrays.copyOf(buffer, bufferSize)));
+ return Collections.unmodifiableList(Arrays.asList(topK));
}
}
diff --git a/guava/src/com/google/common/collect/TreeMultimap.java b/guava/src/com/google/common/collect/TreeMultimap.java
index dd0c2f833..e449caa30 100644
--- a/guava/src/com/google/common/collect/TreeMultimap.java
+++ b/guava/src/com/google/common/collect/TreeMultimap.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -141,7 +142,7 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
@Override
Collection<V> createCollection(@ParametricNullness K key) {
if (key == null) {
- keyComparator().compare(key, key);
+ int unused = keyComparator().compare(key, key);
}
return super.createCollection(key);
}
@@ -201,6 +202,7 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
* distinct key: the key, number of values for that key, and key values
*/
@GwtIncompatible // java.io.ObjectOutputStream
+ @J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyComparator());
@@ -209,6 +211,7 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
}
@GwtIncompatible // java.io.ObjectInputStream
+ @J2ktIncompatible
@SuppressWarnings("unchecked") // reading data stored by writeObject
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -219,5 +222,6 @@ public class TreeMultimap<K extends @Nullable Object, V extends @Nullable Object
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 0;
}
diff --git a/guava/src/com/google/common/collect/TreeMultiset.java b/guava/src/com/google/common/collect/TreeMultiset.java
index 23cbca83e..7efafd8ec 100644
--- a/guava/src/com/google/common/collect/TreeMultiset.java
+++ b/guava/src/com/google/common/collect/TreeMultiset.java
@@ -25,6 +25,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -264,7 +265,7 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
- comparator().compare(element, element);
+ int unused = comparator().compare(element, element);
AvlNode<E> newRoot = new AvlNode<E>(element, occurrences);
successor(header, newRoot, header);
rootReference.checkAndSet(root, newRoot);
@@ -1073,6 +1074,7 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
* @serialData the comparator, the number of distinct elements, the first element, its count, the
* second element, its count, and so on
*/
+ @J2ktIncompatible
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
@@ -1080,6 +1082,7 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
Serialization.writeMultiset(this, stream);
}
+ @J2ktIncompatible
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@@ -1098,5 +1101,6 @@ public final class TreeMultiset<E extends @Nullable Object> extends AbstractSort
}
@GwtIncompatible // not needed in emulated source
+ @J2ktIncompatible
private static final long serialVersionUID = 1;
}
diff --git a/guava/src/com/google/common/collect/TreeRangeMap.java b/guava/src/com/google/common/collect/TreeRangeMap.java
index 60e7bf3df..747afb184 100644
--- a/guava/src/com/google/common/collect/TreeRangeMap.java
+++ b/guava/src/com/google/common/collect/TreeRangeMap.java
@@ -23,7 +23,6 @@ import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
@@ -51,7 +50,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
@@ -169,8 +167,8 @@ public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K,
}
@Override
- public void putAll(RangeMap<K, V> rangeMap) {
- for (Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) {
+ public void putAll(RangeMap<K, ? extends V> rangeMap) {
+ for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@@ -417,7 +415,7 @@ public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K,
}
@Override
- public void putAll(RangeMap<Comparable<?>, Object> rangeMap) {
+ public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
@@ -534,7 +532,7 @@ public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K,
}
@Override
- public void putAll(RangeMap<K, V> rangeMap) {
+ public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
diff --git a/guava/src/com/google/common/collect/TreeRangeSet.java b/guava/src/com/google/common/collect/TreeRangeSet.java
index 7ba71139e..415e80ffb 100644
--- a/guava/src/com/google/common/collect/TreeRangeSet.java
+++ b/guava/src/com/google/common/collect/TreeRangeSet.java
@@ -17,10 +17,10 @@ package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
@@ -38,7 +38,6 @@ import javax.annotation.CheckForNull;
* @author Louis Wasserman
* @since 14.0
*/
-@Beta
@GwtIncompatible // uses NavigableMap
@ElementTypesAreNonnullByDefault
public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
@@ -77,8 +76,8 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
this.rangesByLowerBound = rangesByLowerCut;
}
- @CheckForNull private transient Set<Range<C>> asRanges;
- @CheckForNull private transient Set<Range<C>> asDescendingSetOfRanges;
+ @LazyInit @CheckForNull private transient Set<Range<C>> asRanges;
+ @LazyInit @CheckForNull private transient Set<Range<C>> asDescendingSetOfRanges;
@Override
public Set<Range<C>> asRanges() {
@@ -274,7 +273,7 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
}
}
- @CheckForNull private transient RangeSet<C> complement;
+ @LazyInit @CheckForNull private transient RangeSet<C> complement;
@Override
public RangeSet<C> complement() {
@@ -802,7 +801,7 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
.iterator();
}
Cut<Cut<C>> upperBoundOnLowerBounds =
- Ordering.natural()
+ Ordering.<Cut<Cut<C>>>natural()
.min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound));
return new AbstractIterator<Entry<Cut<C>, Range<C>>>() {
@Override
@@ -828,7 +827,7 @@ public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C>
return Iterators.emptyIterator();
}
Cut<Cut<C>> upperBoundOnLowerBounds =
- Ordering.natural()
+ Ordering.<Cut<Cut<C>>>natural()
.min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound));
Iterator<Range<C>> completeRangeItr =
rangesByLowerBound
diff --git a/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java b/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
index 31f3c7197..c7e1d4c33 100644
--- a/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
+++ b/guava/src/com/google/common/collect/UnmodifiableSortedMultiset.java
@@ -18,6 +18,7 @@ package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multisets.UnmodifiableMultiset;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.util.Comparator;
import java.util.NavigableSet;
import javax.annotation.CheckForNull;
@@ -58,7 +59,7 @@ final class UnmodifiableSortedMultiset<E extends @Nullable Object> extends Unmod
return (NavigableSet<E>) super.elementSet();
}
- @CheckForNull private transient UnmodifiableSortedMultiset<E> descendingMultiset;
+ @LazyInit @CheckForNull private transient UnmodifiableSortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
diff --git a/guava/src/com/google/common/collect/package-info.java b/guava/src/com/google/common/collect/package-info.java
index d46e65fd3..ad169a685 100644
--- a/guava/src/com/google/common/collect/package-info.java
+++ b/guava/src/com/google/common/collect/package-info.java
@@ -15,201 +15,108 @@
*/
/**
- * This package contains generic collection interfaces and implementations, and other utilities for
- * working with collections. It is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Collection interfaces and implementations, and other utilities for collections. This package is a
+ * part of the open-source <a href="https://github.com/google/guava">Guava</a> library.
*
- * <h2>Collection Types</h2>
+ * <p>The classes in this package include:
+ *
+ * <h2>Immutable collections</h2>
+ *
+ * These are collections whose contents will never change. They also offer a few additional
+ * guarantees (see {@link ImmutableCollection} for details). Implementations are available for both
+ * the JDK collection types and the Guava collection types (listed below).
+ *
+ * <h2>Collection types</h2>
*
* <dl>
- * <dt>{@link com.google.common.collect.BiMap}
+ * <dt>{@link Multimap}
+ * <dd>A new type, which is similar to {@link java.util.Map}, but may contain multiple entries
+ * with the same key. Some behaviors of {@link Multimap} are left unspecified and are provided
+ * only by the subtypes mentioned below.
+ * <dt>{@link ListMultimap}
+ * <dd>An extension of {@link Multimap} which permits duplicate entries, supports random access of
+ * values for a particular key, and has <i>partially order-dependent equality</i> as defined
+ * by {@link ListMultimap#equals(Object)}. {@code ListMultimap} takes its name from the fact
+ * that the {@linkplain ListMultimap#get collection of values} associated with a given key
+ * fulfills the {@link java.util.List} contract.
+ * <dt>{@link SetMultimap}
+ * <dd>An extension of {@link Multimap} which has order-independent equality and does not allow
+ * duplicate entries; that is, while a key may appear twice in a {@code SetMultimap}, each
+ * must map to a different value. {@code SetMultimap} takes its name from the fact that the
+ * {@linkplain SetMultimap#get collection of values} associated with a given key fulfills the
+ * {@link java.util.Set} contract.
+ * <dt>{@link SortedSetMultimap}
+ * <dd>An extension of {@link SetMultimap} for which the {@linkplain SortedSetMultimap#get
+ * collection values} associated with a given key is a {@link java.util.SortedSet}.
+ * <dt>{@link BiMap}
* <dd>An extension of {@link java.util.Map} that guarantees the uniqueness of its values as well
* as that of its keys. This is sometimes called an "invertible map," since the restriction on
- * values enables it to support an {@linkplain com.google.common.collect.BiMap#inverse inverse
- * view} -- which is another instance of {@code BiMap}.
- * <dt>{@link com.google.common.collect.Multiset}
+ * values enables it to support an {@linkplain BiMap#inverse inverse view} -- which is another
+ * instance of {@code BiMap}.
+ * <dt>{@link Table}
+ * <dd>A new type, which is similar to {@link java.util.Map}, but which indexes its values by an
+ * ordered pair of keys, a row key and column key.
+ * <dt>{@link Multiset}
* <dd>An extension of {@link java.util.Collection} that may contain duplicate values like a
* {@link java.util.List}, yet has order-independent equality like a {@link java.util.Set}.
* One typical use for a multiset is to represent a histogram.
- * <dt>{@link com.google.common.collect.Multimap}
- * <dd>A new type, which is similar to {@link java.util.Map}, but may contain multiple entries
- * with the same key. Some behaviors of {@link com.google.common.collect.Multimap} are left
- * unspecified and are provided only by the subtypes mentioned below.
- * <dt>{@link com.google.common.collect.ListMultimap}
- * <dd>An extension of {@link com.google.common.collect.Multimap} which permits duplicate entries,
- * supports random access of values for a particular key, and has <i>partially order-dependent
- * equality</i> as defined by {@link com.google.common.collect.ListMultimap#equals(Object)}.
- * {@code ListMultimap} takes its name from the fact that the {@linkplain
- * com.google.common.collect.ListMultimap#get collection of values} associated with a given
- * key fulfills the {@link java.util.List} contract.
- * <dt>{@link com.google.common.collect.SetMultimap}
- * <dd>An extension of {@link com.google.common.collect.Multimap} which has order-independent
- * equality and does not allow duplicate entries; that is, while a key may appear twice in a
- * {@code SetMultimap}, each must map to a different value. {@code SetMultimap} takes its name
- * from the fact that the {@linkplain com.google.common.collect.SetMultimap#get collection of
- * values} associated with a given key fulfills the {@link java.util.Set} contract.
- * <dt>{@link com.google.common.collect.SortedSetMultimap}
- * <dd>An extension of {@link com.google.common.collect.SetMultimap} for which the {@linkplain
- * com.google.common.collect.SortedSetMultimap#get collection values} associated with a given
- * key is a {@link java.util.SortedSet}.
- * <dt>{@link com.google.common.collect.Table}
- * <dd>A new type, which is similar to {@link java.util.Map}, but which indexes its values by an
- * ordered pair of keys, a row key and column key.
- * <dt>{@link com.google.common.collect.ClassToInstanceMap}
+ * <dt>{@link ClassToInstanceMap}
* <dd>An extension of {@link java.util.Map} that associates a raw type with an instance of that
* type.
* </dl>
*
- * <h2>Collection Implementations</h2>
- *
- * <h3>of {@link java.util.List}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableList}
- * </ul>
- *
- * <h3>of {@link java.util.Set}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableSet}
- * <li>{@link com.google.common.collect.ImmutableSortedSet}
- * <li>{@link com.google.common.collect.ContiguousSet} (see {@code Range})
- * </ul>
- *
- * <h3>of {@link java.util.Map}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableMap}
- * <li>{@link com.google.common.collect.ImmutableSortedMap}
- * <li>{@link com.google.common.collect.MapMaker}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.BiMap}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableBiMap}
- * <li>{@link com.google.common.collect.HashBiMap}
- * <li>{@link com.google.common.collect.EnumBiMap}
- * <li>{@link com.google.common.collect.EnumHashBiMap}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.Multiset}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableMultiset}
- * <li>{@link com.google.common.collect.ImmutableSortedMultiset}
- * <li>{@link com.google.common.collect.HashMultiset}
- * <li>{@link com.google.common.collect.LinkedHashMultiset}
- * <li>{@link com.google.common.collect.TreeMultiset}
- * <li>{@link com.google.common.collect.EnumMultiset}
- * <li>{@link com.google.common.collect.ConcurrentHashMultiset}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.Multimap}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableMultimap}
- * <li>{@link com.google.common.collect.ImmutableListMultimap}
- * <li>{@link com.google.common.collect.ImmutableSetMultimap}
- * <li>{@link com.google.common.collect.ArrayListMultimap}
- * <li>{@link com.google.common.collect.HashMultimap}
- * <li>{@link com.google.common.collect.TreeMultimap}
- * <li>{@link com.google.common.collect.LinkedHashMultimap}
- * <li>{@link com.google.common.collect.LinkedListMultimap}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.Table}</h3>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ImmutableTable}
- * <li>{@link com.google.common.collect.ArrayTable}
- * <li>{@link com.google.common.collect.HashBasedTable}
- * <li>{@link com.google.common.collect.TreeBasedTable}
- * </ul>
- *
- * <h3>of {@link com.google.common.collect.ClassToInstanceMap}</h3>
+ * <h2>Ranges</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.ImmutableClassToInstanceMap}
- * <li>{@link com.google.common.collect.MutableClassToInstanceMap}
+ * <li>{@link Range}
+ * <li>{@link RangeMap}
+ * <li>{@link RangeSet}
+ * <li>{@link DiscreteDomain}
+ * <li>{@link ContiguousSet}
* </ul>
*
* <h2>Classes of static utility methods</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.Collections2}
- * <li>{@link com.google.common.collect.Iterators}
- * <li>{@link com.google.common.collect.Iterables}
- * <li>{@link com.google.common.collect.Lists}
- * <li>{@link com.google.common.collect.Maps}
- * <li>{@link com.google.common.collect.Queues}
- * <li>{@link com.google.common.collect.Sets}
- * <li>{@link com.google.common.collect.Multisets}
- * <li>{@link com.google.common.collect.Multimaps}
- * <li>{@link com.google.common.collect.Tables}
- * <li>{@link com.google.common.collect.ObjectArrays}
- * </ul>
- *
- * <h2>Comparison</h2>
- *
- * <ul>
- * <li>{@link com.google.common.collect.Ordering}
- * <li>{@link com.google.common.collect.ComparisonChain}
+ * <li>{@link Collections2}
+ * <li>{@link Comparators}
+ * <li>{@link Iterables}
+ * <li>{@link Iterators}
+ * <li>{@link Lists}
+ * <li>{@link Maps}
+ * <li>{@link MoreCollectors}
+ * <li>{@link Multimaps}
+ * <li>{@link Multisets}
+ * <li>{@link ObjectArrays}
+ * <li>{@link Queues}
+ * <li>{@link Sets}
+ * <li>{@link Streams}
+ * <li>{@link Tables}
* </ul>
*
* <h2>Abstract implementations</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.AbstractIterator}
- * <li>{@link com.google.common.collect.AbstractSequentialIterator}
- * <li>{@link com.google.common.collect.ImmutableCollection}
- * <li>{@link com.google.common.collect.UnmodifiableIterator}
- * <li>{@link com.google.common.collect.UnmodifiableListIterator}
+ * <li>{@link AbstractIterator}
+ * <li>{@link AbstractSequentialIterator}
+ * <li>{@link UnmodifiableIterator}
+ * <li>{@link UnmodifiableListIterator}
* </ul>
*
- * <h2>Ranges</h2>
+ * <h2>Forwarding collections</h2>
*
- * <ul>
- * <li>{@link com.google.common.collect.Range}
- * <li>{@link com.google.common.collect.RangeMap}
- * <li>{@link com.google.common.collect.DiscreteDomain}
- * <li>{@link com.google.common.collect.ContiguousSet}
- * </ul>
+ * We provide implementations of collections that forward all method calls to a delegate collection
+ * by default. Subclasses can override one or more methods to implement the decorator pattern. For
+ * an example, see {@link ForwardingCollection}.
*
* <h2>Other</h2>
*
* <ul>
- * <li>{@link com.google.common.collect.Interner}, {@link com.google.common.collect.Interners}
- * <li>{@link com.google.common.collect.MapDifference}, {@link
- * com.google.common.collect.SortedMapDifference}
- * <li>{@link com.google.common.collect.MinMaxPriorityQueue}
- * <li>{@link com.google.common.collect.PeekingIterator}
- * </ul>
- *
- * <h2>Forwarding collections</h2>
- *
- * <ul>
- * <li>{@link com.google.common.collect.ForwardingCollection}
- * <li>{@link com.google.common.collect.ForwardingConcurrentMap}
- * <li>{@link com.google.common.collect.ForwardingIterator}
- * <li>{@link com.google.common.collect.ForwardingList}
- * <li>{@link com.google.common.collect.ForwardingListIterator}
- * <li>{@link com.google.common.collect.ForwardingListMultimap}
- * <li>{@link com.google.common.collect.ForwardingMap}
- * <li>{@link com.google.common.collect.ForwardingMapEntry}
- * <li>{@link com.google.common.collect.ForwardingMultimap}
- * <li>{@link com.google.common.collect.ForwardingMultiset}
- * <li>{@link com.google.common.collect.ForwardingNavigableMap}
- * <li>{@link com.google.common.collect.ForwardingNavigableSet}
- * <li>{@link com.google.common.collect.ForwardingObject}
- * <li>{@link com.google.common.collect.ForwardingQueue}
- * <li>{@link com.google.common.collect.ForwardingSet}
- * <li>{@link com.google.common.collect.ForwardingSetMultimap}
- * <li>{@link com.google.common.collect.ForwardingSortedMap}
- * <li>{@link com.google.common.collect.ForwardingSortedMultiset}
- * <li>{@link com.google.common.collect.ForwardingSortedSet}
- * <li>{@link com.google.common.collect.ForwardingSortedSetMultimap}
- * <li>{@link com.google.common.collect.ForwardingTable}
+ * <li>{@link EvictingQueue}
+ * <li>{@link Interner}, {@link Interners}
+ * <li>{@link MapMaker}
+ * <li>{@link MinMaxPriorityQueue}
+ * <li>{@link PeekingIterator}
* </ul>
*/
@CheckReturnValue
diff --git a/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java b/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
index 355faaa10..81badfb08 100644
--- a/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
+++ b/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
@@ -128,7 +128,7 @@ public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper {
this.safeMinChar = Character.MAX_VALUE;
this.safeMaxChar = 0;
} else {
- // The safe range is non empty and contains values below the surrogate
+ // The safe range is non-empty and contains values below the surrogate
// range but may extend above it. We may need to clip the maximum value.
this.safeMinChar = (char) safeMin;
this.safeMaxChar = (char) Math.min(safeMax, Character.MIN_HIGH_SURROGATE - 1);
diff --git a/guava/src/com/google/common/escape/Escapers.java b/guava/src/com/google/common/escape/Escapers.java
index acfb82ce2..b7dcfa6b3 100644
--- a/guava/src/com/google/common/escape/Escapers.java
+++ b/guava/src/com/google/common/escape/Escapers.java
@@ -186,7 +186,7 @@ public final class Escapers {
return wrap((CharEscaper) escaper);
}
// In practice this shouldn't happen because it would be very odd not to
- // extend either CharEscaper or UnicodeEscaper for non trivial cases.
+ // extend either CharEscaper or UnicodeEscaper for non-trivial cases.
throw new IllegalArgumentException(
"Cannot create a UnicodeEscaper from: " + escaper.getClass().getName());
}
diff --git a/guava/src/com/google/common/escape/ParametricNullness.java b/guava/src/com/google/common/escape/ParametricNullness.java
index d9412065f..f964ca4a4 100644
--- a/guava/src/com/google/common/escape/ParametricNullness.java
+++ b/guava/src/com/google/common/escape/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/escape/package-info.java b/guava/src/com/google/common/escape/package-info.java
index 8cd29e6f8..4c525386e 100644
--- a/guava/src/com/google/common/escape/package-info.java
+++ b/guava/src/com/google/common/escape/package-info.java
@@ -14,14 +14,14 @@
/**
* Interfaces, utilities, and simple implementations of escapers and encoders. The primary type is
- * {@link com.google.common.escape.Escaper}.
+ * {@link Escaper}.
*
* <p>Additional escapers implementations are found in the applicable packages: {@link
* com.google.common.html.HtmlEscapers} in {@code com.google.common.html}, {@link
* com.google.common.xml.XmlEscapers} in {@code com.google.common.xml}, and {@link
* com.google.common.net.UrlEscapers} in {@code com.google.common.net}.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/guava/src/com/google/common/eventbus/Dispatcher.java b/guava/src/com/google/common/eventbus/Dispatcher.java
index ff1ae2a19..412bb789e 100644
--- a/guava/src/com/google/common/eventbus/Dispatcher.java
+++ b/guava/src/com/google/common/eventbus/Dispatcher.java
@@ -133,7 +133,7 @@ abstract class Dispatcher {
// This dispatcher matches the original dispatch behavior of AsyncEventBus.
//
// We can't really make any guarantees about the overall dispatch order for this dispatcher in
- // a multithreaded environment for a couple reasons:
+ // a multithreaded environment for a couple of reasons:
//
// 1. Subscribers to events posted on different threads can be interleaved with each other
// freely. (A event on one thread, B event on another could yield any of
diff --git a/guava/src/com/google/common/eventbus/EventBus.java b/guava/src/com/google/common/eventbus/EventBus.java
index 4afc19775..a087b3799 100644
--- a/guava/src/com/google/common/eventbus/EventBus.java
+++ b/guava/src/com/google/common/eventbus/EventBus.java
@@ -27,6 +27,7 @@ import java.util.logging.Logger;
/**
* Dispatches events to listeners, and provides ways for listeners to register themselves.
+
*
* <h2>Avoid EventBus</h2>
*
@@ -82,6 +83,8 @@ import java.util.logging.Logger;
* to <a href="https://github.com/google/guava/issues/3311">more verbose</a>.
* </ul>
*
+
+ *
* <h2>EventBus Summary</h2>
*
* <p>The EventBus allows publish-subscribe-style communication between components without requiring
diff --git a/guava/src/com/google/common/eventbus/ParametricNullness.java b/guava/src/com/google/common/eventbus/ParametricNullness.java
index ac91392f7..47c7d8d4d 100644
--- a/guava/src/com/google/common/eventbus/ParametricNullness.java
+++ b/guava/src/com/google/common/eventbus/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/eventbus/package-info.java b/guava/src/com/google/common/eventbus/package-info.java
index fa7faa4ab..bd675415c 100644
--- a/guava/src/com/google/common/eventbus/package-info.java
+++ b/guava/src/com/google/common/eventbus/package-info.java
@@ -13,241 +13,11 @@
*/
/**
- * The EventBus allows publish-subscribe-style communication between components without requiring
- * the components to explicitly register with one another (and thus be aware of each other). It is
- * designed exclusively to replace traditional Java in-process event distribution using explicit
- * registration. It is <em>not</em> a general-purpose publish-subscribe system, nor is it intended
- * for interprocess communication.
+ * <a href="https://guava.dev/EventBus">Discouraged</a> in favor of dependency injection and
+ * concurrency frameworks, EventBus allows publish-subscribe-style communication.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/EventBusExplained">{@code EventBus}</a>.
- *
- * <h2>One-Minute Guide</h2>
- *
- * <p>Converting an existing EventListener-based system to use the EventBus is easy.
- *
- * <h3>For Listeners</h3>
- *
- * <p>To listen for a specific flavor of event (say, a CustomerChangeEvent)...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> implement an interface defined with the
- * event &mdash; such as CustomerChangeEventListener.
- * <li><strong>...with EventBus:</strong> create a method that accepts CustomerChangeEvent as its
- * sole argument, and mark it with the {@link com.google.common.eventbus.Subscribe}
- * annotation.
- * </ul>
- *
- * <p>To register your listener methods with the event producers...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> pass your object to each producer's {@code
- * registerCustomerChangeEventListener} method. These methods are rarely defined in common
- * interfaces, so in addition to knowing every possible producer, you must also know its type.
- * <li><strong>...with EventBus:</strong> pass your object to the {@link
- * com.google.common.eventbus.EventBus#register(Object)} method on an EventBus. You'll need to
- * make sure that your object shares an EventBus instance with the event producers.
- * </ul>
- *
- * <p>To listen for a common event supertype (such as EventObject or Object)...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> not easy.
- * <li><strong>...with EventBus:</strong> events are automatically dispatched to listeners of any
- * supertype, allowing listeners for interface types or "wildcard listeners" for Object.
- * </ul>
- *
- * <p>To listen for and detect events that were dispatched without listeners...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> add code to each event-dispatching method
- * (perhaps using AOP).
- * <li><strong>...with EventBus:</strong> subscribe to {@link
- * com.google.common.eventbus.DeadEvent}. The EventBus will notify you of any events that were
- * posted but not delivered. (Handy for debugging.)
- * </ul>
- *
- * <h3>For Producers</h3>
- *
- * <p>To keep track of listeners to your events...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> write code to manage a list of listeners to
- * your object, including synchronization, or use a utility class like EventListenerList.
- * <li><strong>...with EventBus:</strong> EventBus does this for you.
- * </ul>
- *
- * <p>To dispatch an event to listeners...
- *
- * <ul>
- * <li><strong>...in traditional Java events:</strong> write a method to dispatch events to each
- * event listener, including error isolation and (if desired) asynchronicity.
- * <li><strong>...with EventBus:</strong> pass the event object to an EventBus's {@link
- * com.google.common.eventbus.EventBus#post(Object)} method.
- * </ul>
- *
- * <h2>Glossary</h2>
- *
- * <p>The EventBus system and code use the following terms to discuss event distribution:
- *
- * <dl>
- * <dt>Event
- * <dd>Any object that may be <em>posted</em> to a bus.
- * <dt>Subscribing
- * <dd>The act of registering a <em>listener</em> with an EventBus, so that its <em>subscriber
- * methods</em> will receive events.
- * <dt>Listener
- * <dd>An object that wishes to receive events, by exposing <em>subscriber methods</em>.
- * <dt>Subscriber method
- * <dd>A public method that the EventBus should use to deliver <em>posted</em> events. Subscriber
- * methods are marked by the {@link com.google.common.eventbus.Subscribe} annotation.
- * <dt>Posting an event
- * <dd>Making the event available to any <em>listeners</em> through the EventBus.
- * </dl>
- *
- * <h2>FAQ</h2>
- *
- * <h3>Why must I create my own Event Bus, rather than using a singleton?</h3>
- *
- * <p>The Event Bus doesn't specify how you use it; there's nothing stopping your application from
- * having separate EventBus instances for each component, or using separate instances to separate
- * events by context or topic. This also makes it trivial to set up and tear down EventBus objects
- * in your tests.
- *
- * <p>Of course, if you'd like to have a process-wide EventBus singleton, there's nothing stopping
- * you from doing it that way. Simply have your container (such as Guice) create the EventBus as a
- * singleton at global scope (or stash it in a static field, if you're into that sort of thing).
- *
- * <p>In short, the EventBus is not a singleton because we'd rather not make that decision for you.
- * Use it how you like.
- *
- * <h3>Why use an annotation to mark subscriber methods, rather than requiring the listener to
- * implement an interface?</h3>
- *
- * <p>We feel that the Event Bus's {@code @Subscribe} annotation conveys your intentions just as
- * explicitly as implementing an interface (or perhaps more so), while leaving you free to place
- * event subscriber methods wherever you wish and give them intention-revealing names.
- *
- * <p>Traditional Java Events use a listener interface which typically sports only a handful of
- * methods -- typically one. This has a number of disadvantages:
- *
- * <ul>
- * <li>Any one class can only implement a single response to a given event.
- * <li>Listener interface methods may conflict.
- * <li>The method must be named after the event (e.g. {@code handleChangeEvent}), rather than its
- * purpose (e.g. {@code recordChangeInJournal}).
- * <li>Each event usually has its own interface, without a common parent interface for a family of
- * events (e.g. all UI events).
- * </ul>
- *
- * <p>The difficulties in implementing this cleanly has given rise to a pattern, particularly common
- * in Swing apps, of using tiny anonymous classes to implement event listener interfaces.
- *
- * <p>Compare these two cases:
- *
- * <pre>{@code
- * class ChangeRecorder {
- * void setCustomer(Customer cust) {
- * cust.addChangeListener(new ChangeListener() {
- * void customerChanged(ChangeEvent e) {
- * recordChange(e.getChange());
- * }
- * };
- * }
- * }
- *
- * // Class is typically registered by the container.
- * class EventBusChangeRecorder {
- * }{@code @Subscribe void recordCustomerChange(ChangeEvent e) {
- * recordChange(e.getChange());
- * }
- * }
- * }</pre>
- *
- * <p>The intent is actually clearer in the second case: there's less noise code, and the event
- * subscriber has a clear and meaningful name.
- *
- * <h3>What about a generic {@code Subscriber<T>} interface?</h3>
- *
- * <p>Some have proposed a generic {@code Subscriber<T>} interface for EventBus listeners. This runs
- * into issues with Java's use of type erasure, not to mention problems in usability.
- *
- * <p>Let's say the interface looked something like the following:
- *
- * <pre>{@code
- * interface Subscriber<T> {
- * void handleEvent(T event);
- * }
- * }</pre>
- *
- * <p>Due to erasure, no single class can implement a generic interface more than once with
- * different type parameters. This is a giant step backwards from traditional Java Events, where
- * even if {@code actionPerformed} and {@code keyPressed} aren't very meaningful names, at least you
- * can implement both methods!
- *
- * <h3>Doesn't EventBus destroy static typing and eliminate automated refactoring support?</h3>
- *
- * <p>Some have freaked out about EventBus's {@code register(Object)} and {@code post(Object)}
- * methods' use of the {@code Object} type.
- *
- * <p>{@code Object} is used here for a good reason: the Event Bus library places no restrictions on
- * the types of either your event listeners (as in {@code register(Object)}) or the events
- * themselves (in {@code post(Object)}).
- *
- * <p>Event subscriber methods, on the other hand, must explicitly declare their argument type --
- * the type of event desired (or one of its supertypes). Thus, searching for references to an event
- * class will instantly find all subscriber methods for that event, and renaming the type will
- * affect all subscriber methods within view of your IDE (and any code that creates the event).
- *
- * <p>It's true that you can rename your {@code @Subscribed} event subscriber methods at will; Event
- * Bus will not stop this or do anything to propagate the rename because, to Event Bus, the names of
- * your subscriber methods are irrelevant. Test code that calls the methods directly, of course,
- * will be affected by your renaming -- but that's what your refactoring tools are for.
- *
- * <h3>What happens if I {@code register} a listener without any subscriber methods?</h3>
- *
- * <p>Nothing at all.
- *
- * <p>The Event Bus was designed to integrate with containers and module systems, with Guice as the
- * prototypical example. In these cases, it's convenient to have the container/factory/environment
- * pass <i>every</i> created object to an EventBus's {@code register(Object)} method.
- *
- * <p>This way, any object created by the container/factory/environment can hook into the system's
- * event model simply by exposing subscriber methods.
- *
- * <h3>What Event Bus problems can be detected at compile time?</h3>
- *
- * <p>Any problem that can be unambiguously detected by Java's type system. For example, defining a
- * subscriber method for a nonexistent event type.
- *
- * <h3>What Event Bus problems can be detected immediately at registration?</h3>
- *
- * <p>Immediately upon invoking {@code register(Object)}, the listener being registered is checked
- * for the <i>well-formedness</i> of its subscriber methods. Specifically, any methods marked with
- * {@code @Subscribe} must take only a single argument.
- *
- * <p>Any violations of this rule will cause an {@code IllegalArgumentException} to be thrown.
- *
- * <p>(This check could be moved to compile-time using APT, a solution we're researching.)
- *
- * <h3>What Event Bus problems may only be detected later, at runtime?</h3>
- *
- * <p>If a component posts events with no registered listeners, it <i>may</i> indicate an error
- * (typically an indication that you missed a {@code @Subscribe} annotation, or that the listening
- * component is not loaded).
- *
- * <p>(Note that this is <i>not necessarily</i> indicative of a problem. There are many cases where
- * an application will deliberately ignore a posted event, particularly if the event is coming from
- * code you don't control.)
- *
- * <p>To handle such events, register a subscriber method for the {@code DeadEvent} class. Whenever
- * EventBus receives an event with no registered subscribers, it will turn it into a {@code
- * DeadEvent} and pass it your way -- allowing you to log it or otherwise recover.
- *
- * <h3>How do I test event listeners and their subscriber methods?</h3>
- *
- * <p>Because subscriber methods on your listener classes are normal methods, you can simply call
- * them from your test code to simulate the EventBus.
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
diff --git a/guava/src/com/google/common/graph/AbstractBaseGraph.java b/guava/src/com/google/common/graph/AbstractBaseGraph.java
index 797468b7a..5adcc9216 100644
--- a/guava/src/com/google/common/graph/AbstractBaseGraph.java
+++ b/guava/src/com/google/common/graph/AbstractBaseGraph.java
@@ -44,9 +44,9 @@ import javax.annotation.CheckForNull;
abstract class AbstractBaseGraph<N> implements BaseGraph<N> {
/**
- * Returns the number of edges in this graph; used to calculate the size of {@link #edges()}. This
- * implementation requires O(|N|) time. Classes extending this one may manually keep track of the
- * number of edges as the graph is updated, and override this method for better performance.
+ * Returns the number of edges in this graph; used to calculate the size of {@link Graph#edges()}.
+ * This implementation requires O(|N|) time. Classes extending this one may manually keep track of
+ * the number of edges as the graph is updated, and override this method for better performance.
*/
protected long edgeCount() {
long degreeSum = 0L;
@@ -59,8 +59,8 @@ abstract class AbstractBaseGraph<N> implements BaseGraph<N> {
}
/**
- * An implementation of {@link BaseGraph#edges()} defined in terms of {@link #nodes()} and {@link
- * #successors(Object)}.
+ * An implementation of {@link BaseGraph#edges()} defined in terms of {@link Graph#nodes()} and
+ * {@link #successors(Object)}.
*/
@Override
public Set<EndpointPair<N>> edges() {
@@ -177,7 +177,11 @@ abstract class AbstractBaseGraph<N> implements BaseGraph<N> {
checkArgument(isOrderingCompatible(endpoints), ENDPOINTS_MISMATCH);
}
+ /**
+ * Returns {@code true} iff {@code endpoints}' ordering is compatible with the directionality of
+ * this graph.
+ */
protected final boolean isOrderingCompatible(EndpointPair<?> endpoints) {
- return endpoints.isOrdered() || !this.isDirected();
+ return endpoints.isOrdered() == this.isDirected();
}
}
diff --git a/guava/src/com/google/common/graph/AbstractNetwork.java b/guava/src/com/google/common/graph/AbstractNetwork.java
index d6bf4c36c..6ad96cb06 100644
--- a/guava/src/com/google/common/graph/AbstractNetwork.java
+++ b/guava/src/com/google/common/graph/AbstractNetwork.java
@@ -23,7 +23,6 @@ import static com.google.common.graph.GraphConstants.MULTIPLE_EDGES_CONNECTING;
import static java.util.Collections.unmodifiableSet;
import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
@@ -72,13 +71,7 @@ public abstract class AbstractNetwork<N, E> implements Network<N, E> {
@Override
public Iterator<EndpointPair<N>> iterator() {
return Iterators.transform(
- AbstractNetwork.this.edges().iterator(),
- new Function<E, EndpointPair<N>>() {
- @Override
- public EndpointPair<N> apply(E edge) {
- return incidentNodes(edge);
- }
- });
+ AbstractNetwork.this.edges().iterator(), edge -> incidentNodes(edge));
}
@Override
@@ -253,7 +246,7 @@ public abstract class AbstractNetwork<N, E> implements Network<N, E> {
}
protected final boolean isOrderingCompatible(EndpointPair<?> endpoints) {
- return endpoints.isOrdered() || !this.isDirected();
+ return endpoints.isOrdered() == this.isDirected();
}
@Override
@@ -292,13 +285,6 @@ public abstract class AbstractNetwork<N, E> implements Network<N, E> {
}
private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) {
- Function<E, EndpointPair<N>> edgeToIncidentNodesFn =
- new Function<E, EndpointPair<N>>() {
- @Override
- public EndpointPair<N> apply(E edge) {
- return network.incidentNodes(edge);
- }
- };
- return Maps.asMap(network.edges(), edgeToIncidentNodesFn);
+ return Maps.asMap(network.edges(), network::incidentNodes);
}
}
diff --git a/guava/src/com/google/common/graph/AbstractValueGraph.java b/guava/src/com/google/common/graph/AbstractValueGraph.java
index 5b8e520c3..f7beaa695 100644
--- a/guava/src/com/google/common/graph/AbstractValueGraph.java
+++ b/guava/src/com/google/common/graph/AbstractValueGraph.java
@@ -19,7 +19,6 @@ package com.google.common.graph;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Optional;
@@ -152,14 +151,10 @@ public abstract class AbstractValueGraph<N, V> extends AbstractBaseGraph<N>
}
private static <N, V> Map<EndpointPair<N>, V> edgeValueMap(final ValueGraph<N, V> graph) {
- Function<EndpointPair<N>, V> edgeToValueFn =
- new Function<EndpointPair<N>, V>() {
- @Override
- public V apply(EndpointPair<N> edge) {
+ return Maps.asMap(
+ graph.edges(),
+ edge ->
// requireNonNull is safe because the endpoint pair comes from the graph.
- return requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
- }
- };
- return Maps.asMap(graph.edges(), edgeToValueFn);
+ requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null)));
}
}
diff --git a/guava/src/com/google/common/graph/GraphBuilder.java b/guava/src/com/google/common/graph/GraphBuilder.java
index 8c0871b46..e275c43a5 100644
--- a/guava/src/com/google/common/graph/GraphBuilder.java
+++ b/guava/src/com/google/common/graph/GraphBuilder.java
@@ -22,19 +22,26 @@ import static com.google.common.graph.Graphs.checkNonNegative;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
/**
* A builder for constructing instances of {@link MutableGraph} or {@link ImmutableGraph} with
* user-defined properties.
*
- * <p>A graph built by this class will have the following properties by default:
+ * <p>A {@code Graph} built by this class has the following default properties:
*
* <ul>
* <li>does not allow self-loops
- * <li>orders {@link Graph#nodes()} in the order in which the elements were added
+ * <li>orders {@link Graph#nodes()} in the order in which the elements were added (insertion
+ * order)
* </ul>
*
+ * <p>{@code Graph}s built by this class also guarantee that each collection-returning accessor
+ * returns a <b>(live) unmodifiable view</b>; see <a
+ * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
+ * documentation</a> for details.
+ *
* <p>Examples of use:
*
* <pre>{@code
@@ -118,6 +125,7 @@ public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public GraphBuilder<N> allowsSelfLoops(boolean allowsSelfLoops) {
this.allowsSelfLoops = allowsSelfLoops;
return this;
@@ -128,6 +136,7 @@ public final class GraphBuilder<N> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedNodeCount} is negative
*/
+ @CanIgnoreReturnValue
public GraphBuilder<N> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
diff --git a/guava/src/com/google/common/graph/GraphConstants.java b/guava/src/com/google/common/graph/GraphConstants.java
index ae224fdd2..4e8510662 100644
--- a/guava/src/com/google/common/graph/GraphConstants.java
+++ b/guava/src/com/google/common/graph/GraphConstants.java
@@ -52,7 +52,7 @@ final class GraphConstants {
+ "adjacentNode(node) if you already have a node, or nodeU()/nodeV() if you don't.";
static final String EDGE_ALREADY_EXISTS = "Edge %s already exists in the graph.";
static final String ENDPOINTS_MISMATCH =
- "Mismatch: unordered endpoints cannot be used with directed graphs";
+ "Mismatch: endpoints' ordering is not compatible with directionality of the graph";
/** Singleton edge value for {@link Graph} implementations backed by {@link ValueGraph}s. */
enum Presence {
diff --git a/guava/src/com/google/common/graph/Graphs.java b/guava/src/com/google/common/graph/Graphs.java
index 6ab9f5661..059bc889a 100644
--- a/guava/src/com/google/common/graph/Graphs.java
+++ b/guava/src/com/google/common/graph/Graphs.java
@@ -21,7 +21,6 @@ import static com.google.common.graph.GraphConstants.NODE_NOT_IN_GRAPH;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@@ -289,12 +288,7 @@ public final class Graphs {
public Iterator<EndpointPair<N>> iterator() {
return Iterators.transform(
delegate().incidentEdges(node).iterator(),
- new Function<EndpointPair<N>, EndpointPair<N>>() {
- @Override
- public EndpointPair<N> apply(EndpointPair<N> edge) {
- return EndpointPair.of(delegate(), edge.nodeV(), edge.nodeU());
- }
- });
+ edge -> EndpointPair.of(delegate(), edge.nodeV(), edge.nodeU()));
}
};
}
diff --git a/guava/src/com/google/common/graph/Network.java b/guava/src/com/google/common/graph/Network.java
index c700d3378..eb9e313e5 100644
--- a/guava/src/com/google/common/graph/Network.java
+++ b/guava/src/com/google/common/graph/Network.java
@@ -283,9 +283,10 @@ public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFuncti
*
* <p>In an undirected network, this is equal to {@code edgesConnecting(nodeV, nodeU)}.
*
- * <p>The resulting set of edges will be parallel (i.e. have equal {@link #incidentNodes(Object)}.
- * If this network does not {@link #allowsParallelEdges() allow parallel edges}, the resulting set
- * will contain at most one edge (equivalent to {@code edgeConnecting(nodeU, nodeV).asSet()}).
+ * <p>The resulting set of edges will be parallel (i.e. have equal {@link
+ * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
+ * edges}, the resulting set will contain at most one edge (equivalent to {@code
+ * edgeConnecting(nodeU, nodeV).asSet()}).
*
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* network
@@ -296,9 +297,10 @@ public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFuncti
* Returns the set of edges that each directly connect {@code endpoints} (in the order, if any,
* specified by {@code endpoints}).
*
- * <p>The resulting set of edges will be parallel (i.e. have equal {@link #incidentNodes(Object)}.
- * If this network does not {@link #allowsParallelEdges() allow parallel edges}, the resulting set
- * will contain at most one edge (equivalent to {@code edgeConnecting(endpoints).asSet()}).
+ * <p>The resulting set of edges will be parallel (i.e. have equal {@link
+ * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
+ * edges}, the resulting set will contain at most one edge (equivalent to {@code
+ * edgeConnecting(endpoints).asSet()}).
*
* <p>If this network is directed, {@code endpoints} must be ordered.
*
diff --git a/guava/src/com/google/common/graph/NetworkBuilder.java b/guava/src/com/google/common/graph/NetworkBuilder.java
index 968944493..c1f37147b 100644
--- a/guava/src/com/google/common/graph/NetworkBuilder.java
+++ b/guava/src/com/google/common/graph/NetworkBuilder.java
@@ -21,20 +21,26 @@ import static com.google.common.graph.Graphs.checkNonNegative;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
/**
* A builder for constructing instances of {@link MutableNetwork} or {@link ImmutableNetwork} with
* user-defined properties.
*
- * <p>A network built by this class will have the following properties by default:
+ * <p>A {@code Network} built by this class has the following default properties:
*
* <ul>
* <li>does not allow parallel edges
* <li>does not allow self-loops
* <li>orders {@link Network#nodes()} and {@link Network#edges()} in the order in which the
- * elements were added
+ * elements were added (insertion order)
* </ul>
*
+ * <p>{@code Network}s built by this class also guarantee that each collection-returning accessor
+ * returns a <b>(live) unmodifiable view</b>; see <a
+ * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
+ * documentation</a> for details.
+ *
* <p>Examples of use:
*
* <pre>{@code
@@ -122,6 +128,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> allowsParallelEdges(boolean allowsParallelEdges) {
this.allowsParallelEdges = allowsParallelEdges;
return this;
@@ -134,6 +141,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> allowsSelfLoops(boolean allowsSelfLoops) {
this.allowsSelfLoops = allowsSelfLoops;
return this;
@@ -144,6 +152,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedNodeCount} is negative
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
@@ -154,6 +163,7 @@ public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedEdgeCount} is negative
*/
+ @CanIgnoreReturnValue
public NetworkBuilder<N, E> expectedEdgeCount(int expectedEdgeCount) {
this.expectedEdgeCount = Optional.of(checkNonNegative(expectedEdgeCount));
return this;
diff --git a/guava/src/com/google/common/graph/ParametricNullness.java b/guava/src/com/google/common/graph/ParametricNullness.java
index 87ff930a4..32fd5ee7e 100644
--- a/guava/src/com/google/common/graph/ParametricNullness.java
+++ b/guava/src/com/google/common/graph/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/graph/Traverser.java b/guava/src/com/google/common/graph/Traverser.java
index fb594b440..4ab4585f7 100644
--- a/guava/src/com/google/common/graph/Traverser.java
+++ b/guava/src/com/google/common/graph/Traverser.java
@@ -396,7 +396,7 @@ public abstract class Traverser<N> {
* requireNonNull(top.next())`) once our checker supports it.
*
* (The problem is likely
- * https://github.com/jspecify/nullness-checker-for-checker-framework/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecAnnotatedTypeFactory.java#L896)
+ * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecAnnotatedTypeFactory.java#L896)
*/
requireNonNull(element);
if (visited.add(element)) {
diff --git a/guava/src/com/google/common/graph/ValueGraphBuilder.java b/guava/src/com/google/common/graph/ValueGraphBuilder.java
index ce146c325..a4014606d 100644
--- a/guava/src/com/google/common/graph/ValueGraphBuilder.java
+++ b/guava/src/com/google/common/graph/ValueGraphBuilder.java
@@ -22,18 +22,25 @@ import static com.google.common.graph.Graphs.checkNonNegative;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
/**
* A builder for constructing instances of {@link MutableValueGraph} or {@link ImmutableValueGraph}
* with user-defined properties.
*
- * <p>A graph built by this class will have the following properties by default:
+ * <p>A {@code ValueGraph} built by this class has the following default properties:
*
* <ul>
* <li>does not allow self-loops
- * <li>orders {@link Graph#nodes()} in the order in which the elements were added
+ * <li>orders {@link ValueGraph#nodes()} in the order in which the elements were added (insertion
+ * order)
* </ul>
*
+ * <p>{@code ValueGraph}s built by this class also guarantee that each collection-returning accessor
+ * returns a <b>(live) unmodifiable view</b>; see <a
+ * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
+ * documentation</a> for details.
+ *
* <p>Examples of use:
*
* <pre>{@code
@@ -122,6 +129,7 @@ public final class ValueGraphBuilder<N, V> extends AbstractGraphBuilder<N> {
*
* <p>The default value is {@code false}.
*/
+ @CanIgnoreReturnValue
public ValueGraphBuilder<N, V> allowsSelfLoops(boolean allowsSelfLoops) {
this.allowsSelfLoops = allowsSelfLoops;
return this;
@@ -132,6 +140,7 @@ public final class ValueGraphBuilder<N, V> extends AbstractGraphBuilder<N> {
*
* @throws IllegalArgumentException if {@code expectedNodeCount} is negative
*/
+ @CanIgnoreReturnValue
public ValueGraphBuilder<N, V> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
diff --git a/guava/src/com/google/common/hash/AbstractByteHasher.java b/guava/src/com/google/common/hash/AbstractByteHasher.java
index 9f7e04190..2c8682575 100644
--- a/guava/src/com/google/common/hash/AbstractByteHasher.java
+++ b/guava/src/com/google/common/hash/AbstractByteHasher.java
@@ -31,7 +31,6 @@ import java.nio.ByteOrder;
*
* @author Colin Decker
*/
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
abstract class AbstractByteHasher extends AbstractHasher {
private final ByteBuffer scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
@@ -64,6 +63,7 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
/** Updates the sink with the given number of bytes from the buffer. */
+ @CanIgnoreReturnValue
private Hasher update(int bytes) {
try {
update(scratch.array(), 0, bytes);
@@ -74,12 +74,14 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putByte(byte b) {
update(b);
return this;
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes) {
checkNotNull(bytes);
update(bytes);
@@ -87,6 +89,7 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
update(bytes, off, len);
@@ -94,30 +97,35 @@ abstract class AbstractByteHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(ByteBuffer bytes) {
update(bytes);
return this;
}
@Override
+ @CanIgnoreReturnValue
public Hasher putShort(short s) {
scratch.putShort(s);
return update(Shorts.BYTES);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putInt(int i) {
scratch.putInt(i);
return update(Ints.BYTES);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putLong(long l) {
scratch.putLong(l);
return update(Longs.BYTES);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putChar(char c) {
scratch.putChar(c);
return update(Chars.BYTES);
diff --git a/guava/src/com/google/common/hash/AbstractHasher.java b/guava/src/com/google/common/hash/AbstractHasher.java
index c72e05be0..905a425c9 100644
--- a/guava/src/com/google/common/hash/AbstractHasher.java
+++ b/guava/src/com/google/common/hash/AbstractHasher.java
@@ -26,25 +26,28 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Dimitris Andreou
*/
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
abstract class AbstractHasher implements Hasher {
@Override
+ @CanIgnoreReturnValue
public final Hasher putBoolean(boolean b) {
return putByte(b ? (byte) 1 : (byte) 0);
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putDouble(double d) {
return putLong(Double.doubleToRawLongBits(d));
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putFloat(float f) {
return putInt(Float.floatToRawIntBits(f));
}
@Override
+ @CanIgnoreReturnValue
public Hasher putUnencodedChars(CharSequence charSequence) {
for (int i = 0, len = charSequence.length(); i < len; i++) {
putChar(charSequence.charAt(i));
@@ -53,16 +56,19 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putString(CharSequence charSequence, Charset charset) {
return putBytes(charSequence.toString().getBytes(charset));
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes) {
return putBytes(bytes, 0, bytes.length);
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(byte[] bytes, int off, int len) {
Preconditions.checkPositionIndexes(off, off + len, bytes.length);
for (int i = 0; i < len; i++) {
@@ -72,6 +78,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putBytes(ByteBuffer b) {
if (b.hasArray()) {
putBytes(b.array(), b.arrayOffset() + b.position(), b.remaining());
@@ -85,6 +92,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putShort(short s) {
putByte((byte) s);
putByte((byte) (s >>> 8));
@@ -92,6 +100,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putInt(int i) {
putByte((byte) i);
putByte((byte) (i >>> 8));
@@ -101,6 +110,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putLong(long l) {
for (int i = 0; i < 64; i += 8) {
putByte((byte) (l >>> i));
@@ -109,6 +119,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public Hasher putChar(char c) {
putByte((byte) c);
putByte((byte) (c >>> 8));
@@ -116,6 +127,7 @@ abstract class AbstractHasher implements Hasher {
}
@Override
+ @CanIgnoreReturnValue
public <T extends @Nullable Object> Hasher putObject(
@ParametricNullness T instance, Funnel<? super T> funnel) {
funnel.funnel(instance, this);
diff --git a/guava/src/com/google/common/hash/AbstractStreamingHasher.java b/guava/src/com/google/common/hash/AbstractStreamingHasher.java
index a987b48c3..875bc6ec4 100644
--- a/guava/src/com/google/common/hash/AbstractStreamingHasher.java
+++ b/guava/src/com/google/common/hash/AbstractStreamingHasher.java
@@ -28,7 +28,6 @@ import java.nio.ByteOrder;
* @author Dimitris Andreou
*/
// TODO(kevinb): this class still needs some design-and-document-for-inheritance love
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
abstract class AbstractStreamingHasher extends AbstractHasher {
/** Buffer via which we pass data to the hash algorithm (the implementor) */
@@ -92,11 +91,13 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putBytes(byte[] bytes, int off, int len) {
return putBytesInternal(ByteBuffer.wrap(bytes, off, len).order(ByteOrder.LITTLE_ENDIAN));
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putBytes(ByteBuffer readBuffer) {
ByteOrder order = readBuffer.order();
try {
@@ -107,6 +108,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
}
+ @CanIgnoreReturnValue
private Hasher putBytesInternal(ByteBuffer readBuffer) {
// If we have room for all of it, this is easy
if (readBuffer.remaining() <= buffer.remaining()) {
@@ -143,6 +145,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
*/
@Override
+ @CanIgnoreReturnValue
public final Hasher putByte(byte b) {
buffer.put(b);
munchIfFull();
@@ -150,6 +153,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putShort(short s) {
buffer.putShort(s);
munchIfFull();
@@ -157,6 +161,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putChar(char c) {
buffer.putChar(c);
munchIfFull();
@@ -164,6 +169,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putInt(int i) {
buffer.putInt(i);
munchIfFull();
@@ -171,6 +177,7 @@ abstract class AbstractStreamingHasher extends AbstractHasher {
}
@Override
+ @CanIgnoreReturnValue
public final Hasher putLong(long l) {
buffer.putLong(l);
munchIfFull();
diff --git a/guava/src/com/google/common/hash/BloomFilter.java b/guava/src/com/google/common/hash/BloomFilter.java
index 889ab5049..3f1079ee8 100644
--- a/guava/src/com/google/common/hash/BloomFilter.java
+++ b/guava/src/com/google/common/hash/BloomFilter.java
@@ -31,6 +31,8 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.RoundingMode;
@@ -538,6 +540,10 @@ public final class BloomFilter<T extends @Nullable Object> implements Predicate<
return new SerialForm<T>(this);
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static class SerialForm<T extends @Nullable Object> implements Serializable {
final long[] data;
final int numHashFunctions;
diff --git a/guava/src/com/google/common/hash/BloomFilterStrategies.java b/guava/src/com/google/common/hash/BloomFilterStrategies.java
index 876269e9c..7c5650b2d 100644
--- a/guava/src/com/google/common/hash/BloomFilterStrategies.java
+++ b/guava/src/com/google/common/hash/BloomFilterStrategies.java
@@ -94,7 +94,7 @@ enum BloomFilterStrategies implements BloomFilter.Strategy {
},
/**
* This strategy uses all 128 bits of {@link Hashing#murmur3_128} when hashing. It looks different
- * than the implementation in MURMUR128_MITZ_32 because we're avoiding the multiplication in the
+ * from the implementation in MURMUR128_MITZ_32 because we're avoiding the multiplication in the
* loop and doing a (much simpler) += hash2. We're also changing the index to a positive number by
* AND'ing with Long.MAX_VALUE instead of flipping the bits.
*/
diff --git a/guava/src/com/google/common/hash/FarmHashFingerprint64.java b/guava/src/com/google/common/hash/FarmHashFingerprint64.java
index 3437b00a2..329a981c4 100644
--- a/guava/src/com/google/common/hash/FarmHashFingerprint64.java
+++ b/guava/src/com/google/common/hash/FarmHashFingerprint64.java
@@ -117,7 +117,7 @@ final class FarmHashFingerprint64 extends AbstractNonStreamingHashFunction {
private static long hashLength0to16(byte[] bytes, int offset, int length) {
if (length >= 8) {
- long mul = K2 + length * 2;
+ long mul = K2 + length * 2L;
long a = load64(bytes, offset) + K2;
long b = load64(bytes, offset + length - 8);
long c = rotateRight(b, 37) * mul + a;
@@ -141,7 +141,7 @@ final class FarmHashFingerprint64 extends AbstractNonStreamingHashFunction {
}
private static long hashLength17to32(byte[] bytes, int offset, int length) {
- long mul = K2 + length * 2;
+ long mul = K2 + length * 2L;
long a = load64(bytes, offset) * K1;
long b = load64(bytes, offset + 8);
long c = load64(bytes, offset + length - 8) * mul;
@@ -151,7 +151,7 @@ final class FarmHashFingerprint64 extends AbstractNonStreamingHashFunction {
}
private static long hashLength33To64(byte[] bytes, int offset, int length) {
- long mul = K2 + length * 2;
+ long mul = K2 + length * 2L;
long a = load64(bytes, offset) * K2;
long b = load64(bytes, offset + 8);
long c = load64(bytes, offset + length - 8) * mul;
diff --git a/guava/src/com/google/common/hash/Funnels.java b/guava/src/com/google/common/hash/Funnels.java
index b8e63d504..1d1d0a499 100644
--- a/guava/src/com/google/common/hash/Funnels.java
+++ b/guava/src/com/google/common/hash/Funnels.java
@@ -16,6 +16,8 @@ package com.google.common.hash;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
@@ -122,6 +124,10 @@ public final class Funnels {
return new SerializedForm(charset);
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
private static class SerializedForm implements Serializable {
private final String charsetCanonicalName;
diff --git a/guava/src/com/google/common/hash/Hasher.java b/guava/src/com/google/common/hash/Hasher.java
index b3f24fa28..f9a74c046 100644
--- a/guava/src/com/google/common/hash/Hasher.java
+++ b/guava/src/com/google/common/hash/Hasher.java
@@ -54,42 +54,52 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 11.0
*/
@Beta
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
public interface Hasher extends PrimitiveSink {
+ @CanIgnoreReturnValue
@Override
Hasher putByte(byte b);
+ @CanIgnoreReturnValue
@Override
Hasher putBytes(byte[] bytes);
+ @CanIgnoreReturnValue
@Override
Hasher putBytes(byte[] bytes, int off, int len);
+ @CanIgnoreReturnValue
@Override
Hasher putBytes(ByteBuffer bytes);
+ @CanIgnoreReturnValue
@Override
Hasher putShort(short s);
+ @CanIgnoreReturnValue
@Override
Hasher putInt(int i);
+ @CanIgnoreReturnValue
@Override
Hasher putLong(long l);
/** Equivalent to {@code putInt(Float.floatToRawIntBits(f))}. */
+ @CanIgnoreReturnValue
@Override
Hasher putFloat(float f);
/** Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}. */
+ @CanIgnoreReturnValue
@Override
Hasher putDouble(double d);
/** Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}. */
+ @CanIgnoreReturnValue
@Override
Hasher putBoolean(boolean b);
+ @CanIgnoreReturnValue
@Override
Hasher putChar(char c);
@@ -106,6 +116,7 @@ public interface Hasher extends PrimitiveSink {
*
* @since 15.0 (since 11.0 as putString(CharSequence)).
*/
+ @CanIgnoreReturnValue
@Override
Hasher putUnencodedChars(CharSequence charSequence);
@@ -117,10 +128,12 @@ public interface Hasher extends PrimitiveSink {
* faster, produces the same output across Java releases, and hashes every {@code char} in the
* input, even if some are invalid.
*/
+ @CanIgnoreReturnValue
@Override
Hasher putString(CharSequence charSequence, Charset charset);
/** A simple convenience for {@code funnel.funnel(object, this)}. */
+ @CanIgnoreReturnValue
<T extends @Nullable Object> Hasher putObject(
@ParametricNullness T instance, Funnel<? super T> funnel);
diff --git a/guava/src/com/google/common/hash/Hashing.java b/guava/src/com/google/common/hash/Hashing.java
index afff20c74..f2ec72f38 100644
--- a/guava/src/com/google/common/hash/Hashing.java
+++ b/guava/src/com/google/common/hash/Hashing.java
@@ -16,8 +16,13 @@ package com.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Throwables.throwIfUnchecked;
+import static java.lang.invoke.MethodType.methodType;
import com.google.errorprone.annotations.Immutable;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
import java.security.Key;
import java.util.ArrayList;
import java.util.Arrays;
@@ -57,7 +62,8 @@ public final class Hashing {
* <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value
* for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances.
*
- * @param minimumBits a positive integer (can be arbitrarily large)
+ * @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link
+ * HashFunction} instance may use memory proportional to this integer.
* @return a hash function, described above, that produces hash codes of length {@code
* minimumBits} or greater
*/
@@ -373,9 +379,13 @@ public final class Hashing {
}
private static String hmacToString(String methodName, Key key) {
- return String.format(
- "Hashing.%s(Key[algorithm=%s, format=%s])",
- methodName, key.getAlgorithm(), key.getFormat());
+ return "Hashing."
+ + methodName
+ + "(Key[algorithm="
+ + key.getAlgorithm()
+ + ", format="
+ + key.getFormat()
+ + "])";
}
/**
@@ -389,7 +399,45 @@ public final class Hashing {
* @since 18.0
*/
public static HashFunction crc32c() {
- return Crc32cHashFunction.CRC_32_C;
+ return Crc32CSupplier.HASH_FUNCTION;
+ }
+
+ @Immutable
+ private enum Crc32CSupplier implements ImmutableSupplier<HashFunction> {
+ @J2ObjCIncompatible
+ JAVA_UTIL_ZIP {
+ @Override
+ public HashFunction get() {
+ return ChecksumType.CRC_32C.hashFunction;
+ }
+ },
+ ABSTRACT_HASH_FUNCTION {
+ @Override
+ public HashFunction get() {
+ return Crc32cHashFunction.CRC_32_C;
+ }
+ };
+
+ static final HashFunction HASH_FUNCTION = pickFunction().get();
+
+ private static Crc32CSupplier pickFunction() {
+ Crc32CSupplier[] functions = values();
+
+ if (functions.length == 1) {
+ // We're running under J2ObjC.
+ return functions[0];
+ }
+
+ // We can't refer to JAVA_UTIL_ZIP directly at compile time because of J2ObjC.
+ Crc32CSupplier javaUtilZip = functions[0];
+
+ try {
+ Class.forName("java.util.zip.CRC32C");
+ return javaUtilZip;
+ } catch (ClassNotFoundException runningUnderJava8) {
+ return ABSTRACT_HASH_FUNCTION;
+ }
+ }
}
/**
@@ -432,6 +480,13 @@ public final class Hashing {
return new CRC32();
}
},
+ @J2ObjCIncompatible
+ CRC_32C("Hashing.crc32c()") {
+ @Override
+ public Checksum get() {
+ return Crc32cMethodHandles.newCrc32c();
+ }
+ },
ADLER_32("Hashing.adler32()") {
@Override
public Checksum get() {
@@ -446,6 +501,52 @@ public final class Hashing {
}
}
+ @J2ObjCIncompatible
+ @SuppressWarnings("unused")
+ private static final class Crc32cMethodHandles {
+ private static final MethodHandle CONSTRUCTOR = crc32cConstructor();
+
+ @IgnoreJRERequirement // https://github.com/mojohaus/animal-sniffer/issues/67
+ static Checksum newCrc32c() {
+ try {
+ return (Checksum) CONSTRUCTOR.invokeExact();
+ } catch (Throwable e) {
+ throwIfUnchecked(e);
+ // That constructor has no `throws` clause.
+ throw newLinkageError(e);
+ }
+ }
+
+ private static MethodHandle crc32cConstructor() {
+ try {
+ Class<?> clazz = Class.forName("java.util.zip.CRC32C");
+ /*
+ * We can't cast to CRC32C at the call site because we support building with Java 8
+ * (https://github.com/google/guava/issues/6549). So we have to use asType() to change from
+ * CRC32C to Checksum. This may carry some performance cost
+ * (https://stackoverflow.com/a/22321671/28465), but I'd have to benchmark more carefully to
+ * even detect it.
+ */
+ return MethodHandles.lookup()
+ .findConstructor(clazz, methodType(void.class))
+ .asType(methodType(Checksum.class));
+ } catch (ClassNotFoundException e) {
+ // We check that the class is available before calling this method.
+ throw new AssertionError(e);
+ } catch (IllegalAccessException e) {
+ // That API is public.
+ throw newLinkageError(e);
+ } catch (NoSuchMethodException e) {
+ // That constructor exists.
+ throw newLinkageError(e);
+ }
+ }
+
+ private static LinkageError newLinkageError(Throwable cause) {
+ return new LinkageError(cause.toString(), cause);
+ }
+ }
+
/**
* Returns a hash function implementing FarmHash's Fingerprint64, an open-source algorithm.
*
diff --git a/guava/src/com/google/common/hash/IgnoreJRERequirement.java b/guava/src/com/google/common/hash/IgnoreJRERequirement.java
new file mode 100644
index 000000000..0de7c9a92
--- /dev/null
+++ b/guava/src/com/google/common/hash/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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.hash;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/guava/src/com/google/common/hash/LittleEndianByteArray.java b/guava/src/com/google/common/hash/LittleEndianByteArray.java
index 625201547..4ff44796a 100644
--- a/guava/src/com/google/common/hash/LittleEndianByteArray.java
+++ b/guava/src/com/google/common/hash/LittleEndianByteArray.java
@@ -15,7 +15,11 @@
package com.google.common.hash;
import com.google.common.primitives.Longs;
+import java.lang.reflect.Field;
import java.nio.ByteOrder;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
import sun.misc.Unsafe;
/**
@@ -160,34 +164,32 @@ final class LittleEndianByteArray {
private static final int BYTE_ARRAY_BASE_OFFSET;
/**
- * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple
- * call to Unsafe.getUnsafe when integrating into a jdk.
+ * Returns an Unsafe. Suitable for use in a 3rd party package. Replace with a simple call to
+ * Unsafe.getUnsafe when integrating into a JDK.
*
- * @return a sun.misc.Unsafe instance if successful
+ * @return an Unsafe instance if successful
*/
- private static sun.misc.Unsafe getUnsafe() {
+ private static Unsafe getUnsafe() {
try {
- return sun.misc.Unsafe.getUnsafe();
+ return Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {
// We'll try reflection instead.
}
try {
- return java.security.AccessController.doPrivileged(
- new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
- @Override
- public sun.misc.Unsafe run() throws Exception {
- Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
- for (java.lang.reflect.Field f : k.getDeclaredFields()) {
- f.setAccessible(true);
- Object x = f.get(null);
- if (k.isInstance(x)) {
- return k.cast(x);
+ return AccessController.doPrivileged(
+ (PrivilegedExceptionAction<Unsafe>)
+ () -> {
+ Class<Unsafe> k = Unsafe.class;
+ for (Field f : k.getDeclaredFields()) {
+ f.setAccessible(true);
+ Object x = f.get(null);
+ if (k.isInstance(x)) {
+ return k.cast(x);
+ }
}
- }
- throw new NoSuchFieldError("the Unsafe");
- }
- });
- } catch (java.security.PrivilegedActionException e) {
+ throw new NoSuchFieldError("the Unsafe");
+ });
+ } catch (PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics", e.getCause());
}
}
@@ -226,7 +228,7 @@ final class LittleEndianByteArray {
sink[offset + i] = (byte) ((value & mask) >> (i * 8));
}
}
- };
+ }
}
static {
@@ -244,7 +246,7 @@ final class LittleEndianByteArray {
*
*/
String arch = System.getProperty("os.arch");
- if ("amd64".equals(arch)) {
+ if ("amd64".equals(arch) || "aarch64".equals(arch)) {
theGetter =
ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)
? UnsafeByteArray.UNSAFE_LITTLE_ENDIAN
diff --git a/guava/src/com/google/common/hash/MessageDigestHashFunction.java b/guava/src/com/google/common/hash/MessageDigestHashFunction.java
index 43fc087f2..0fe3347ea 100644
--- a/guava/src/com/google/common/hash/MessageDigestHashFunction.java
+++ b/guava/src/com/google/common/hash/MessageDigestHashFunction.java
@@ -19,6 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.errorprone.annotations.Immutable;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
@@ -120,6 +122,10 @@ final class MessageDigestHashFunction extends AbstractHashFunction implements Se
return new SerializedForm(prototype.getAlgorithm(), bytes, toString);
}
+ private void readObject(ObjectInputStream stream) throws InvalidObjectException {
+ throw new InvalidObjectException("Use SerializedForm");
+ }
+
/** Hasher that updates a message digest. */
private static final class MessageDigestHasher extends AbstractByteHasher {
private final MessageDigest digest;
diff --git a/guava/src/com/google/common/hash/Murmur3_32HashFunction.java b/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
index a47184be5..c320cd218 100644
--- a/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
+++ b/guava/src/com/google/common/hash/Murmur3_32HashFunction.java
@@ -267,7 +267,6 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return HashCode.fromInt(h1);
}
- @CanIgnoreReturnValue
private static final class Murmur3_32Hasher extends AbstractHasher {
private int h1;
private long buffer;
@@ -294,12 +293,14 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
}
}
+ @CanIgnoreReturnValue
@Override
public Hasher putByte(byte b) {
update(1, b & 0xFF);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putBytes(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
@@ -313,6 +314,7 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putBytes(ByteBuffer buffer) {
ByteOrder bo = buffer.order();
@@ -327,12 +329,14 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putInt(int i) {
update(4, i);
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putLong(long l) {
update(4, (int) l);
@@ -340,12 +344,14 @@ final class Murmur3_32HashFunction extends AbstractHashFunction implements Seria
return this;
}
+ @CanIgnoreReturnValue
@Override
public Hasher putChar(char c) {
update(2, c);
return this;
}
+ @CanIgnoreReturnValue
@SuppressWarnings("deprecation") // need to use Charsets for Android tests to pass
@Override
public Hasher putString(CharSequence input, Charset charset) {
diff --git a/guava/src/com/google/common/hash/ParametricNullness.java b/guava/src/com/google/common/hash/ParametricNullness.java
index 460106c09..4ebc40bb7 100644
--- a/guava/src/com/google/common/hash/ParametricNullness.java
+++ b/guava/src/com/google/common/hash/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/hash/PrimitiveSink.java b/guava/src/com/google/common/hash/PrimitiveSink.java
index a29ba4e13..ecd6a32c8 100644
--- a/guava/src/com/google/common/hash/PrimitiveSink.java
+++ b/guava/src/com/google/common/hash/PrimitiveSink.java
@@ -26,7 +26,6 @@ import java.nio.charset.Charset;
* @since 12.0 (in 11.0 as {@code Sink})
*/
@Beta
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
public interface PrimitiveSink {
/**
@@ -35,6 +34,7 @@ public interface PrimitiveSink {
* @param b a byte
* @return this instance
*/
+ @CanIgnoreReturnValue
PrimitiveSink putByte(byte b);
/**
@@ -43,6 +43,7 @@ public interface PrimitiveSink {
* @param bytes a byte array
* @return this instance
*/
+ @CanIgnoreReturnValue
PrimitiveSink putBytes(byte[] bytes);
/**
@@ -56,6 +57,7 @@ public interface PrimitiveSink {
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or
* {@code len < 0}
*/
+ @CanIgnoreReturnValue
PrimitiveSink putBytes(byte[] bytes, int off, int len);
/**
@@ -67,27 +69,35 @@ public interface PrimitiveSink {
* @return this instance
* @since 23.0
*/
+ @CanIgnoreReturnValue
PrimitiveSink putBytes(ByteBuffer bytes);
/** Puts a short into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putShort(short s);
/** Puts an int into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putInt(int i);
/** Puts a long into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putLong(long l);
/** Puts a float into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putFloat(float f);
/** Puts a double into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putDouble(double d);
/** Puts a boolean into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putBoolean(boolean b);
/** Puts a character into this sink. */
+ @CanIgnoreReturnValue
PrimitiveSink putChar(char c);
/**
@@ -99,6 +109,7 @@ public interface PrimitiveSink {
*
* @since 15.0 (since 11.0 as putString(CharSequence))
*/
+ @CanIgnoreReturnValue
PrimitiveSink putUnencodedChars(CharSequence charSequence);
/**
@@ -109,5 +120,6 @@ public interface PrimitiveSink {
* is faster, produces the same output across Java releases, and processes every {@code char} in
* the input, even if some are invalid.
*/
+ @CanIgnoreReturnValue
PrimitiveSink putString(CharSequence charSequence, Charset charset);
}
diff --git a/guava/src/com/google/common/html/ParametricNullness.java b/guava/src/com/google/common/html/ParametricNullness.java
index 61b446164..50a64c781 100644
--- a/guava/src/com/google/common/html/ParametricNullness.java
+++ b/guava/src/com/google/common/html/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/html/package-info.java b/guava/src/com/google/common/html/package-info.java
index f84d7f23d..1a97bccd1 100644
--- a/guava/src/com/google/common/html/package-info.java
+++ b/guava/src/com/google/common/html/package-info.java
@@ -17,7 +17,7 @@
* for
* HTML.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/guava/src/com/google/common/io/AppendableWriter.java b/guava/src/com/google/common/io/AppendableWriter.java
index d9aab342f..8566569a9 100644
--- a/guava/src/com/google/common/io/AppendableWriter.java
+++ b/guava/src/com/google/common/io/AppendableWriter.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
@@ -31,6 +32,7 @@ import javax.annotation.CheckForNull;
* @author Sebastian Kanthak
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
class AppendableWriter extends Writer {
diff --git a/guava/src/com/google/common/io/BaseEncoding.java b/guava/src/com/google/common/io/BaseEncoding.java
index 0d6f2e068..50a8ff7e4 100644
--- a/guava/src/com/google/common/io/BaseEncoding.java
+++ b/guava/src/com/google/common/io/BaseEncoding.java
@@ -26,8 +26,8 @@ import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
-import com.google.common.base.Objects;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.IOException;
import java.io.InputStream;
@@ -35,6 +35,7 @@ import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
+import java.util.Objects;
import javax.annotation.CheckForNull;
/**
@@ -169,12 +170,14 @@ public abstract class BaseEncoding {
* {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code
* Writer}.
*/
+ @J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
public abstract OutputStream encodingStream(Writer writer);
/**
* Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}.
*/
+ @J2ktIncompatible
@GwtIncompatible // ByteSink,CharSink
public final ByteSink encodingSink(CharSink encodedSink) {
checkNotNull(encodedSink);
@@ -239,6 +242,7 @@ public abstract class BaseEncoding {
* Returns an {@code InputStream} that decodes base-encoded input from the specified {@code
* Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors.
*/
+ @J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public abstract InputStream decodingStream(Reader reader);
@@ -246,6 +250,7 @@ public abstract class BaseEncoding {
* Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code
* CharSource}.
*/
+ @J2ktIncompatible
@GwtIncompatible // ByteSource,CharSource
public final ByteSource decodingSource(CharSource encodedSource) {
checkNotNull(encodedSource);
@@ -318,6 +323,16 @@ public abstract class BaseEncoding {
*/
public abstract BaseEncoding lowerCase();
+ /**
+ * Returns an encoding that behaves equivalently to this encoding, but decodes letters without
+ * regard to case.
+ *
+ * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
+ * lower-case characters
+ * @since 32.0.0
+ */
+ public abstract BaseEncoding ignoreCase();
+
private static final BaseEncoding BASE64 =
new Base64Encoding(
"base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '=');
@@ -428,8 +443,13 @@ public abstract class BaseEncoding {
final int bytesPerChunk;
private final byte[] decodabet;
private final boolean[] validPadding;
+ private final boolean ignoreCase;
Alphabet(String name, char[] chars) {
+ this(name, chars, decodabetFor(chars), /* ignoreCase= */ false);
+ }
+
+ private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) {
this.name = checkNotNull(name);
this.chars = checkNotNull(chars);
try {
@@ -438,20 +458,30 @@ public abstract class BaseEncoding {
throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e);
}
- /*
- * e.g. for base64, bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. This makes
- * for the smallest chunk size that still has charsPerChunk * bitsPerChar be a multiple of 8.
- */
- int gcd = Math.min(8, Integer.lowestOneBit(bitsPerChar));
- try {
- this.charsPerChunk = 8 / gcd;
- this.bytesPerChunk = bitsPerChar / gcd;
- } catch (ArithmeticException e) {
- throw new IllegalArgumentException("Illegal alphabet " + new String(chars), e);
- }
+ // Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into
+ // 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3.
+ // We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a
+ // multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many
+ // extra zero bits we need to add to the end of bitsPerChar to get 3 in total.
+ // The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII
+ // characters that can't happen.
+ int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar);
+ this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar);
+ this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar;
this.mask = chars.length - 1;
+ this.decodabet = decodabet;
+
+ boolean[] validPadding = new boolean[charsPerChunk];
+ for (int i = 0; i < bytesPerChunk; i++) {
+ validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
+ }
+ this.validPadding = validPadding;
+ this.ignoreCase = ignoreCase;
+ }
+
+ private static byte[] decodabetFor(char[] chars) {
byte[] decodabet = new byte[Ascii.MAX + 1];
Arrays.fill(decodabet, (byte) -1);
for (int i = 0; i < chars.length; i++) {
@@ -460,13 +490,33 @@ public abstract class BaseEncoding {
checkArgument(decodabet[c] == -1, "Duplicate character: %s", c);
decodabet[c] = (byte) i;
}
- this.decodabet = decodabet;
+ return decodabet;
+ }
- boolean[] validPadding = new boolean[charsPerChunk];
- for (int i = 0; i < bytesPerChunk; i++) {
- validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
+ /** Returns an equivalent {@code Alphabet} except it ignores case. */
+ Alphabet ignoreCase() {
+ if (ignoreCase) {
+ return this;
}
- this.validPadding = validPadding;
+
+ // We can't use .clone() because of GWT.
+ byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length);
+ for (int upper = 'A'; upper <= 'Z'; upper++) {
+ int lower = upper | 0x20;
+ byte decodeUpper = decodabet[upper];
+ byte decodeLower = decodabet[lower];
+ if (decodeUpper == -1) {
+ newDecodabet[upper] = decodeLower;
+ } else {
+ checkState(
+ decodeLower == -1,
+ "Can't ignoreCase() since '%s' and '%s' encode different values",
+ (char) upper,
+ (char) lower);
+ newDecodabet[lower] = decodeUpper;
+ }
+ }
+ return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true);
}
char encode(int bits) {
@@ -523,7 +573,8 @@ public abstract class BaseEncoding {
for (int i = 0; i < chars.length; i++) {
upperCased[i] = Ascii.toUpperCase(chars[i]);
}
- return new Alphabet(name + ".upperCase()", upperCased);
+ Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased);
+ return ignoreCase ? upperCase.ignoreCase() : upperCase;
}
Alphabet lowerCase() {
@@ -535,7 +586,8 @@ public abstract class BaseEncoding {
for (int i = 0; i < chars.length; i++) {
lowerCased[i] = Ascii.toLowerCase(chars[i]);
}
- return new Alphabet(name + ".lowerCase()", lowerCased);
+ Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased);
+ return ignoreCase ? lowerCase.ignoreCase() : lowerCase;
}
public boolean matches(char c) {
@@ -551,19 +603,18 @@ public abstract class BaseEncoding {
public boolean equals(@CheckForNull Object other) {
if (other instanceof Alphabet) {
Alphabet that = (Alphabet) other;
- return Arrays.equals(this.chars, that.chars);
+ return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars);
}
return false;
}
@Override
public int hashCode() {
- return Arrays.hashCode(chars);
+ return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237);
}
}
static class StandardBaseEncoding extends BaseEncoding {
- // TODO(lowasser): provide a useful toString
final Alphabet alphabet;
@CheckForNull final Character paddingChar;
@@ -586,6 +637,7 @@ public abstract class BaseEncoding {
return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING);
}
+ @J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer out) {
@@ -727,6 +779,7 @@ public abstract class BaseEncoding {
}
@Override
+ @J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
checkNotNull(reader);
@@ -830,8 +883,9 @@ public abstract class BaseEncoding {
return new SeparatedBaseEncoding(this, separator, afterEveryChars);
}
- @LazyInit @CheckForNull private transient BaseEncoding upperCase;
- @LazyInit @CheckForNull private transient BaseEncoding lowerCase;
+ @LazyInit @CheckForNull private volatile BaseEncoding upperCase;
+ @LazyInit @CheckForNull private volatile BaseEncoding lowerCase;
+ @LazyInit @CheckForNull private volatile BaseEncoding ignoreCase;
@Override
public BaseEncoding upperCase() {
@@ -853,6 +907,16 @@ public abstract class BaseEncoding {
return result;
}
+ @Override
+ public BaseEncoding ignoreCase() {
+ BaseEncoding result = ignoreCase;
+ if (result == null) {
+ Alphabet ignore = alphabet.ignoreCase();
+ result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar);
+ }
+ return result;
+ }
+
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new StandardBaseEncoding(alphabet, paddingChar);
}
@@ -860,7 +924,7 @@ public abstract class BaseEncoding {
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BaseEncoding.");
- builder.append(alphabet.toString());
+ builder.append(alphabet);
if (8 % alphabet.bitsPerChar != 0) {
if (paddingChar == null) {
builder.append(".omitPadding()");
@@ -876,7 +940,7 @@ public abstract class BaseEncoding {
if (other instanceof StandardBaseEncoding) {
StandardBaseEncoding that = (StandardBaseEncoding) other;
return this.alphabet.equals(that.alphabet)
- && Objects.equal(this.paddingChar, that.paddingChar);
+ && Objects.equals(this.paddingChar, that.paddingChar);
}
return false;
}
@@ -991,6 +1055,7 @@ public abstract class BaseEncoding {
}
}
+ @J2ktIncompatible
@GwtIncompatible
static Reader ignoringReader(Reader delegate, String toIgnore) {
checkNotNull(delegate);
@@ -1048,6 +1113,7 @@ public abstract class BaseEncoding {
};
}
+ @J2ktIncompatible
@GwtIncompatible // Writer
static Writer separatingWriter(Writer delegate, String separator, int afterEveryChars) {
Appendable separatingAppendable = separatingAppendable(delegate, separator, afterEveryChars);
@@ -1099,6 +1165,7 @@ public abstract class BaseEncoding {
+ separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR);
}
+ @J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer output) {
@@ -1140,6 +1207,7 @@ public abstract class BaseEncoding {
}
@Override
+ @J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
return delegate.decodingStream(ignoringReader(reader, separator));
@@ -1171,6 +1239,11 @@ public abstract class BaseEncoding {
}
@Override
+ public BaseEncoding ignoreCase() {
+ return delegate.ignoreCase().withSeparator(separator, afterEveryChars);
+ }
+
+ @Override
public String toString() {
return delegate + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")";
}
diff --git a/guava/src/com/google/common/io/ByteArrayDataInput.java b/guava/src/com/google/common/io/ByteArrayDataInput.java
index cf84fcc13..9fa295904 100644
--- a/guava/src/com/google/common/io/ByteArrayDataInput.java
+++ b/guava/src/com/google/common/io/ByteArrayDataInput.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.DataInput;
import java.io.IOException;
@@ -32,6 +33,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ByteArrayDataInput extends DataInput {
diff --git a/guava/src/com/google/common/io/ByteArrayDataOutput.java b/guava/src/com/google/common/io/ByteArrayDataOutput.java
index 373907361..487783531 100644
--- a/guava/src/com/google/common/io/ByteArrayDataOutput.java
+++ b/guava/src/com/google/common/io/ByteArrayDataOutput.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.DataOutput;
import java.io.IOException;
@@ -25,6 +26,7 @@ import java.io.IOException;
* @author Jayaprabhakar Kadarkarai
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ByteArrayDataOutput extends DataOutput {
diff --git a/guava/src/com/google/common/io/ByteProcessor.java b/guava/src/com/google/common/io/ByteProcessor.java
index 98ea3ffbb..cfb531c5a 100644
--- a/guava/src/com/google/common/io/ByteProcessor.java
+++ b/guava/src/com/google/common/io/ByteProcessor.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.io.IOException;
@@ -30,8 +30,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Chris Nokleberg
* @since 1.0
*/
-@Beta
@DoNotMock("Implement it normally")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ByteProcessor<T extends @Nullable Object> {
diff --git a/guava/src/com/google/common/io/ByteSink.java b/guava/src/com/google/common/io/ByteSink.java
index 7a6af6fc5..230216919 100644
--- a/guava/src/com/google/common/io/ByteSink.java
+++ b/guava/src/com/google/common/io/ByteSink.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedOutputStream;
import java.io.IOException;
@@ -45,6 +46,7 @@ import java.nio.charset.Charset;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ByteSink {
diff --git a/guava/src/com/google/common/io/ByteSource.java b/guava/src/com/google/common/io/ByteSource.java
index c8da9678b..31a5aa5d5 100644
--- a/guava/src/com/google/common/io/ByteSource.java
+++ b/guava/src/com/google/common/io/ByteSource.java
@@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.ByteStreams.createBuffer;
import static com.google.common.io.ByteStreams.skipUpTo;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
@@ -73,6 +73,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ByteSource {
@@ -178,7 +179,6 @@ public abstract class ByteSource {
*
* @since 19.0
*/
- @Beta
public Optional<Long> sizeIfKnown() {
return Optional.absent();
}
@@ -314,8 +314,8 @@ public abstract class ByteSource {
* processor} throws an {@code IOException}
* @since 16.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
+ @ParametricNullness
public <T extends @Nullable Object> T read(ByteProcessor<T> processor) throws IOException {
checkNotNull(processor);
@@ -571,7 +571,9 @@ public abstract class ByteSource {
}
}
- private static class ByteArrayByteSource extends ByteSource {
+ private static class ByteArrayByteSource extends
+ ByteSource
+ {
final byte[] bytes;
final int offset;
@@ -594,7 +596,7 @@ public abstract class ByteSource {
}
@Override
- public InputStream openBufferedStream() throws IOException {
+ public InputStream openBufferedStream() {
return openStream();
}
diff --git a/guava/src/com/google/common/io/ByteStreams.java b/guava/src/com/google/common/io/ByteStreams.java
index 99213bf16..640bc8bfc 100644
--- a/guava/src/com/google/common/io/ByteStreams.java
+++ b/guava/src/com/google/common/io/ByteStreams.java
@@ -21,8 +21,8 @@ import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Math.max;
import static java.lang.Math.min;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.ByteArrayInputStream;
@@ -53,6 +53,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ByteStreams {
@@ -99,6 +100,9 @@ public final class ByteStreams {
* Copies all bytes from the input stream to the output stream. Does not close or flush either
* stream.
*
+ * <p><b>Java 9 users and later:</b> this method should be treated as deprecated; use the
+ * equivalent {@link InputStream#transferTo} method instead.
+ *
* @param from the input stream to read from
* @param to the output stream to write to
* @return the number of bytes copied
@@ -283,7 +287,6 @@ public final class ByteStreams {
* @since 20.0
*/
@CanIgnoreReturnValue
- @Beta
public static long exhaust(InputStream in) throws IOException {
long total = 0;
long read;
@@ -298,7 +301,6 @@ public final class ByteStreams {
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the
* beginning.
*/
- @Beta
public static ByteArrayDataInput newDataInput(byte[] bytes) {
return newDataInput(new ByteArrayInputStream(bytes));
}
@@ -310,7 +312,6 @@ public final class ByteStreams {
* @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of
* the array
*/
- @Beta
public static ByteArrayDataInput newDataInput(byte[] bytes, int start) {
checkPositionIndex(start, bytes.length);
return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start));
@@ -323,7 +324,6 @@ public final class ByteStreams {
*
* @since 17.0
*/
- @Beta
public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) {
return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream));
}
@@ -475,7 +475,6 @@ public final class ByteStreams {
}
/** Returns a new {@link ByteArrayDataOutput} instance with a default size. */
- @Beta
public static ByteArrayDataOutput newDataOutput() {
return newDataOutput(new ByteArrayOutputStream());
}
@@ -486,7 +485,6 @@ public final class ByteStreams {
*
* @throws IllegalArgumentException if {@code size} is negative
*/
- @Beta
public static ByteArrayDataOutput newDataOutput(int size) {
// When called at high frequency, boxing size generates too much garbage,
// so avoid doing that if we can.
@@ -508,7 +506,6 @@ public final class ByteStreams {
*
* @since 17.0
*/
- @Beta
public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputStream) {
return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputStream));
}
@@ -685,7 +682,6 @@ public final class ByteStreams {
*
* @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream)
*/
- @Beta
public static OutputStream nullOutputStream() {
return NULL_OUTPUT_STREAM;
}
@@ -698,7 +694,6 @@ public final class ByteStreams {
* @return a length-limited {@link InputStream}
* @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream)
*/
- @Beta
public static InputStream limit(InputStream in, long limit) {
return new LimitedInputStream(in, limit);
}
@@ -785,7 +780,6 @@ public final class ByteStreams {
* @throws EOFException if this stream reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
- @Beta
public static void readFully(InputStream in, byte[] b) throws IOException {
readFully(in, b, 0, b.length);
}
@@ -802,7 +796,6 @@ public final class ByteStreams {
* @throws EOFException if this stream reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
- @Beta
public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException {
int read = read(in, b, off, len);
if (read != len) {
@@ -820,7 +813,6 @@ public final class ByteStreams {
* @throws EOFException if this stream reaches the end before skipping all the bytes
* @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
- @Beta
public static void skipFully(InputStream in, long n) throws IOException {
long skipped = skipUpTo(in, n);
if (skipped < n) {
@@ -886,7 +878,6 @@ public final class ByteStreams {
* @throws IOException if an I/O error occurs
* @since 14.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public static <T extends @Nullable Object> T readBytes(
@@ -926,7 +917,6 @@ public final class ByteStreams {
* @throws IndexOutOfBoundsException if {@code off} is negative, if {@code len} is negative, or if
* {@code off + len} is greater than {@code b.length}
*/
- @Beta
@CanIgnoreReturnValue
// Sometimes you don't care how many bytes you actually read, I guess.
// (You know that it's either going to read len bytes or stop at EOF.)
diff --git a/guava/src/com/google/common/io/CharSequenceReader.java b/guava/src/com/google/common/io/CharSequenceReader.java
index 790e26623..152743fec 100644
--- a/guava/src/com/google/common/io/CharSequenceReader.java
+++ b/guava/src/com/google/common/io/CharSequenceReader.java
@@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
@@ -32,6 +33,7 @@ import javax.annotation.CheckForNull;
* @author Colin Decker
*/
// TODO(cgdecker): make this public? as a type, or a method in CharStreams?
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class CharSequenceReader extends Reader {
diff --git a/guava/src/com/google/common/io/CharSink.java b/guava/src/com/google/common/io/CharSink.java
index f804daeb7..160522ed5 100644
--- a/guava/src/com/google/common/io/CharSink.java
+++ b/guava/src/com/google/common/io/CharSink.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -50,6 +50,7 @@ import java.util.stream.Stream;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class CharSink {
@@ -135,7 +136,6 @@ public abstract class CharSink {
* @throws IOException if an I/O error occurs while writing to this sink
* @since 22.0
*/
- @Beta
public void writeLines(Stream<? extends CharSequence> lines) throws IOException {
writeLines(lines, System.getProperty("line.separator"));
}
@@ -147,7 +147,6 @@ public abstract class CharSink {
* @throws IOException if an I/O error occurs while writing to this sink
* @since 22.0
*/
- @Beta
public void writeLines(Stream<? extends CharSequence> lines, String lineSeparator)
throws IOException {
writeLines(lines.iterator(), lineSeparator);
diff --git a/guava/src/com/google/common/io/CharSource.java b/guava/src/com/google/common/io/CharSource.java
index 24a67af5c..3c82bac13 100644
--- a/guava/src/com/google/common/io/CharSource.java
+++ b/guava/src/com/google/common/io/CharSource.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
@@ -81,6 +81,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class CharSource {
@@ -99,7 +100,6 @@ public abstract class CharSource {
*
* @since 20.0
*/
- @Beta
public ByteSource asByteSource(Charset charset) {
return new AsByteSource(charset);
}
@@ -155,7 +155,6 @@ public abstract class CharSource {
* @throws IOException if an I/O error occurs while opening the stream
* @since 22.0
*/
- @Beta
@MustBeClosed
public Stream<String> lines() throws IOException {
BufferedReader reader = openBufferedStream();
@@ -185,7 +184,6 @@ public abstract class CharSource {
*
* @since 19.0
*/
- @Beta
public Optional<Long> lengthIfKnown() {
return Optional.absent();
}
@@ -209,7 +207,6 @@ public abstract class CharSource {
* @throws IOException if an I/O error occurs while reading the length of this source
* @since 19.0
*/
- @Beta
public long length() throws IOException {
Optional<Long> lengthIfKnown = lengthIfKnown();
if (lengthIfKnown.isPresent()) {
@@ -364,7 +361,6 @@ public abstract class CharSource {
* processor} throws an {@code IOException}
* @since 16.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException {
@@ -394,7 +390,6 @@ public abstract class CharSource {
* throws an {@code UncheckedIOException}
* @since 22.0
*/
- @Beta
public void forEachLine(Consumer<? super String> action) throws IOException {
try (Stream<String> lines = lines()) {
// The lines should be ordered regardless in most cases, but use forEachOrdered to be sure
diff --git a/guava/src/com/google/common/io/CharStreams.java b/guava/src/com/google/common/io/CharStreams.java
index d36f9a3c5..877de824d 100644
--- a/guava/src/com/google/common/io/CharStreams.java
+++ b/guava/src/com/google/common/io/CharStreams.java
@@ -17,8 +17,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Closeable;
import java.io.EOFException;
@@ -43,6 +43,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CharStreams {
@@ -193,7 +194,6 @@ public final class CharStreams {
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
- @Beta
public static List<String> readLines(Readable r) throws IOException {
List<String> result = new ArrayList<>();
LineReader lineReader = new LineReader(r);
@@ -213,7 +213,6 @@ public final class CharStreams {
* @throws IOException if an I/O error occurs
* @since 14.0
*/
- @Beta
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public static <T extends @Nullable Object> T readLines(
@@ -237,7 +236,6 @@ public final class CharStreams {
*
* @since 20.0
*/
- @Beta
@CanIgnoreReturnValue
public static long exhaust(Readable readable) throws IOException {
long total = 0;
@@ -259,7 +257,6 @@ public final class CharStreams {
* @throws EOFException if this stream reaches the end before skipping all the characters
* @throws IOException if an I/O error occurs
*/
- @Beta
public static void skipFully(Reader reader, long n) throws IOException {
checkNotNull(reader);
while (n > 0) {
@@ -276,7 +273,6 @@ public final class CharStreams {
*
* @since 15.0
*/
- @Beta
public static Writer nullWriter() {
return NullWriter.INSTANCE;
}
@@ -344,7 +340,6 @@ public final class CharStreams {
* @param target the object to which output will be sent
* @return a new Writer object, unless target is a Writer, in which case the target is returned
*/
- @Beta
public static Writer asWriter(Appendable target) {
if (target instanceof Writer) {
return (Writer) target;
diff --git a/guava/src/com/google/common/io/Closeables.java b/guava/src/com/google/common/io/Closeables.java
index b45f5f0fd..aca51a996 100644
--- a/guava/src/com/google/common/io/Closeables.java
+++ b/guava/src/com/google/common/io/Closeables.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.IOException;
@@ -31,7 +31,7 @@ import javax.annotation.CheckForNull;
* @author Michael Lancaster
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Closeables {
diff --git a/guava/src/com/google/common/io/Closer.java b/guava/src/com/google/common/io/Closer.java
index 12998eff9..8e1db7a83 100644
--- a/guava/src/com/google/common/io/Closer.java
+++ b/guava/src/com/google/common/io/Closer.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -87,7 +87,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0
*/
// Coffee's for {@link Closer closers} only.
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Closer implements Closeable {
diff --git a/guava/src/com/google/common/io/CountingInputStream.java b/guava/src/com/google/common/io/CountingInputStream.java
index a37807ae7..bc481dd74 100644
--- a/guava/src/com/google/common/io/CountingInputStream.java
+++ b/guava/src/com/google/common/io/CountingInputStream.java
@@ -16,8 +16,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -28,7 +28,7 @@ import java.io.InputStream;
* @author Chris Nokleberg
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CountingInputStream extends FilterInputStream {
diff --git a/guava/src/com/google/common/io/CountingOutputStream.java b/guava/src/com/google/common/io/CountingOutputStream.java
index cf62b9c37..1cbfe081f 100644
--- a/guava/src/com/google/common/io/CountingOutputStream.java
+++ b/guava/src/com/google/common/io/CountingOutputStream.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -27,6 +28,7 @@ import java.io.OutputStream;
* @author Chris Nokleberg
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class CountingOutputStream extends FilterOutputStream {
diff --git a/guava/src/com/google/common/io/FileBackedOutputStream.java b/guava/src/com/google/common/io/FileBackedOutputStream.java
index 9912e2fcd..dd297e90a 100644
--- a/guava/src/com/google/common/io/FileBackedOutputStream.java
+++ b/guava/src/com/google/common/io/FileBackedOutputStream.java
@@ -14,12 +14,15 @@
package com.google.common.io;
+import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -34,6 +37,14 @@ import javax.annotation.CheckForNull;
* An {@link OutputStream} that starts buffering to a byte array, but switches to file buffering
* once the data reaches a configurable size.
*
+ * <p>When this stream creates a temporary file, it restricts the file's permissions to the current
+ * user or, in the case of Android, the current app. If that is not possible (as is the case under
+ * the very old Android Ice Cream Sandwich release), then this stream throws an exception instead of
+ * creating a file that would be more accessible. (This behavior is new in Guava 32.0.0. Previous
+ * versions would create a file that is more accessible, as discussed in <a
+ * href="https://github.com/google/guava/issues/2575">Guava issue 2575</a>. TODO: b/283778848 - Fill
+ * in CVE number once it's available.)
+ *
* <p>Temporary files created by this stream may live in the local filesystem until either:
*
* <ul>
@@ -51,13 +62,14 @@ import javax.annotation.CheckForNull;
* @since 1.0
*/
@Beta
+@J2ktIncompatible
@GwtIncompatible
+@J2ObjCIncompatible
@ElementTypesAreNonnullByDefault
public final class FileBackedOutputStream extends OutputStream {
private final int fileThreshold;
private final boolean resetOnFinalize;
private final ByteSource source;
- @CheckForNull private final File parentDirectory;
@GuardedBy("this")
private OutputStream out;
@@ -93,6 +105,7 @@ public final class FileBackedOutputStream extends OutputStream {
* {@link ByteSource} returned by {@link #asByteSource} is finalized.
*
* @param fileThreshold the number of bytes before the stream should switch to buffering to a file
+ * @throws IllegalArgumentException if {@code fileThreshold} is negative
*/
public FileBackedOutputStream(int fileThreshold) {
this(fileThreshold, false);
@@ -105,16 +118,13 @@ public final class FileBackedOutputStream extends OutputStream {
* @param fileThreshold the number of bytes before the stream should switch to buffering to a file
* @param resetOnFinalize if true, the {@link #reset} method will be called when the {@link
* ByteSource} returned by {@link #asByteSource} is finalized.
+ * @throws IllegalArgumentException if {@code fileThreshold} is negative
*/
public FileBackedOutputStream(int fileThreshold, boolean resetOnFinalize) {
- this(fileThreshold, resetOnFinalize, null);
- }
-
- private FileBackedOutputStream(
- int fileThreshold, boolean resetOnFinalize, @CheckForNull File parentDirectory) {
+ checkArgument(
+ fileThreshold >= 0, "fileThreshold must be non-negative, but was %s", fileThreshold);
this.fileThreshold = fileThreshold;
this.resetOnFinalize = resetOnFinalize;
- this.parentDirectory = parentDirectory;
memory = new MemoryOutput();
out = memory;
@@ -225,7 +235,7 @@ public final class FileBackedOutputStream extends OutputStream {
@GuardedBy("this")
private void update(int len) throws IOException {
if (memory != null && (memory.getCount() + len > fileThreshold)) {
- File temp = File.createTempFile("FileBackedOutputStream", null, parentDirectory);
+ File temp = TempFileCreator.INSTANCE.createTempFile("FileBackedOutputStream");
if (resetOnFinalize) {
// Finalizers are not guaranteed to be called on system shutdown;
// this is insurance.
diff --git a/guava/src/com/google/common/io/FileWriteMode.java b/guava/src/com/google/common/io/FileWriteMode.java
index 86872d1ba..47cf251e7 100644
--- a/guava/src/com/google/common/io/FileWriteMode.java
+++ b/guava/src/com/google/common/io/FileWriteMode.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
/**
* Modes for opening a file for writing. The default when mode when none is specified is to truncate
@@ -22,6 +23,7 @@ import com.google.common.annotations.GwtIncompatible;
*
* @author Colin Decker
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public enum FileWriteMode {
diff --git a/guava/src/com/google/common/io/Files.java b/guava/src/com/google/common/io/Files.java
index ba5528ff8..499ea6a20 100644
--- a/guava/src/com/google/common/io/Files.java
+++ b/guava/src/com/google/common/io/Files.java
@@ -20,6 +20,7 @@ import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
@@ -33,6 +34,7 @@ import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.InlineMe;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
@@ -66,13 +68,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Files {
- /** Maximum loop count when creating temp directories. */
- private static final int TEMP_DIR_ATTEMPTS = 10000;
-
private Files() {}
/**
@@ -119,7 +119,9 @@ public final class Files {
return new FileByteSource(file);
}
- private static final class FileByteSource extends ByteSource {
+ private static final class FileByteSource extends
+ ByteSource
+ {
private final File file;
@@ -394,17 +396,19 @@ public final class Files {
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
+ * <p>The temporary directory is created with permissions restricted to the current user or, in
+ * the case of Android, the current app. If that is not possible (as is the case under the very
+ * old Android Ice Cream Sandwich release), then this method throws an exception instead of
+ * creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0.
+ * Previous versions would create a directory that is more accessible, as discussed in <a
+ * href="https://github.com/google/guava/issues/4011">CVE-2020-8908</a>.)
+ *
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
- * <p>Depending on the environmment that this code is run in, the system temporary directory (and
- * thus the directory this method creates) may be more visible that a program would like - files
- * written to this directory may be read or overwritten by hostile programs running on the same
- * machine.
- *
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
@@ -412,36 +416,26 @@ public final class Files {
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
- * @throws IllegalStateException if the directory could not be created
+ * @throws IllegalStateException if the directory could not be created, such as if the system does
+ * not support creating temporary directories securely
* @deprecated For Android users, see the <a
* href="https://developer.android.com/training/data-storage" target="_blank">Data and File
* Storage overview</a> to select an appropriate temporary directory (perhaps {@code
- * context.getCacheDir()}). For developers on Java 7 or later, use {@link
- * java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using {@link
- * java.nio.file.Path#toFile() toFile()} if needed.
+ * context.getCacheDir()}), and create your own directory under that. (For example, you might
+ * use {@code new File(context.getCacheDir(), "directoryname").mkdir()}, or, if you need an
+ * arbitrary number of temporary directories, you might have to generate multiple directory
+ * names in a loop until {@code mkdir()} returns {@code true}.) For developers on Java 7 or
+ * later, use {@link java.nio.file.Files#createTempDirectory}, transforming it to a {@link
+ * File} using {@link java.nio.file.Path#toFile() toFile()} if needed. To restrict permissions
+ * as this method does, pass {@code
+ * PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))} to your
+ * call to {@code createTempDirectory}.
*/
@Beta
@Deprecated
+ @J2ObjCIncompatible
public static File createTempDir() {
- File baseDir = new File(System.getProperty("java.io.tmpdir"));
- @SuppressWarnings("GoodTime") // reading system time without TimeSource
- String baseName = System.currentTimeMillis() + "-";
-
- for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
- File tempDir = new File(baseDir, baseName + counter);
- if (tempDir.mkdir()) {
- return tempDir;
- }
- }
- throw new IllegalStateException(
- "Failed to create directory within "
- + TEMP_DIR_ATTEMPTS
- + " attempts (tried "
- + baseName
- + "0 to "
- + baseName
- + (TEMP_DIR_ATTEMPTS - 1)
- + ')');
+ return TempFileCreator.INSTANCE.createTempDir();
}
/**
@@ -847,7 +841,6 @@ public final class Files {
*
* @since 23.5
*/
- @Beta
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
diff --git a/guava/src/com/google/common/io/Flushables.java b/guava/src/com/google/common/io/Flushables.java
index 1f795a24a..4a42e4a40 100644
--- a/guava/src/com/google/common/io/Flushables.java
+++ b/guava/src/com/google/common/io/Flushables.java
@@ -16,6 +16,7 @@ package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.Flushable;
import java.io.IOException;
import java.util.logging.Level;
@@ -27,7 +28,7 @@ import java.util.logging.Logger;
* @author Michael Lancaster
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Flushables {
@@ -66,6 +67,7 @@ public final class Flushables {
*
* @param flushable the {@code Flushable} object to be flushed.
*/
+ @Beta
public static void flushQuietly(Flushable flushable) {
try {
flush(flushable, true);
diff --git a/guava/src/com/google/common/io/IgnoreJRERequirement.java b/guava/src/com/google/common/io/IgnoreJRERequirement.java
new file mode 100644
index 000000000..b1b8e1032
--- /dev/null
+++ b/guava/src/com/google/common/io/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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.io;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/guava/src/com/google/common/io/InsecureRecursiveDeleteException.java b/guava/src/com/google/common/io/InsecureRecursiveDeleteException.java
index 414093606..c292879ba 100644
--- a/guava/src/com/google/common/io/InsecureRecursiveDeleteException.java
+++ b/guava/src/com/google/common/io/InsecureRecursiveDeleteException.java
@@ -16,8 +16,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.nio.file.FileSystemException;
import java.nio.file.SecureDirectoryStream;
@@ -35,7 +35,7 @@ import javax.annotation.CheckForNull;
* @since 21.0
* @author Colin Decker
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@J2ObjCIncompatible // java.nio.file
@ElementTypesAreNonnullByDefault
diff --git a/guava/src/com/google/common/io/Java8Compatibility.java b/guava/src/com/google/common/io/Java8Compatibility.java
index 705d97b4d..bd3e6e055 100644
--- a/guava/src/com/google/common/io/Java8Compatibility.java
+++ b/guava/src/com/google/common/io/Java8Compatibility.java
@@ -15,12 +15,14 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.nio.Buffer;
/**
* Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
* https://github.com/google/guava/issues/3990
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
diff --git a/guava/src/com/google/common/io/LineBuffer.java b/guava/src/com/google/common/io/LineBuffer.java
index f944abc49..201dfd616 100644
--- a/guava/src/com/google/common/io/LineBuffer.java
+++ b/guava/src/com/google/common/io/LineBuffer.java
@@ -15,6 +15,7 @@
package com.google.common.io;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
@@ -29,6 +30,7 @@ import java.io.IOException;
* @author Chris Nokleberg
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class LineBuffer {
diff --git a/guava/src/com/google/common/io/LineProcessor.java b/guava/src/com/google/common/io/LineProcessor.java
index e28bebcc5..c0e08fa11 100644
--- a/guava/src/com/google/common/io/LineProcessor.java
+++ b/guava/src/com/google/common/io/LineProcessor.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -29,7 +29,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Miles Barr
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface LineProcessor<T extends @Nullable Object> {
diff --git a/guava/src/com/google/common/io/LineReader.java b/guava/src/com/google/common/io/LineReader.java
index 2c57ac454..54bf04c7c 100644
--- a/guava/src/com/google/common/io/LineReader.java
+++ b/guava/src/com/google/common/io/LineReader.java
@@ -17,8 +17,8 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.CharStreams.createBuffer;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.Reader;
@@ -35,7 +35,7 @@ import javax.annotation.CheckForNull;
* @author Chris Nokleberg
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class LineReader {
diff --git a/guava/src/com/google/common/io/LittleEndianDataInputStream.java b/guava/src/com/google/common/io/LittleEndianDataInputStream.java
index 88c8e27bc..54b1b14e8 100644
--- a/guava/src/com/google/common/io/LittleEndianDataInputStream.java
+++ b/guava/src/com/google/common/io/LittleEndianDataInputStream.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
@@ -39,7 +39,7 @@ import java.io.InputStream;
* @author Keith Bottner
* @since 8.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class LittleEndianDataInputStream extends FilterInputStream implements DataInput {
diff --git a/guava/src/com/google/common/io/LittleEndianDataOutputStream.java b/guava/src/com/google/common/io/LittleEndianDataOutputStream.java
index 6e51aff49..5d534f61c 100644
--- a/guava/src/com/google/common/io/LittleEndianDataOutputStream.java
+++ b/guava/src/com/google/common/io/LittleEndianDataOutputStream.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import java.io.DataOutput;
@@ -35,7 +35,7 @@ import java.io.OutputStream;
* @author Keith Bottner
* @since 8.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class LittleEndianDataOutputStream extends FilterOutputStream implements DataOutput {
diff --git a/guava/src/com/google/common/io/MoreFiles.java b/guava/src/com/google/common/io/MoreFiles.java
index ffe200d5e..b9a30c8fe 100644
--- a/guava/src/com/google/common/io/MoreFiles.java
+++ b/guava/src/com/google/common/io/MoreFiles.java
@@ -21,12 +21,11 @@ import static com.google.common.collect.Iterables.getOnlyElement;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
-import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.IOException;
@@ -67,7 +66,7 @@ import javax.annotation.CheckForNull;
* @since 21.0
* @author Colin Decker
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@J2ObjCIncompatible // java.nio.file
@ElementTypesAreNonnullByDefault
@@ -87,7 +86,9 @@ public final class MoreFiles {
return new PathByteSource(path, options);
}
- private static final class PathByteSource extends ByteSource {
+ private static final class PathByteSource extends
+ ByteSource
+ {
private static final LinkOption[] FOLLOW_LINKS = {};
@@ -170,7 +171,7 @@ public final class MoreFiles {
// If no OpenOptions were passed, delegate to Files.lines, which could have performance
// advantages. (If OpenOptions were passed we can't, because Files.lines doesn't have an
// overload taking OpenOptions, meaning we can't guarantee the same behavior w.r.t. things
- // like following/not following symlinks.
+ // like following/not following symlinks.)
return new AsCharSource(charset) {
@SuppressWarnings("FilesLinesLeak") // the user needs to close it in this case
@Override
@@ -292,17 +293,9 @@ public final class MoreFiles {
* @since 23.5
*/
public static Traverser<Path> fileTraverser() {
- return Traverser.forTree(FILE_TREE);
+ return Traverser.forTree(MoreFiles::fileTreeChildren);
}
- private static final SuccessorsFunction<Path> FILE_TREE =
- new SuccessorsFunction<Path>() {
- @Override
- public Iterable<Path> successors(Path path) {
- return fileTreeChildren(path);
- }
- };
-
private static Iterable<Path> fileTreeChildren(Path dir) {
if (Files.isDirectory(dir, NOFOLLOW_LINKS)) {
try {
diff --git a/guava/src/com/google/common/io/MultiInputStream.java b/guava/src/com/google/common/io/MultiInputStream.java
index 9a7e0fd1c..068baf679 100644
--- a/guava/src/com/google/common/io/MultiInputStream.java
+++ b/guava/src/com/google/common/io/MultiInputStream.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
@@ -29,6 +30,7 @@ import javax.annotation.CheckForNull;
* @author Chris Nokleberg
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class MultiInputStream extends InputStream {
diff --git a/guava/src/com/google/common/io/MultiReader.java b/guava/src/com/google/common/io/MultiReader.java
index cc36e527b..9e3a7eccb 100644
--- a/guava/src/com/google/common/io/MultiReader.java
+++ b/guava/src/com/google/common/io/MultiReader.java
@@ -17,6 +17,7 @@ package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Reader;
@@ -29,6 +30,7 @@ import javax.annotation.CheckForNull;
* @author Bin Zhu
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
class MultiReader extends Reader {
diff --git a/guava/src/com/google/common/io/ParametricNullness.java b/guava/src/com/google/common/io/ParametricNullness.java
index 98da76585..881c07d49 100644
--- a/guava/src/com/google/common/io/ParametricNullness.java
+++ b/guava/src/com/google/common/io/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/io/PatternFilenameFilter.java b/guava/src/com/google/common/io/PatternFilenameFilter.java
index 3cb2371e2..ee0a0bda2 100644
--- a/guava/src/com/google/common/io/PatternFilenameFilter.java
+++ b/guava/src/com/google/common/io/PatternFilenameFilter.java
@@ -14,8 +14,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FilenameFilter;
@@ -29,7 +29,7 @@ import java.util.regex.PatternSyntaxException;
* @author Apple Chow
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class PatternFilenameFilter implements FilenameFilter {
diff --git a/guava/src/com/google/common/io/ReaderInputStream.java b/guava/src/com/google/common/io/ReaderInputStream.java
index 75f8a3e1e..af84686ec 100644
--- a/guava/src/com/google/common/io/ReaderInputStream.java
+++ b/guava/src/com/google/common/io/ReaderInputStream.java
@@ -19,6 +19,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.UnsignedBytes;
import java.io.IOException;
import java.io.InputStream;
@@ -43,6 +44,7 @@ import java.util.Arrays;
*
* @author Chris Nokleberg
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class ReaderInputStream extends InputStream {
@@ -198,8 +200,8 @@ final class ReaderInputStream extends InputStream {
/** Handle the case of underflow caused by needing more input characters. */
private void readMoreChars() throws IOException {
// Possibilities:
- // 1) array has space available on right hand side (between limit and capacity)
- // 2) array has space available on left hand side (before position)
+ // 1) array has space available on right-hand side (between limit and capacity)
+ // 2) array has space available on left-hand side (before position)
// 3) array has no space available
//
// In case 2 we shift the existing chars to the left, and in case 3 we create a bigger
diff --git a/guava/src/com/google/common/io/RecursiveDeleteOption.java b/guava/src/com/google/common/io/RecursiveDeleteOption.java
index 1bb27a16b..a25055e40 100644
--- a/guava/src/com/google/common/io/RecursiveDeleteOption.java
+++ b/guava/src/com/google/common/io/RecursiveDeleteOption.java
@@ -16,8 +16,8 @@
package com.google.common.io;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.nio.file.SecureDirectoryStream;
@@ -28,7 +28,7 @@ import java.nio.file.SecureDirectoryStream;
* @since 21.0
* @author Colin Decker
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@J2ObjCIncompatible // java.nio.file
@ElementTypesAreNonnullByDefault
diff --git a/guava/src/com/google/common/io/Resources.java b/guava/src/com/google/common/io/Resources.java
index d1e37070a..aedf3ade2 100644
--- a/guava/src/com/google/common/io/Resources.java
+++ b/guava/src/com/google/common/io/Resources.java
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
@@ -40,6 +41,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Colin Decker
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Resources {
diff --git a/guava/src/com/google/common/io/TempFileCreator.java b/guava/src/com/google/common/io/TempFileCreator.java
new file mode 100644
index 000000000..966323599
--- /dev/null
+++ b/guava/src/com/google/common/io/TempFileCreator.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright (C) 2007 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.io;
+
+import static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR;
+import static com.google.common.base.StandardSystemProperty.USER_NAME;
+import static java.nio.file.attribute.AclEntryFlag.DIRECTORY_INHERIT;
+import static java.nio.file.attribute.AclEntryFlag.FILE_INHERIT;
+import static java.nio.file.attribute.AclEntryType.ALLOW;
+import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;
+
+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import com.google.common.collect.ImmutableList;
+import com.google.j2objc.annotations.J2ObjCIncompatible;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Paths;
+import java.nio.file.attribute.AclEntry;
+import java.nio.file.attribute.AclEntryPermission;
+import java.nio.file.attribute.FileAttribute;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.nio.file.attribute.UserPrincipal;
+import java.util.EnumSet;
+import java.util.Set;
+
+/**
+ * Creates temporary files and directories whose permissions are restricted to the current user or,
+ * in the case of Android, the current app. If that is not possible (as is the case under the very
+ * old Android Ice Cream Sandwich release), then this class throws an exception instead of creating
+ * a file or directory that would be more accessible.
+ */
+@J2ktIncompatible
+@GwtIncompatible
+@J2ObjCIncompatible
+@ElementTypesAreNonnullByDefault
+abstract class TempFileCreator {
+ static final TempFileCreator INSTANCE = pickSecureCreator();
+
+ /**
+ * @throws IllegalStateException if the directory could not be created (to implement the contract
+ * of {@link Files#createTempDir()}, such as if the system does not support creating temporary
+ * directories securely
+ */
+ abstract File createTempDir();
+
+ abstract File createTempFile(String prefix) throws IOException;
+
+ private static TempFileCreator pickSecureCreator() {
+ try {
+ Class.forName("java.nio.file.Path");
+ return new JavaNioCreator();
+ } catch (ClassNotFoundException runningUnderAndroid) {
+ // Try another way.
+ }
+
+ try {
+ int version = (int) Class.forName("android.os.Build$VERSION").getField("SDK_INT").get(null);
+ int jellyBean =
+ (int) Class.forName("android.os.Build$VERSION_CODES").getField("JELLY_BEAN").get(null);
+ /*
+ * I assume that this check can't fail because JELLY_BEAN will be present only if we're
+ * running under Jelly Bean or higher. But it seems safest to check.
+ */
+ if (version < jellyBean) {
+ return new ThrowingCreator();
+ }
+
+ // Don't merge these catch() blocks, let alone use ReflectiveOperationException directly:
+ // b/65343391
+ } catch (NoSuchFieldException e) {
+ // The JELLY_BEAN field doesn't exist because we're running on a version before Jelly Bean :)
+ return new ThrowingCreator();
+ } catch (ClassNotFoundException e) {
+ // Should be impossible, but we want to return *something* so that class init succeeds.
+ return new ThrowingCreator();
+ } catch (IllegalAccessException e) {
+ // ditto
+ return new ThrowingCreator();
+ }
+
+ // Android isolates apps' temporary directories since Jelly Bean:
+ // https://github.com/google/guava/issues/4011#issuecomment-770020802
+ // So we can create files there with any permissions and still get security from the isolation.
+ return new JavaIoCreator();
+ }
+
+ @IgnoreJRERequirement // used only when Path is available
+ private static final class JavaNioCreator extends TempFileCreator {
+ @Override
+ File createTempDir() {
+ try {
+ return java.nio.file.Files.createTempDirectory(
+ Paths.get(JAVA_IO_TMPDIR.value()), /* prefix= */ null, directoryPermissions.get())
+ .toFile();
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to create directory", e);
+ }
+ }
+
+ @Override
+ File createTempFile(String prefix) throws IOException {
+ return java.nio.file.Files.createTempFile(
+ Paths.get(JAVA_IO_TMPDIR.value()),
+ /* prefix= */ prefix,
+ /* suffix= */ null,
+ filePermissions.get())
+ .toFile();
+ }
+
+ @IgnoreJRERequirement // see enclosing class (whose annotation Animal Sniffer ignores here...)
+ private interface PermissionSupplier {
+ FileAttribute<?> get() throws IOException;
+ }
+
+ private static final PermissionSupplier filePermissions;
+ private static final PermissionSupplier directoryPermissions;
+
+ static {
+ Set<String> views = FileSystems.getDefault().supportedFileAttributeViews();
+ if (views.contains("posix")) {
+ filePermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rw-------"));
+ directoryPermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rwx------"));
+ } else if (views.contains("acl")) {
+ filePermissions = directoryPermissions = userPermissions();
+ } else {
+ filePermissions =
+ directoryPermissions =
+ () -> {
+ throw new IOException("unrecognized FileSystem type " + FileSystems.getDefault());
+ };
+ }
+ }
+
+ private static PermissionSupplier userPermissions() {
+ try {
+ UserPrincipal user =
+ FileSystems.getDefault()
+ .getUserPrincipalLookupService()
+ .lookupPrincipalByName(USER_NAME.value());
+ ImmutableList<AclEntry> acl =
+ ImmutableList.of(
+ AclEntry.newBuilder()
+ .setType(ALLOW)
+ .setPrincipal(user)
+ .setPermissions(EnumSet.allOf(AclEntryPermission.class))
+ .setFlags(DIRECTORY_INHERIT, FILE_INHERIT)
+ .build());
+ FileAttribute<ImmutableList<AclEntry>> attribute =
+ new FileAttribute<ImmutableList<AclEntry>>() {
+ @Override
+ public String name() {
+ return "acl:acl";
+ }
+
+ @Override
+ public ImmutableList<AclEntry> value() {
+ return acl;
+ }
+ };
+ return () -> attribute;
+ } catch (IOException e) {
+ // We throw a new exception each time so that the stack trace is right.
+ return () -> {
+ throw new IOException("Could not find user", e);
+ };
+ }
+ }
+ }
+
+ private static final class JavaIoCreator extends TempFileCreator {
+ @Override
+ File createTempDir() {
+ File baseDir = new File(JAVA_IO_TMPDIR.value());
+ @SuppressWarnings("GoodTime") // reading system time without TimeSource
+ String baseName = System.currentTimeMillis() + "-";
+
+ for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
+ File tempDir = new File(baseDir, baseName + counter);
+ if (tempDir.mkdir()) {
+ return tempDir;
+ }
+ }
+ throw new IllegalStateException(
+ "Failed to create directory within "
+ + TEMP_DIR_ATTEMPTS
+ + " attempts (tried "
+ + baseName
+ + "0 to "
+ + baseName
+ + (TEMP_DIR_ATTEMPTS - 1)
+ + ')');
+ }
+
+ @Override
+ File createTempFile(String prefix) throws IOException {
+ return File.createTempFile(
+ /* prefix= */ prefix,
+ /* suffix= */ null,
+ /* directory= */ null /* defaults to java.io.tmpdir */);
+ }
+
+ /** Maximum loop count when creating temp directories. */
+ private static final int TEMP_DIR_ATTEMPTS = 10000;
+ }
+
+ private static final class ThrowingCreator extends TempFileCreator {
+ private static final String MESSAGE =
+ "Guava cannot securely create temporary files or directories under SDK versions before"
+ + " Jelly Bean. You can create one yourself, either in the insecure default directory"
+ + " or in a more secure directory, such as context.getCacheDir(). For more information,"
+ + " see the Javadoc for Files.createTempDir().";
+
+ @Override
+ File createTempDir() {
+ throw new IllegalStateException(MESSAGE);
+ }
+
+ @Override
+ File createTempFile(String prefix) throws IOException {
+ throw new IOException(MESSAGE);
+ }
+ }
+
+ private TempFileCreator() {}
+}
diff --git a/guava/src/com/google/common/io/package-info.java b/guava/src/com/google/common/io/package-info.java
index f0666b26f..e4eebbd0d 100644
--- a/guava/src/com/google/common/io/package-info.java
+++ b/guava/src/com/google/common/io/package-info.java
@@ -13,16 +13,15 @@
*/
/**
- * This package contains utility methods and classes for working with Java I/O; for example input
- * streams, output streams, readers, writers, and files.
+ * Utility methods and classes for I/O; for example input streams, output streams, readers, writers,
+ * and files.
*
- * <p>At the core of this package are the Source/Sink types: {@link com.google.common.io.ByteSource
- * ByteSource}, {@link com.google.common.io.CharSource CharSource}, {@link
- * com.google.common.io.ByteSink ByteSink} and {@link com.google.common.io.CharSink CharSink}. They
- * are factories for I/O streams that provide many convenience methods that handle both opening and
+ * <p>At the core of this package are the Source/Sink types: {@link ByteSource ByteSource}, {@link
+ * CharSource CharSource}, {@link ByteSink ByteSink} and {@link CharSink CharSink}. They are
+ * factories for I/O streams that provide many convenience methods that handle both opening and
* closing streams for you.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library. For more information on Sources and Sinks as well as other features of this package, see
* <a href="https://github.com/google/guava/wiki/IOExplained">I/O Explained</a> on the Guava wiki.
*
diff --git a/guava/src/com/google/common/math/BigDecimalMath.java b/guava/src/com/google/common/math/BigDecimalMath.java
index 33a55d356..d70940479 100644
--- a/guava/src/com/google/common/math/BigDecimalMath.java
+++ b/guava/src/com/google/common/math/BigDecimalMath.java
@@ -15,6 +15,7 @@
package com.google.common.math;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -24,6 +25,7 @@ import java.math.RoundingMode;
* @author Louis Wasserman
* @since 30.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class BigDecimalMath {
diff --git a/guava/src/com/google/common/math/BigIntegerMath.java b/guava/src/com/google/common/math/BigIntegerMath.java
index 6ef1e81ed..cf943195d 100644
--- a/guava/src/com/google/common/math/BigIntegerMath.java
+++ b/guava/src/com/google/common/math/BigIntegerMath.java
@@ -25,9 +25,9 @@ import static java.math.RoundingMode.HALF_DOWN;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.UNNECESSARY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -57,7 +57,6 @@ public final class BigIntegerMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static BigInteger ceilingPowerOfTwo(BigInteger x) {
return BigInteger.ZERO.setBit(log2(x, CEILING));
}
@@ -69,7 +68,6 @@ public final class BigIntegerMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static BigInteger floorPowerOfTwo(BigInteger x) {
return BigInteger.ZERO.setBit(log2(x, FLOOR));
}
@@ -146,6 +144,7 @@ public final class BigIntegerMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static int log10(BigInteger x, RoundingMode mode) {
@@ -224,6 +223,7 @@ public final class BigIntegerMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
* sqrt(x)} is not an integer
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
@@ -260,6 +260,7 @@ public final class BigIntegerMath {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static BigInteger sqrtFloor(BigInteger x) {
/*
@@ -304,6 +305,7 @@ public final class BigIntegerMath {
return sqrt0;
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static BigInteger sqrtApproxWithDoubles(BigInteger x) {
return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN);
@@ -330,11 +332,13 @@ public final class BigIntegerMath {
* is not precisely representable as a {@code double}
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible
public static double roundToDouble(BigInteger x, RoundingMode mode) {
return BigIntegerToDoubleRounder.INSTANCE.roundToDouble(x, mode);
}
+ @J2ktIncompatible
@GwtIncompatible
private static class BigIntegerToDoubleRounder extends ToDoubleRounder<BigInteger> {
static final BigIntegerToDoubleRounder INSTANCE = new BigIntegerToDoubleRounder();
@@ -369,6 +373,7 @@ public final class BigIntegerMath {
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) {
BigDecimal pDec = new BigDecimal(p);
@@ -521,6 +526,7 @@ public final class BigIntegerMath {
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
+ @J2ktIncompatible
@GwtIncompatible // TODO
static boolean fitsInLong(BigInteger x) {
return x.bitLength() <= Long.SIZE - 1;
diff --git a/guava/src/com/google/common/math/DoubleMath.java b/guava/src/com/google/common/math/DoubleMath.java
index cdd0a4b39..36de5378f 100644
--- a/guava/src/com/google/common/math/DoubleMath.java
+++ b/guava/src/com/google/common/math/DoubleMath.java
@@ -32,6 +32,7 @@ import static java.lang.Math.rint;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Booleans;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -52,6 +53,7 @@ public final class DoubleMath {
* This method returns a value y such that rounding y DOWN (towards zero) gives the same result as
* rounding x according to the specified mode.
*/
+ @J2ktIncompatible
@GwtIncompatible // #isMathematicalInteger, com.google.common.math.DoubleUtils
static double roundIntermediate(double x, RoundingMode mode) {
if (!isFinite(x)) {
@@ -128,6 +130,7 @@ public final class DoubleMath {
* RoundingMode#UNNECESSARY}
* </ul>
*/
+ @J2ktIncompatible
@GwtIncompatible // #roundIntermediate
public static int roundToInt(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
@@ -153,6 +156,7 @@ public final class DoubleMath {
* RoundingMode#UNNECESSARY}
* </ul>
*/
+ @J2ktIncompatible
@GwtIncompatible // #roundIntermediate
public static long roundToLong(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
@@ -180,6 +184,7 @@ public final class DoubleMath {
* </ul>
*/
// #roundIntermediate, java.lang.Math.getExponent, com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static BigInteger roundToBigInteger(double x, RoundingMode mode) {
x = roundIntermediate(x, mode);
@@ -196,6 +201,7 @@ public final class DoubleMath {
* Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer
* {@code k}.
*/
+ @J2ktIncompatible
@GwtIncompatible // com.google.common.math.DoubleUtils
public static boolean isPowerOfTwo(double x) {
if (x > 0.0 && isFinite(x)) {
@@ -234,6 +240,7 @@ public final class DoubleMath {
* @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is
* infinite
*/
+ @J2ktIncompatible
@GwtIncompatible // java.lang.Math.getExponent, com.google.common.math.DoubleUtils
@SuppressWarnings("fallthrough")
public static int log2(double x, RoundingMode mode) {
@@ -404,6 +411,7 @@ public final class DoubleMath {
*/
@Deprecated
// com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static double mean(double... values) {
checkArgument(values.length > 0, "Cannot take mean of 0 values");
@@ -484,6 +492,7 @@ public final class DoubleMath {
*/
@Deprecated
// com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static double mean(Iterable<? extends Number> values) {
return mean(values.iterator());
@@ -504,6 +513,7 @@ public final class DoubleMath {
*/
@Deprecated
// com.google.common.math.DoubleUtils
+ @J2ktIncompatible
@GwtIncompatible
public static double mean(Iterator<? extends Number> values) {
checkArgument(values.hasNext(), "Cannot take mean of 0 values");
@@ -518,6 +528,7 @@ public final class DoubleMath {
return mean;
}
+ @J2ktIncompatible
@GwtIncompatible // com.google.common.math.DoubleUtils
@CanIgnoreReturnValue
private static double checkFinite(double argument) {
diff --git a/guava/src/com/google/common/math/IntMath.java b/guava/src/com/google/common/math/IntMath.java
index 17a18c699..3fff5793c 100644
--- a/guava/src/com/google/common/math/IntMath.java
+++ b/guava/src/com/google/common/math/IntMath.java
@@ -25,9 +25,9 @@ import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.math.BigInteger;
@@ -63,7 +63,6 @@ public final class IntMath {
* int}, i.e. when {@code x > 2^30}
* @since 20.0
*/
- @Beta
public static int ceilingPowerOfTwo(int x) {
checkPositive("x", x);
if (x > MAX_SIGNED_POWER_OF_TWO) {
@@ -79,7 +78,6 @@ public final class IntMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static int floorPowerOfTwo(int x) {
checkPositive("x", x);
return Integer.highestOneBit(x);
@@ -155,6 +153,7 @@ public final class IntMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
+ @J2ktIncompatible
@GwtIncompatible // need BigIntegerMath to adequately test
@SuppressWarnings("fallthrough")
public static int log10(int x, RoundingMode mode) {
@@ -224,6 +223,7 @@ public final class IntMath {
*
* @throws IllegalArgumentException if {@code k < 0}
*/
+ @J2ktIncompatible
@GwtIncompatible // failing tests
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
@@ -532,7 +532,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedAdd(int a, int b) {
return Ints.saturatedCast((long) a + b);
}
@@ -543,7 +542,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedSubtract(int a, int b) {
return Ints.saturatedCast((long) a - b);
}
@@ -554,7 +552,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedMultiply(int a, int b) {
return Ints.saturatedCast((long) a * b);
}
@@ -565,7 +562,6 @@ public final class IntMath {
*
* @since 20.0
*/
- @Beta
public static int saturatedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
@@ -719,8 +715,8 @@ public final class IntMath {
* @throws IllegalArgumentException if {@code n} is negative
* @since 20.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
- @Beta
public static boolean isPrime(int n) {
return LongMath.isPrime(n);
}
diff --git a/guava/src/com/google/common/math/LinearTransformation.java b/guava/src/com/google/common/math/LinearTransformation.java
index 4cc1eb87d..51d3f32a3 100644
--- a/guava/src/com/google/common/math/LinearTransformation.java
+++ b/guava/src/com/google/common/math/LinearTransformation.java
@@ -18,8 +18,8 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.DoubleUtils.isFinite;
import static java.lang.Double.NaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.LazyInit;
import javax.annotation.CheckForNull;
@@ -34,7 +34,7 @@ import javax.annotation.CheckForNull;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class LinearTransformation {
diff --git a/guava/src/com/google/common/math/LongMath.java b/guava/src/com/google/common/math/LongMath.java
index dd5ff0694..fa8271a1e 100644
--- a/guava/src/com/google/common/math/LongMath.java
+++ b/guava/src/com/google/common/math/LongMath.java
@@ -25,9 +25,9 @@ import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Longs;
import com.google.common.primitives.UnsignedLongs;
@@ -64,7 +64,6 @@ public final class LongMath {
* long}, i.e. when {@code x > 2^62}
* @since 20.0
*/
- @Beta
public static long ceilingPowerOfTwo(long x) {
checkPositive("x", x);
if (x > MAX_SIGNED_POWER_OF_TWO) {
@@ -80,7 +79,6 @@ public final class LongMath {
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
- @Beta
public static long floorPowerOfTwo(long x) {
checkPositive("x", x);
@@ -95,6 +93,7 @@ public final class LongMath {
* <p>This differs from {@code Long.bitCount(x) == 1}, because {@code
* Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
*/
+ @SuppressWarnings("ShortCircuitBoolean")
public static boolean isPowerOfTwo(long x) {
return x > 0 & (x & (x - 1)) == 0;
}
@@ -142,10 +141,8 @@ public final class LongMath {
// floor(2^(logFloor + 0.5))
int logFloor = (Long.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
-
- default:
- throw new AssertionError("impossible");
}
+ throw new AssertionError("impossible");
}
/** The biggest half power of two that fits into an unsigned long */
@@ -158,6 +155,7 @@ public final class LongMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
@@ -180,11 +178,11 @@ public final class LongMath {
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
- default:
- throw new AssertionError();
}
+ throw new AssertionError();
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
static int log10Floor(long x) {
/*
@@ -210,6 +208,7 @@ public final class LongMath {
3, 2, 2, 2, 1, 1, 1, 0, 0, 0
};
+ @J2ktIncompatible
@GwtIncompatible // TODO
@VisibleForTesting
static final long[] powersOf10 = {
@@ -235,6 +234,7 @@ public final class LongMath {
};
// halfPowersOf10[i] = largest long less than 10^(i + 0.5)
+ @J2ktIncompatible
@GwtIncompatible // TODO
@VisibleForTesting
static final long[] halfPowersOf10 = {
@@ -266,6 +266,7 @@ public final class LongMath {
*
* @throws IllegalArgumentException if {@code k < 0}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static long pow(long b, int k) {
checkNonNegative("exponent", k);
@@ -309,8 +310,8 @@ public final class LongMath {
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
* sqrt(x)} is not an integer
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
- @SuppressWarnings("fallthrough")
public static long sqrt(long x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInInt(x)) {
@@ -331,7 +332,7 @@ public final class LongMath {
* since (long) Math.sqrt(k * k) == k, as checked exhaustively in
* {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect}
*/
- long guess = (long) Math.sqrt(x);
+ long guess = (long) Math.sqrt((double) x);
// Note: guess is always <= FLOOR_SQRT_MAX_LONG.
long guessSquared = guess * guess;
// Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is
@@ -369,9 +370,8 @@ public final class LongMath {
* signed long, so lessThanBranchFree is safe for use.
*/
return sqrtFloor + lessThanBranchFree(halfSquare, x);
- default:
- throw new AssertionError();
}
+ throw new AssertionError();
}
/**
@@ -381,6 +381,7 @@ public final class LongMath {
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("fallthrough")
public static long divide(long p, long q, RoundingMode mode) {
@@ -454,6 +455,7 @@ public final class LongMath {
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
* Remainder Operator</a>
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static int mod(long x, int m) {
// Cast is safe because the result is guaranteed in the range [0, m)
@@ -478,6 +480,7 @@ public final class LongMath {
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
* Remainder Operator</a>
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static long mod(long x, long m) {
if (m <= 0) {
@@ -543,7 +546,7 @@ public final class LongMath {
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
*/
- @GwtIncompatible // TODO
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedAdd(long a, long b) {
long result = a + b;
checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0, "checkedAdd", a, b);
@@ -555,7 +558,9 @@ public final class LongMath {
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedSubtract(long a, long b) {
long result = a - b;
checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0, "checkedSubtract", a, b);
@@ -567,6 +572,7 @@ public final class LongMath {
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
*/
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedMultiply(long a, long b) {
// Hacker's Delight, Section 2-12
int leadingZeros =
@@ -600,7 +606,9 @@ public final class LongMath {
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code
* long} arithmetic
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
+ @SuppressWarnings("ShortCircuitBoolean")
public static long checkedPow(long b, int k) {
checkNonNegative("exponent", k);
if (b >= -2 & b <= 2) {
@@ -648,7 +656,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedAdd(long a, long b) {
long naiveSum = a + b;
if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) {
@@ -666,7 +674,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedSubtract(long a, long b) {
long naiveDifference = a - b;
if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) {
@@ -684,7 +692,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedMultiply(long a, long b) {
// see checkedMultiply for explanation
int leadingZeros =
@@ -714,7 +722,7 @@ public final class LongMath {
*
* @since 20.0
*/
- @Beta
+ @SuppressWarnings("ShortCircuitBoolean")
public static long saturatedPow(long b, int k) {
checkNonNegative("exponent", k);
if (b >= -2 & b <= 2) {
@@ -741,7 +749,7 @@ public final class LongMath {
}
long accum = 1;
// if b is negative and k is odd then the limit is MIN otherwise the limit is MAX
- long limit = Long.MAX_VALUE + ((b >>> Long.SIZE - 1) & (k & 1));
+ long limit = Long.MAX_VALUE + ((b >>> (Long.SIZE - 1)) & (k & 1));
while (true) {
switch (k) {
case 0:
@@ -771,6 +779,7 @@ public final class LongMath {
*
* @throws IllegalArgumentException if {@code n < 0}
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static long factorial(int n) {
checkNonNegative("n", n);
@@ -979,7 +988,7 @@ public final class LongMath {
}
/*
- * This bitmask is used as an optimization for cheaply testing for divisiblity by 2, 3, or 5.
+ * This bitmask is used as an optimization for cheaply testing for divisibility by 2, 3, or 5.
* Each bit is set to 1 for all remainders that indicate divisibility by 2, 3, or 5, so
* 1, 7, 11, 13, 17, 19, 23, 29 are set to 0. 30 and up don't matter because they won't be hit.
*/
@@ -999,8 +1008,8 @@ public final class LongMath {
* @throws IllegalArgumentException if {@code n} is negative
* @since 20.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
- @Beta
public static boolean isPrime(long n) {
if (n < 2) {
checkNonNegative("n", n);
@@ -1116,7 +1125,7 @@ public final class LongMath {
private long times2ToThe32Mod(long a, long m) {
int remainingPowersOf2 = 32;
do {
- int shift = Math.min(remainingPowersOf2, Long.numberOfLeadingZeros(a));
+ int shift = min(remainingPowersOf2, Long.numberOfLeadingZeros(a));
// shift is either the number of powers of 2 left to multiply a by, or the biggest shift
// possible while keeping a in an unsigned long.
a = UnsignedLongs.remainder(a << shift, m);
@@ -1243,6 +1252,7 @@ public final class LongMath {
* @since 30.0
*/
@SuppressWarnings("deprecation")
+ @J2ktIncompatible
@GwtIncompatible
public static double roundToDouble(long x, RoundingMode mode) {
// Logic adapted from ToDoubleRounder.
diff --git a/guava/src/com/google/common/math/MathPreconditions.java b/guava/src/com/google/common/math/MathPreconditions.java
index 37d608a82..d8b7b10bf 100644
--- a/guava/src/com/google/common/math/MathPreconditions.java
+++ b/guava/src/com/google/common/math/MathPreconditions.java
@@ -25,9 +25,9 @@ import java.math.RoundingMode;
* @author Louis Wasserman
*/
@GwtCompatible
-@CanIgnoreReturnValue
@ElementTypesAreNonnullByDefault
final class MathPreconditions {
+ @CanIgnoreReturnValue
static int checkPositive(String role, int x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
@@ -35,6 +35,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static long checkPositive(String role, long x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
@@ -42,6 +43,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static BigInteger checkPositive(String role, BigInteger x) {
if (x.signum() <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
@@ -49,6 +51,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static int checkNonNegative(String role, int x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
@@ -56,6 +59,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static long checkNonNegative(String role, long x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
@@ -63,6 +67,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static BigInteger checkNonNegative(String role, BigInteger x) {
if (x.signum() < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
@@ -70,6 +75,7 @@ final class MathPreconditions {
return x;
}
+ @CanIgnoreReturnValue
static double checkNonNegative(String role, double x) {
if (!(x >= 0)) { // not x < 0, to work with NaN.
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
diff --git a/guava/src/com/google/common/math/PairedStats.java b/guava/src/com/google/common/math/PairedStats.java
index 31ab9b719..c60a62b0a 100644
--- a/guava/src/com/google/common/math/PairedStats.java
+++ b/guava/src/com/google/common/math/PairedStats.java
@@ -21,8 +21,8 @@ import static java.lang.Double.NaN;
import static java.lang.Double.doubleToLongBits;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.io.Serializable;
@@ -37,7 +37,7 @@ import javax.annotation.CheckForNull;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class PairedStats implements Serializable {
diff --git a/guava/src/com/google/common/math/PairedStatsAccumulator.java b/guava/src/com/google/common/math/PairedStatsAccumulator.java
index 072ef13b3..9d365633a 100644
--- a/guava/src/com/google/common/math/PairedStatsAccumulator.java
+++ b/guava/src/com/google/common/math/PairedStatsAccumulator.java
@@ -19,8 +19,8 @@ import static com.google.common.primitives.Doubles.isFinite;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Doubles;
/**
@@ -30,7 +30,7 @@ import com.google.common.primitives.Doubles;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class PairedStatsAccumulator {
diff --git a/guava/src/com/google/common/math/ParametricNullness.java b/guava/src/com/google/common/math/ParametricNullness.java
index 8e57826e4..612fa934a 100644
--- a/guava/src/com/google/common/math/ParametricNullness.java
+++ b/guava/src/com/google/common/math/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/math/Quantiles.java b/guava/src/com/google/common/math/Quantiles.java
index 6ddea9bcf..78f310dd0 100644
--- a/guava/src/com/google/common/math/Quantiles.java
+++ b/guava/src/com/google/common/math/Quantiles.java
@@ -21,8 +21,8 @@ import static java.lang.Double.POSITIVE_INFINITY;
import static java.util.Arrays.sort;
import static java.util.Collections.unmodifiableMap;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Ints;
import java.math.RoundingMode;
@@ -126,7 +126,7 @@ import java.util.Map;
* @author Pete Gillin
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Quantiles {
diff --git a/guava/src/com/google/common/math/Stats.java b/guava/src/com/google/common/math/Stats.java
index 20c9466f5..c1143c04f 100644
--- a/guava/src/com/google/common/math/Stats.java
+++ b/guava/src/com/google/common/math/Stats.java
@@ -24,8 +24,8 @@ import static java.lang.Double.NaN;
import static java.lang.Double.doubleToLongBits;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.io.Serializable;
@@ -62,7 +62,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Stats implements Serializable {
@@ -126,9 +126,9 @@ public final class Stats implements Serializable {
* @param values a series of values
*/
public static Stats of(double... values) {
- StatsAccumulator acummulator = new StatsAccumulator();
- acummulator.addAll(values);
- return acummulator.snapshot();
+ StatsAccumulator accumulator = new StatsAccumulator();
+ accumulator.addAll(values);
+ return accumulator.snapshot();
}
/**
@@ -137,9 +137,9 @@ public final class Stats implements Serializable {
* @param values a series of values
*/
public static Stats of(int... values) {
- StatsAccumulator acummulator = new StatsAccumulator();
- acummulator.addAll(values);
- return acummulator.snapshot();
+ StatsAccumulator accumulator = new StatsAccumulator();
+ accumulator.addAll(values);
+ return accumulator.snapshot();
}
/**
@@ -149,9 +149,9 @@ public final class Stats implements Serializable {
* cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15))
*/
public static Stats of(long... values) {
- StatsAccumulator acummulator = new StatsAccumulator();
- acummulator.addAll(values);
- return acummulator.snapshot();
+ StatsAccumulator accumulator = new StatsAccumulator();
+ accumulator.addAll(values);
+ return accumulator.snapshot();
}
/**
diff --git a/guava/src/com/google/common/math/StatsAccumulator.java b/guava/src/com/google/common/math/StatsAccumulator.java
index b28229c96..c7bf01cf6 100644
--- a/guava/src/com/google/common/math/StatsAccumulator.java
+++ b/guava/src/com/google/common/math/StatsAccumulator.java
@@ -20,8 +20,8 @@ import static com.google.common.primitives.Doubles.isFinite;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Iterator;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
@@ -35,7 +35,7 @@ import java.util.stream.LongStream;
* @author Kevin Bourrillion
* @since 20.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class StatsAccumulator {
diff --git a/guava/src/com/google/common/math/ToDoubleRounder.java b/guava/src/com/google/common/math/ToDoubleRounder.java
index 2e7e7fae0..5bfcd12ca 100644
--- a/guava/src/com/google/common/math/ToDoubleRounder.java
+++ b/guava/src/com/google/common/math/ToDoubleRounder.java
@@ -18,12 +18,14 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.math.RoundingMode;
/**
* Helper type to implement rounding {@code X} to a representable {@code double} value according to
* a {@link RoundingMode}.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class ToDoubleRounder<X extends Number & Comparable<X>> {
diff --git a/guava/src/com/google/common/math/package-info.java b/guava/src/com/google/common/math/package-info.java
index 0408246e7..02580e1a4 100644
--- a/guava/src/com/google/common/math/package-info.java
+++ b/guava/src/com/google/common/math/package-info.java
@@ -13,9 +13,10 @@
*/
/**
- * Arithmetic functions operating on primitive values and {@link java.math.BigInteger} instances.
+ * Arithmetic functions operating on primitive values and on {@link java.math.BigInteger} and {@link
+ * java.math.BigDecimal} instances.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* <p>See the Guava User Guide article on <a
diff --git a/guava/src/com/google/common/net/HostSpecifier.java b/guava/src/com/google/common/net/HostSpecifier.java
index c57f3d975..65194112e 100644
--- a/guava/src/com/google/common/net/HostSpecifier.java
+++ b/guava/src/com/google/common/net/HostSpecifier.java
@@ -15,6 +15,7 @@
package com.google.common.net;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.net.InetAddress;
@@ -41,6 +42,7 @@ import javax.annotation.CheckForNull;
* @author Craig Berry
* @since 5.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class HostSpecifier {
diff --git a/guava/src/com/google/common/net/HttpHeaders.java b/guava/src/com/google/common/net/HttpHeaders.java
index 2ecbfaa8c..4c1f865b5 100644
--- a/guava/src/com/google/common/net/HttpHeaders.java
+++ b/guava/src/com/google/common/net/HttpHeaders.java
@@ -317,6 +317,13 @@ public final class HttpHeaders {
*/
public static final String KEEP_ALIVE = "Keep-Alive";
/**
+ * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/no-vary-search.md">{@code
+ * No-Vary-Seearch}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String NO_VARY_SEARCH = "No-Vary-Search";
+ /**
* The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code Origin-Trial}</a>
* header field name.
*
@@ -366,6 +373,16 @@ public final class HttpHeaders {
public static final String SOURCE_MAP = "SourceMap";
/**
+ * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/opt-in.md">{@code
+ * Supports-Loading-Mode}</a> header field name. This can be used to specify, for example, <a
+ * href="https://developer.chrome.com/docs/privacy-sandbox/fenced-frame/#server-opt-in">fenced
+ * frames</a>.
+ *
+ * @since 32.0.0
+ */
+ public static final String SUPPORTS_LOADING_MODE = "Supports-Loading-Mode";
+
+ /**
* The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">{@code
* Strict-Transport-Security}</a> header field name.
*
@@ -690,13 +707,49 @@ public final class HttpHeaders {
*/
public static final String SEC_CH_UA_MOBILE = "Sec-CH-UA-Mobile";
/**
+ * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-wow64">{@code
+ * Sec-CH-UA-WoW64}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_UA_WOW64 = "Sec-CH-UA-WoW64";
+ /**
* The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness">{@code
* Sec-CH-UA-Bitness}</a> header field name.
*
* @since 31.0
*/
public static final String SEC_CH_UA_BITNESS = "Sec-CH-UA-Bitness";
-
+ /**
+ * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factor">{@code
+ * Sec-CH-UA-Form-Factor}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_UA_FORM_FACTOR = "Sec-CH-UA-Form-Factor";
+ /**
+ * The HTTP <a
+ * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-width">{@code
+ * Sec-CH-Viewport-Width}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_VIEWPORT_WIDTH = "Sec-CH-Viewport-Width";
+ /**
+ * The HTTP <a
+ * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-height">{@code
+ * Sec-CH-Viewport-Height}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_VIEWPORT_HEIGHT = "Sec-CH-Viewport-Height";
+ /**
+ * The HTTP <a href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-dpr">{@code
+ * Sec-CH-DPR}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_CH_DPR = "Sec-CH-DPR";
/**
* The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Dest}</a>
* header field name.
@@ -789,6 +842,20 @@ public final class HttpHeaders {
*/
public static final String SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version";
/**
+ * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code
+ * Sec-Browsing-Topics}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String SEC_BROWSING_TOPICS = "Sec-Browsing-Topics";
+ /**
+ * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code
+ * Observe-Browsing-Topics}</a> header field name.
+ *
+ * @since 32.0.0
+ */
+ public static final String OBSERVE_BROWSING_TOPICS = "Observe-Browsing-Topics";
+ /**
* The HTTP <a href="https://tools.ietf.org/html/rfc8586">{@code CDN-Loop}</a> header field name.
*
* @since 28.0
diff --git a/guava/src/com/google/common/net/InetAddresses.java b/guava/src/com/google/common/net/InetAddresses.java
index d3e68db8a..6d8309381 100644
--- a/guava/src/com/google/common/net/InetAddresses.java
+++ b/guava/src/com/google/common/net/InetAddresses.java
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.MoreObjects;
import com.google.common.hash.Hashing;
@@ -95,6 +96,7 @@ import javax.annotation.CheckForNull;
* @author Erik Kline
* @since 5.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class InetAddresses {
@@ -522,7 +524,7 @@ public final class InetAddresses {
* want to accept ASCII digits only, you can use something like {@code
* CharMatcher.ascii().matchesAllOf(ipString)}.
*
- * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
+ * @param hostAddr an RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
* @return an InetAddress representing the address in {@code hostAddr}
* @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6
* address surrounded by square brackets
@@ -1026,7 +1028,7 @@ public final class InetAddresses {
/**
* Converts a BigInteger to either an IPv4 or IPv6 address. If the IP is IPv4, it must be
- * constrainted to 32 bits, otherwise it is constrained to 128 bits.
+ * constrained to 32 bits, otherwise it is constrained to 128 bits.
*
* @param address the address represented as a big integer
* @param isIpv6 whether the created address should be IPv4 or IPv6
diff --git a/guava/src/com/google/common/net/InternetDomainName.java b/guava/src/com/google/common/net/InternetDomainName.java
index d71a9d5c3..d098bf4fb 100644
--- a/guava/src/com/google/common/net/InternetDomainName.java
+++ b/guava/src/com/google/common/net/InternetDomainName.java
@@ -27,6 +27,7 @@ import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.thirdparty.publicsuffix.PublicSuffixPatterns;
import com.google.thirdparty.publicsuffix.PublicSuffixType;
import java.util.List;
@@ -81,12 +82,18 @@ public final class InternetDomainName {
private static final Joiner DOT_JOINER = Joiner.on('.');
/**
- * Value of {@link #publicSuffixIndex} or {@link #registrySuffixIndex} which indicates that no
+ * Value of {@link #publicSuffixIndex()} or {@link #registrySuffixIndex()} which indicates that no
* relevant suffix was found.
*/
private static final int NO_SUFFIX_FOUND = -1;
/**
+ * Value of {@link #publicSuffixIndexCache} or {@link #registrySuffixIndexCache} which indicates
+ * that they were not initialized yet.
+ */
+ private static final int SUFFIX_NOT_INITIALIZED = -2;
+
+ /**
* Maximum parts (labels) in a domain name. This value arises from the 255-octet limit described
* in <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11 with the fact that the
* encoding of each part occupies at least two bytes (dot plus label externally, length byte plus
@@ -113,20 +120,26 @@ public final class InternetDomainName {
private final ImmutableList<String> parts;
/**
- * The index in the {@link #parts()} list at which the public suffix begins. For example, for the
- * domain name {@code myblog.blogspot.co.uk}, the value would be 1 (the index of the {@code
- * blogspot} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no public
- * suffix was found.
+ * Cached value of #publicSuffixIndex(). Do not use directly.
+ *
+ * <p>Since this field isn't {@code volatile}, if an instance of this class is shared across
+ * threads before it is initialized, then each thread is likely to compute their own copy of the
+ * value.
*/
- private final int publicSuffixIndex;
+ @SuppressWarnings("Immutable")
+ @LazyInit
+ private int publicSuffixIndexCache = SUFFIX_NOT_INITIALIZED;
/**
- * The index in the {@link #parts()} list at which the registry suffix begins. For example, for
- * the domain name {@code myblog.blogspot.co.uk}, the value would be 2 (the index of the {@code
- * co} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no registry suffix
- * was found.
+ * Cached value of #registrySuffixIndex(). Do not use directly.
+ *
+ * <p>Since this field isn't {@code volatile}, if an instance of this class is shared across
+ * threads before it is initialized, then each thread is likely to compute their own copy of the
+ * value.
*/
- private final int registrySuffixIndex;
+ @SuppressWarnings("Immutable")
+ @LazyInit
+ private int registrySuffixIndexCache = SUFFIX_NOT_INITIALIZED;
/** Constructor used to implement {@link #from(String)}, and from subclasses. */
InternetDomainName(String name) {
@@ -147,9 +160,36 @@ public final class InternetDomainName {
this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name));
checkArgument(parts.size() <= MAX_PARTS, "Domain has too many parts: '%s'", name);
checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name);
+ }
- this.publicSuffixIndex = findSuffixOfType(Optional.<PublicSuffixType>absent());
- this.registrySuffixIndex = findSuffixOfType(Optional.of(PublicSuffixType.REGISTRY));
+ /**
+ * The index in the {@link #parts()} list at which the public suffix begins. For example, for the
+ * domain name {@code myblog.blogspot.co.uk}, the value would be 1 (the index of the {@code
+ * blogspot} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no public
+ * suffix was found.
+ */
+ private int publicSuffixIndex() {
+ int publicSuffixIndexLocal = publicSuffixIndexCache;
+ if (publicSuffixIndexLocal == SUFFIX_NOT_INITIALIZED) {
+ publicSuffixIndexCache =
+ publicSuffixIndexLocal = findSuffixOfType(Optional.<PublicSuffixType>absent());
+ }
+ return publicSuffixIndexLocal;
+ }
+
+ /**
+ * The index in the {@link #parts()} list at which the registry suffix begins. For example, for
+ * the domain name {@code myblog.blogspot.co.uk}, the value would be 2 (the index of the {@code
+ * co} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no registry suffix
+ * was found.
+ */
+ private int registrySuffixIndex() {
+ int registrySuffixIndexLocal = registrySuffixIndexCache;
+ if (registrySuffixIndexLocal == SUFFIX_NOT_INITIALIZED) {
+ registrySuffixIndexCache =
+ registrySuffixIndexLocal = findSuffixOfType(Optional.of(PublicSuffixType.REGISTRY));
+ }
+ return registrySuffixIndexLocal;
}
/**
@@ -167,6 +207,12 @@ public final class InternetDomainName {
for (int i = 0; i < partsSize; i++) {
String ancestorName = DOT_JOINER.join(parts.subList(i, partsSize));
+ if (i > 0
+ && matchesType(
+ desiredType, Optional.fromNullable(PublicSuffixPatterns.UNDER.get(ancestorName)))) {
+ return i - 1;
+ }
+
if (matchesType(
desiredType, Optional.fromNullable(PublicSuffixPatterns.EXACT.get(ancestorName)))) {
return i;
@@ -178,10 +224,6 @@ public final class InternetDomainName {
if (PublicSuffixPatterns.EXCLUDED.containsKey(ancestorName)) {
return i + 1;
}
-
- if (matchesWildcardSuffixType(desiredType, ancestorName)) {
- return i;
- }
}
return NO_SUFFIX_FOUND;
@@ -329,7 +371,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean isPublicSuffix() {
- return publicSuffixIndex == 0;
+ return publicSuffixIndex() == 0;
}
/**
@@ -345,7 +387,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean hasPublicSuffix() {
- return publicSuffixIndex != NO_SUFFIX_FOUND;
+ return publicSuffixIndex() != NO_SUFFIX_FOUND;
}
/**
@@ -356,7 +398,7 @@ public final class InternetDomainName {
*/
@CheckForNull
public InternetDomainName publicSuffix() {
- return hasPublicSuffix() ? ancestor(publicSuffixIndex) : null;
+ return hasPublicSuffix() ? ancestor(publicSuffixIndex()) : null;
}
/**
@@ -372,7 +414,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean isUnderPublicSuffix() {
- return publicSuffixIndex > 0;
+ return publicSuffixIndex() > 0;
}
/**
@@ -388,7 +430,7 @@ public final class InternetDomainName {
* @since 6.0
*/
public boolean isTopPrivateDomain() {
- return publicSuffixIndex == 1;
+ return publicSuffixIndex() == 1;
}
/**
@@ -412,7 +454,7 @@ public final class InternetDomainName {
return this;
}
checkState(isUnderPublicSuffix(), "Not under a public suffix: %s", name);
- return ancestor(publicSuffixIndex - 1);
+ return ancestor(publicSuffixIndex() - 1);
}
/**
@@ -439,7 +481,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean isRegistrySuffix() {
- return registrySuffixIndex == 0;
+ return registrySuffixIndex() == 0;
}
/**
@@ -454,7 +496,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean hasRegistrySuffix() {
- return registrySuffixIndex != NO_SUFFIX_FOUND;
+ return registrySuffixIndex() != NO_SUFFIX_FOUND;
}
/**
@@ -465,7 +507,7 @@ public final class InternetDomainName {
*/
@CheckForNull
public InternetDomainName registrySuffix() {
- return hasRegistrySuffix() ? ancestor(registrySuffixIndex) : null;
+ return hasRegistrySuffix() ? ancestor(registrySuffixIndex()) : null;
}
/**
@@ -477,7 +519,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean isUnderRegistrySuffix() {
- return registrySuffixIndex > 0;
+ return registrySuffixIndex() > 0;
}
/**
@@ -492,7 +534,7 @@ public final class InternetDomainName {
* @since 23.3
*/
public boolean isTopDomainUnderRegistrySuffix() {
- return registrySuffixIndex == 1;
+ return registrySuffixIndex() == 1;
}
/**
@@ -515,7 +557,7 @@ public final class InternetDomainName {
return this;
}
checkState(isUnderRegistrySuffix(), "Not under a registry suffix: %s", name);
- return ancestor(registrySuffixIndex - 1);
+ return ancestor(registrySuffixIndex() - 1);
}
/** Indicates whether this domain is composed of two or more parts. */
@@ -592,18 +634,6 @@ public final class InternetDomainName {
}
/**
- * Does the domain name match one of the "wildcard" patterns (e.g. {@code "*.ar"})? If a {@code
- * desiredType} is specified, the wildcard pattern must also match that type.
- */
- private static boolean matchesWildcardSuffixType(
- Optional<PublicSuffixType> desiredType, String domain) {
- List<String> pieces = DOT_SPLITTER.limit(2).splitToList(domain);
- return pieces.size() == 2
- && matchesType(
- desiredType, Optional.fromNullable(PublicSuffixPatterns.UNDER.get(pieces.get(1))));
- }
-
- /**
* If a {@code desiredType} is specified, returns true only if the {@code actualType} is
* identical. Otherwise, returns true as long as {@code actualType} is present.
*/
diff --git a/guava/src/com/google/common/net/MediaType.java b/guava/src/com/google/common/net/MediaType.java
index a713d0b17..c7da53491 100644
--- a/guava/src/com/google/common/net/MediaType.java
+++ b/guava/src/com/google/common/net/MediaType.java
@@ -492,6 +492,13 @@ public final class MediaType {
public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
/**
+ * For <a href="https://tools.ietf.org/html/7519">JWT objects using the compact Serialization</a>.
+ *
+ * @since 32.0.0
+ */
+ public static final MediaType JWT = createConstant(APPLICATION_TYPE, "jwt");
+
+ /**
* The <a href="http://www.w3.org/TR/appmanifest/">Manifest for a web application</a>.
*
* @since 19.0
@@ -886,7 +893,7 @@ public final class MediaType {
* one.
*
* <p>If a charset must be specified that is not supported on this JVM (and thus is not
- * representable as a {@link Charset} instance, use {@link #withParameter}.
+ * representable as a {@link Charset} instance), use {@link #withParameter}.
*/
public MediaType withCharset(Charset charset) {
checkNotNull(charset);
diff --git a/guava/src/com/google/common/net/ParametricNullness.java b/guava/src/com/google/common/net/ParametricNullness.java
index 1ad2e27c0..83b9eb6fa 100644
--- a/guava/src/com/google/common/net/ParametricNullness.java
+++ b/guava/src/com/google/common/net/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/net/PercentEscaper.java b/guava/src/com/google/common/net/PercentEscaper.java
index 929014731..411834f8d 100644
--- a/guava/src/com/google/common/net/PercentEscaper.java
+++ b/guava/src/com/google/common/net/PercentEscaper.java
@@ -74,10 +74,10 @@ public final class PercentEscaper extends UnicodeEscaper {
* space character.
*
* <p>Not that it is allowed, but not necessarily desirable to specify {@code %} as a safe
- * character. This has the effect of creating an escaper which has no well defined inverse but it
+ * character. This has the effect of creating an escaper which has no well-defined inverse but it
* can be useful when escaping additional characters.
*
- * @param safeChars a non null string specifying additional safe characters for this escaper (the
+ * @param safeChars a non-null string specifying additional safe characters for this escaper (the
* ranges 0..9, a..z and A..Z are always safe and should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +} rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
diff --git a/guava/src/com/google/common/net/package-info.java b/guava/src/com/google/common/net/package-info.java
index d55642d94..6a74ecee4 100644
--- a/guava/src/com/google/common/net/package-info.java
+++ b/guava/src/com/google/common/net/package-info.java
@@ -13,10 +13,9 @@
*/
/**
- * This package contains utility methods and classes for working with net addresses (numeric IP and
- * domain names).
+ * Utility methods and classes for networking (such as IP addresses and domain names).
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* @author Craig Berry
diff --git a/guava/src/com/google/common/primitives/Booleans.java b/guava/src/com/google/common/primitives/Booleans.java
index 522049bfe..1af9e337d 100644
--- a/guava/src/com/google/common/primitives/Booleans.java
+++ b/guava/src/com/google/common/primitives/Booleans.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
@@ -80,7 +79,6 @@ public final class Booleans {
*
* @since 21.0
*/
- @Beta
public static Comparator<Boolean> trueFirst() {
return BooleanComparator.TRUE_FIRST;
}
@@ -93,7 +91,6 @@ public final class Booleans {
*
* @since 21.0
*/
- @Beta
public static Comparator<Boolean> falseFirst() {
return BooleanComparator.FALSE_FIRST;
}
@@ -361,9 +358,10 @@ public final class Booleans {
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
* set a value to {@code null} will result in a {@link NullPointerException}.
*
- * <p>The returned list maintains the values, but not the identities, of {@code Boolean} objects
- * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
- * the returned list is unspecified.
+ * <p>There are at most two distinct objects in this list, {@code (Boolean) true} and {@code
+ * (Boolean) false}. Java guarantees that those are always represented by the same objects.
+ *
+ * <p>The returned list is serializable.
*
* @param backingArray the array to back the list
* @return a list view of the array
@@ -510,7 +508,6 @@ public final class Booleans {
*
* @since 16.0
*/
- @Beta
public static int countTrue(boolean... values) {
int count = 0;
for (boolean value : values) {
@@ -551,4 +548,54 @@ public final class Booleans {
array[j] = tmp;
}
}
+
+ /**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Booleans.asList(array),
+ * distance)}, but is somewhat faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(boolean[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Booleans.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * somewhat faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(boolean[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
}
diff --git a/guava/src/com/google/common/primitives/Bytes.java b/guava/src/com/google/common/primitives/Bytes.java
index 62997f34a..b32ef8ec9 100644
--- a/guava/src/com/google/common/primitives/Bytes.java
+++ b/guava/src/com/google/common/primitives/Bytes.java
@@ -227,6 +227,8 @@ public final class Bytes {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
@@ -396,4 +398,54 @@ public final class Bytes {
array[j] = tmp;
}
}
+
+ /**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
+ * distance)}, but is somewhat faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(byte[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is somewhat
+ * faster.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(byte[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
}
diff --git a/guava/src/com/google/common/primitives/Chars.java b/guava/src/com/google/common/primitives/Chars.java
index 4a2e3a344..728c6e5e9 100644
--- a/guava/src/com/google/common/primitives/Chars.java
+++ b/guava/src/com/google/common/primitives/Chars.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
@@ -258,7 +257,6 @@ public final class Chars {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static char constrainToRange(char value, char min, char max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return value < min ? min : value < max ? value : max;
@@ -489,6 +487,56 @@ public final class Chars {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Chars.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(char[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Chars.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(char[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
* set a value to {@code null} will result in a {@link NullPointerException}.
@@ -497,6 +545,8 @@ public final class Chars {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
diff --git a/guava/src/com/google/common/primitives/Doubles.java b/guava/src/com/google/common/primitives/Doubles.java
index fab3cf610..f5133ecde 100644
--- a/guava/src/com/google/common/primitives/Doubles.java
+++ b/guava/src/com/google/common/primitives/Doubles.java
@@ -22,9 +22,9 @@ import static com.google.common.base.Strings.lenientFormat;
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.POSITIVE_INFINITY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
import java.util.AbstractList;
@@ -255,7 +255,6 @@ public final class Doubles extends DoublesMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static double constrainToRange(double value, double min, double max) {
// avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984
// Reject NaN by testing for the good case (min <= max) instead of the bad (min > max).
@@ -320,7 +319,6 @@ public final class Doubles extends DoublesMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Double> stringConverter() {
return DoubleConverter.INSTANCE;
}
@@ -470,6 +468,56 @@ public final class Doubles extends DoublesMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(double[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(double[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code double}
* value in the manner of {@link Number#doubleValue}.
*
@@ -509,6 +557,8 @@ public final class Doubles extends DoublesMethodsForWeb {
* <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
* is used as a parameter to any of its methods.
*
+ * <p>The returned list is serializable.
+ *
* <p><b>Note:</b> when possible, you should represent your data as an {@link
* ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view.
*
@@ -662,7 +712,7 @@ public final class Doubles extends DoublesMethodsForWeb {
* inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs
* that pass this regex are valid -- only a performance hit is incurred, not a semantics bug.
*/
- @GwtIncompatible // regular expressions
+ @J2ktIncompatible @GwtIncompatible // regular expressions
static final
java.util.regex.Pattern
FLOATING_POINT_PATTERN = fpPattern();
@@ -708,7 +758,7 @@ public final class Doubles extends DoublesMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // regular expressions
@CheckForNull
public static Double tryParse(String string) {
diff --git a/guava/src/com/google/common/primitives/Floats.java b/guava/src/com/google/common/primitives/Floats.java
index b038cb289..d7f156b1e 100644
--- a/guava/src/com/google/common/primitives/Floats.java
+++ b/guava/src/com/google/common/primitives/Floats.java
@@ -22,9 +22,9 @@ import static com.google.common.base.Strings.lenientFormat;
import static java.lang.Float.NEGATIVE_INFINITY;
import static java.lang.Float.POSITIVE_INFINITY;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
import java.util.AbstractList;
@@ -250,7 +250,6 @@ public final class Floats extends FloatsMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static float constrainToRange(float value, float min, float max) {
// avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984
// Reject NaN by testing for the good case (min <= max) instead of the bad (min > max).
@@ -315,7 +314,6 @@ public final class Floats extends FloatsMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Float> stringConverter() {
return FloatConverter.INSTANCE;
}
@@ -465,6 +463,56 @@ public final class Floats extends FloatsMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Floats.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(float[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Floats.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(float[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code float}
* value in the manner of {@link Number#floatValue}.
*
@@ -504,6 +552,8 @@ public final class Floats extends FloatsMethodsForWeb {
* <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
* is used as a parameter to any of its methods.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
@@ -660,7 +710,7 @@ public final class Floats extends FloatsMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // regular expressions
@CheckForNull
public static Float tryParse(String string) {
diff --git a/guava/src/com/google/common/primitives/ImmutableDoubleArray.java b/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
index 9731c1131..7ee8cfc73 100644
--- a/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
+++ b/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
@@ -17,11 +17,9 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.AbstractList;
@@ -85,7 +83,6 @@ import javax.annotation.CheckForNull;
*
* @since 22.0
*/
-@Beta
@GwtCompatible
@Immutable
@ElementTypesAreNonnullByDefault
@@ -210,7 +207,6 @@ public final class ImmutableDoubleArray implements Serializable {
* A builder for {@link ImmutableDoubleArray} instances; obtained using {@link
* ImmutableDoubleArray#builder}.
*/
- @CanIgnoreReturnValue
public static final class Builder {
private double[] array;
private int count = 0; // <= array.length
@@ -223,6 +219,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code value} to the end of the values the built {@link ImmutableDoubleArray} will
* contain.
*/
+ @CanIgnoreReturnValue
public Builder add(double value) {
ensureRoomFor(1);
array[count] = value;
@@ -234,6 +231,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(double[] values) {
ensureRoomFor(values.length);
System.arraycopy(values, 0, array, count, values.length);
@@ -245,6 +243,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Iterable<Double> values) {
if (values instanceof Collection) {
return addAll((Collection<Double>) values);
@@ -259,6 +258,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Collection<Double> values) {
ensureRoomFor(values.size());
for (Double value : values) {
@@ -271,6 +271,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends all values from {@code stream}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(DoubleStream stream) {
Spliterator.OfDouble spliterator = stream.spliterator();
long size = spliterator.getExactSizeIfKnown();
@@ -285,6 +286,7 @@ public final class ImmutableDoubleArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableDoubleArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(ImmutableDoubleArray values) {
ensureRoomFor(values.length());
System.arraycopy(values.array, values.start, array, count, values.length());
@@ -323,7 +325,6 @@ public final class ImmutableDoubleArray implements Serializable {
* no data is copied as part of this step, but this may occupy more memory than strictly
* necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
*/
- @CheckReturnValue
public ImmutableDoubleArray build() {
return count == 0 ? EMPTY : new ImmutableDoubleArray(array, 0, count);
}
diff --git a/guava/src/com/google/common/primitives/ImmutableIntArray.java b/guava/src/com/google/common/primitives/ImmutableIntArray.java
index cc3c67144..f21afe222 100644
--- a/guava/src/com/google/common/primitives/ImmutableIntArray.java
+++ b/guava/src/com/google/common/primitives/ImmutableIntArray.java
@@ -17,11 +17,9 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.AbstractList;
@@ -85,7 +83,6 @@ import javax.annotation.CheckForNull;
*
* @since 22.0
*/
-@Beta
@GwtCompatible
@Immutable
@ElementTypesAreNonnullByDefault
@@ -207,7 +204,6 @@ public final class ImmutableIntArray implements Serializable {
* A builder for {@link ImmutableIntArray} instances; obtained using {@link
* ImmutableIntArray#builder}.
*/
- @CanIgnoreReturnValue
public static final class Builder {
private int[] array;
private int count = 0; // <= array.length
@@ -220,6 +216,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code value} to the end of the values the built {@link ImmutableIntArray} will
* contain.
*/
+ @CanIgnoreReturnValue
public Builder add(int value) {
ensureRoomFor(1);
array[count] = value;
@@ -231,6 +228,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(int[] values) {
ensureRoomFor(values.length);
System.arraycopy(values, 0, array, count, values.length);
@@ -242,6 +240,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Iterable<Integer> values) {
if (values instanceof Collection) {
return addAll((Collection<Integer>) values);
@@ -256,6 +255,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Collection<Integer> values) {
ensureRoomFor(values.size());
for (Integer value : values) {
@@ -268,6 +268,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends all values from {@code stream}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(IntStream stream) {
Spliterator.OfInt spliterator = stream.spliterator();
long size = spliterator.getExactSizeIfKnown();
@@ -282,6 +283,7 @@ public final class ImmutableIntArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableIntArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(ImmutableIntArray values) {
ensureRoomFor(values.length());
System.arraycopy(values.array, values.start, array, count, values.length());
@@ -320,7 +322,6 @@ public final class ImmutableIntArray implements Serializable {
* no data is copied as part of this step, but this may occupy more memory than strictly
* necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
*/
- @CheckReturnValue
public ImmutableIntArray build() {
return count == 0 ? EMPTY : new ImmutableIntArray(array, 0, count);
}
diff --git a/guava/src/com/google/common/primitives/ImmutableLongArray.java b/guava/src/com/google/common/primitives/ImmutableLongArray.java
index c8f70375d..3ff21f16c 100644
--- a/guava/src/com/google/common/primitives/ImmutableLongArray.java
+++ b/guava/src/com/google/common/primitives/ImmutableLongArray.java
@@ -17,11 +17,9 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.AbstractList;
@@ -85,7 +83,6 @@ import javax.annotation.CheckForNull;
*
* @since 22.0
*/
-@Beta
@GwtCompatible
@Immutable
@ElementTypesAreNonnullByDefault
@@ -209,7 +206,6 @@ public final class ImmutableLongArray implements Serializable {
* A builder for {@link ImmutableLongArray} instances; obtained using {@link
* ImmutableLongArray#builder}.
*/
- @CanIgnoreReturnValue
public static final class Builder {
private long[] array;
private int count = 0; // <= array.length
@@ -222,6 +218,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code value} to the end of the values the built {@link ImmutableLongArray} will
* contain.
*/
+ @CanIgnoreReturnValue
public Builder add(long value) {
ensureRoomFor(1);
array[count] = value;
@@ -233,6 +230,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(long[] values) {
ensureRoomFor(values.length);
System.arraycopy(values, 0, array, count, values.length);
@@ -244,6 +242,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Iterable<Long> values) {
if (values instanceof Collection) {
return addAll((Collection<Long>) values);
@@ -258,6 +257,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(Collection<Long> values) {
ensureRoomFor(values.size());
for (Long value : values) {
@@ -270,6 +270,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends all values from {@code stream}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(LongStream stream) {
Spliterator.OfLong spliterator = stream.spliterator();
long size = spliterator.getExactSizeIfKnown();
@@ -284,6 +285,7 @@ public final class ImmutableLongArray implements Serializable {
* Appends {@code values}, in order, to the end of the values the built {@link
* ImmutableLongArray} will contain.
*/
+ @CanIgnoreReturnValue
public Builder addAll(ImmutableLongArray values) {
ensureRoomFor(values.length());
System.arraycopy(values.array, values.start, array, count, values.length());
@@ -322,7 +324,6 @@ public final class ImmutableLongArray implements Serializable {
* no data is copied as part of this step, but this may occupy more memory than strictly
* necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
*/
- @CheckReturnValue
public ImmutableLongArray build() {
return count == 0 ? EMPTY : new ImmutableLongArray(array, 0, count);
}
diff --git a/guava/src/com/google/common/primitives/Ints.java b/guava/src/com/google/common/primitives/Ints.java
index b63b0f946..4eaa5a6a4 100644
--- a/guava/src/com/google/common/primitives/Ints.java
+++ b/guava/src/com/google/common/primitives/Ints.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Converter;
@@ -269,7 +268,6 @@ public final class Ints extends IntsMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static int constrainToRange(int value, int min, int max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return Math.min(Math.max(value, min), max);
@@ -374,7 +372,6 @@ public final class Ints extends IntsMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Integer> stringConverter() {
return IntConverter.INSTANCE;
}
@@ -513,6 +510,82 @@ public final class Ints extends IntsMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(int[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(int[] array, int distance, int fromIndex, int toIndex) {
+ // There are several well-known algorithms for rotating part of an array (or, equivalently,
+ // exchanging two blocks of memory). This classic text by Gries and Mills mentions several:
+ // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf.
+ // (1) "Reversal", the one we have here.
+ // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0]
+ // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0].
+ // (All indices taken mod n.) If d and n are mutually prime, all elements will have been
+ // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc,
+ // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles
+ // in all.
+ // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a
+ // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we
+ // imagine a line separating the first block from the second, we can proceed by exchanging
+ // the smaller of these blocks with the far end of the other one. That leaves us with a
+ // smaller version of the same problem.
+ // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]:
+ // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de]
+ // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]:
+ // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]:
+ // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done.
+ // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each
+ // array slot is read and written exactly once. However, it can have very poor memory locality:
+ // benchmarking shows it can take 7 times longer than the other two in some cases. The other two
+ // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about
+ // twice as many reads and writes. But benchmarking shows that they usually perform better than
+ // Dolphin. Reversal is about as good as Successive on average, and it is much simpler,
+ // especially since we already have a `reverse` method.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code int} value
* in the manner of {@link Number#intValue}.
*
@@ -549,6 +622,8 @@ public final class Ints extends IntsMethodsForWeb {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray}
* instead, which has an {@link ImmutableIntArray#asList asList} view.
*
@@ -713,7 +788,6 @@ public final class Ints extends IntsMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 11.0
*/
- @Beta
@CheckForNull
public static Integer tryParse(String string) {
return tryParse(string, 10);
@@ -739,7 +813,6 @@ public final class Ints extends IntsMethodsForWeb {
* @throws NullPointerException if {@code string} is {@code null}
* @since 19.0
*/
- @Beta
@CheckForNull
public static Integer tryParse(String string, int radix) {
Long result = Longs.tryParse(string, radix);
diff --git a/guava/src/com/google/common/primitives/Longs.java b/guava/src/com/google/common/primitives/Longs.java
index 98c055e27..8369973cc 100644
--- a/guava/src/com/google/common/primitives/Longs.java
+++ b/guava/src/com/google/common/primitives/Longs.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
@@ -236,7 +235,6 @@ public final class Longs {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static long constrainToRange(long value, long min, long max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return Math.min(Math.max(value, min), max);
@@ -248,13 +246,15 @@ public final class Longs {
*
* @param arrays zero or more {@code long} arrays
* @return a single array containing all the values from the source arrays, in order
+ * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
+ * in an {@code int}
*/
public static long[] concat(long[]... arrays) {
- int length = 0;
+ long length = 0;
for (long[] array : arrays) {
length += array.length;
}
- long[] result = new long[length];
+ long[] result = new long[checkNoOverflow(length)];
int pos = 0;
for (long[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
@@ -263,6 +263,14 @@ public final class Longs {
return result;
}
+ private static int checkNoOverflow(long result) {
+ checkArgument(
+ result == (int) result,
+ "the total number of elements (%s) in the arrays must fit in an int",
+ result);
+ return (int) result;
+ }
+
/**
* Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
* {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code
@@ -363,7 +371,6 @@ public final class Longs {
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
- @Beta
@CheckForNull
public static Long tryParse(String string) {
return tryParse(string, 10);
@@ -380,7 +387,7 @@ public final class Longs {
* <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
* the change to {@link Long#parseLong(String, int)} for that version.
*
- * @param string the string representation of an long value
+ * @param string the string representation of a long value
* @param radix the radix to use when parsing
* @return the long value represented by {@code string} using {@code radix}, or {@code null} if
* {@code string} has a length of zero or cannot be parsed as a long value
@@ -389,7 +396,6 @@ public final class Longs {
* @throws NullPointerException if {@code string} is {@code null}
* @since 19.0
*/
- @Beta
@CheckForNull
public static Long tryParse(String string, int radix) {
if (checkNotNull(string).isEmpty()) {
@@ -469,7 +475,6 @@ public final class Longs {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Long> stringConverter() {
return LongConverter.INSTANCE;
}
@@ -609,6 +614,56 @@ public final class Longs {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(long[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(long[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code long} value
* in the manner of {@link Number#longValue}.
*
@@ -645,6 +700,8 @@ public final class Longs {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
* instead, which has an {@link ImmutableLongArray#asList asList} view.
*
diff --git a/guava/src/com/google/common/primitives/ParametricNullness.java b/guava/src/com/google/common/primitives/ParametricNullness.java
index 4289b9b16..c40ea499d 100644
--- a/guava/src/com/google/common/primitives/ParametricNullness.java
+++ b/guava/src/com/google/common/primitives/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/primitives/Platform.java b/guava/src/com/google/common/primitives/Platform.java
deleted file mode 100644
index ca3168922..000000000
--- a/guava/src/com/google/common/primitives/Platform.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2019 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.primitives;
-
-import com.google.common.annotations.GwtCompatible;
-
-/** Methods factored out so that they can be emulated differently in GWT. */
-@GwtCompatible(emulated = true)
-@ElementTypesAreNonnullByDefault
-final class Platform {
- private static final java.util.logging.Logger logger =
- java.util.logging.Logger.getLogger(Platform.class.getName());
-
- static void checkGwtRpcEnabled() {
- String propertyName = "guava.gwt.emergency_reenable_rpc";
-
- if (!Boolean.parseBoolean(System.getProperty(propertyName, "false"))) {
- throw new UnsupportedOperationException(
- com.google.common.base.Strings.lenientFormat(
- "We are removing GWT-RPC support for Guava types. You can temporarily reenable"
- + " support by setting the system property %s to true. For more about system"
- + " properties, see %s. For more about Guava's GWT-RPC support, see %s.",
- propertyName,
- "https://stackoverflow.com/q/5189914/28465",
- "https://groups.google.com/d/msg/guava-announce/zHZTFg7YF3o/rQNnwdHeEwAJ"));
- }
- logger.log(
- java.util.logging.Level.WARNING,
- "Later in 2020, we will remove GWT-RPC support for Guava types. You are seeing this"
- + " warning because you are sending a Guava type over GWT-RPC, which will break. You"
- + " can identify which type by looking at the class name in the attached stack trace.",
- new Throwable());
- }
-
- private Platform() {}
-}
diff --git a/guava/src/com/google/common/primitives/Primitives.java b/guava/src/com/google/common/primitives/Primitives.java
index 7ceed0365..cfd1eac46 100644
--- a/guava/src/com/google/common/primitives/Primitives.java
+++ b/guava/src/com/google/common/primitives/Primitives.java
@@ -16,7 +16,7 @@ package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.GwtCompatible;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -29,7 +29,7 @@ import java.util.Set;
* @author Kevin Bourrillion
* @since 1.0
*/
-@GwtIncompatible
+@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Primitives {
private Primitives() {}
diff --git a/guava/src/com/google/common/primitives/Shorts.java b/guava/src/com/google/common/primitives/Shorts.java
index 09e0f7cfc..85ffd3ba8 100644
--- a/guava/src/com/google/common/primitives/Shorts.java
+++ b/guava/src/com/google/common/primitives/Shorts.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Converter;
@@ -266,7 +265,6 @@ public final class Shorts extends ShortsMethodsForWeb {
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
- @Beta
public static short constrainToRange(short value, short min, short max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return value < min ? min : value < max ? value : max;
@@ -372,7 +370,6 @@ public final class Shorts extends ShortsMethodsForWeb {
*
* @since 16.0
*/
- @Beta
public static Converter<String, Short> stringConverter() {
return ShortConverter.INSTANCE;
}
@@ -513,6 +510,56 @@ public final class Shorts extends ShortsMethodsForWeb {
}
/**
+ * Performs a right rotation of {@code array} of "distance" places, so that the first element is
+ * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
+ * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Shorts.asList(array),
+ * distance)}, but is considerably faster and avoids allocation and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @since 32.0.0
+ */
+ public static void rotate(short[] array, int distance) {
+ rotate(array, distance, 0, array.length);
+ }
+
+ /**
+ * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
+ * toIndex} exclusive. This is equivalent to {@code
+ * Collections.rotate(Shorts.asList(array).subList(fromIndex, toIndex), distance)}, but is
+ * considerably faster and avoids allocations and garbage collection.
+ *
+ * <p>The provided "distance" may be negative, which will rotate left.
+ *
+ * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
+ * {@code toIndex > fromIndex}
+ * @since 32.0.0
+ */
+ public static void rotate(short[] array, int distance, int fromIndex, int toIndex) {
+ // See Ints.rotate for more details about possible algorithms here.
+ checkNotNull(array);
+ checkPositionIndexes(fromIndex, toIndex, array.length);
+ if (array.length <= 1) {
+ return;
+ }
+
+ int length = toIndex - fromIndex;
+ // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
+ // places left to rotate.
+ int m = -distance % length;
+ m = (m < 0) ? m + length : m;
+ // The current index of what will become the first element of the rotated section.
+ int newFirstIndex = m + fromIndex;
+ if (newFirstIndex == fromIndex) {
+ return;
+ }
+
+ reverse(array, fromIndex, newFirstIndex);
+ reverse(array, newFirstIndex, toIndex);
+ reverse(array, fromIndex, toIndex);
+ }
+
+ /**
* Returns an array containing each value of {@code collection}, converted to a {@code short}
* value in the manner of {@link Number#shortValue}.
*
@@ -549,6 +596,8 @@ public final class Shorts extends ShortsMethodsForWeb {
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
+ * <p>The returned list is serializable.
+ *
* @param backingArray the array to back the list
* @return a list view of the array
*/
diff --git a/guava/src/com/google/common/primitives/UnsignedBytes.java b/guava/src/com/google/common/primitives/UnsignedBytes.java
index db4f489e4..0490c6714 100644
--- a/guava/src/com/google/common/primitives/UnsignedBytes.java
+++ b/guava/src/com/google/common/primitives/UnsignedBytes.java
@@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.nio.ByteOrder;
@@ -43,6 +43,7 @@ import sun.misc.Unsafe;
* @author Louis Wasserman
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class UnsignedBytes {
@@ -167,7 +168,6 @@ public final class UnsignedBytes {
*
* @since 13.0
*/
- @Beta
public static String toString(byte x) {
return toString(x, 10);
}
@@ -182,7 +182,6 @@ public final class UnsignedBytes {
* and {@link Character#MAX_RADIX}.
* @since 13.0
*/
- @Beta
public static String toString(byte x, int radix) {
checkArgument(
radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
@@ -201,7 +200,6 @@ public final class UnsignedBytes {
* Byte#parseByte(String)})
* @since 13.0
*/
- @Beta
@CanIgnoreReturnValue
public static byte parseUnsignedByte(String string) {
return parseUnsignedByte(string, 10);
@@ -219,7 +217,6 @@ public final class UnsignedBytes {
* Byte#parseByte(String)})
* @since 13.0
*/
- @Beta
@CanIgnoreReturnValue
public static byte parseUnsignedByte(String string, int radix) {
int parse = Integer.parseInt(checkNotNull(string), radix);
diff --git a/guava/src/com/google/common/primitives/UnsignedInteger.java b/guava/src/com/google/common/primitives/UnsignedInteger.java
index 0b30cef3f..52b05e4e7 100644
--- a/guava/src/com/google/common/primitives/UnsignedInteger.java
+++ b/guava/src/com/google/common/primitives/UnsignedInteger.java
@@ -22,6 +22,7 @@ import static com.google.common.primitives.UnsignedInts.toLong;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.math.BigInteger;
import javax.annotation.CheckForNull;
@@ -143,6 +144,7 @@ public final class UnsignedInteger extends Number implements Comparable<Unsigned
*
* @since 14.0
*/
+ @J2ktIncompatible
@GwtIncompatible // Does not truncate correctly
public UnsignedInteger times(UnsignedInteger val) {
// TODO(lowasser): make this GWT-compatible
diff --git a/guava/src/com/google/common/primitives/UnsignedInts.java b/guava/src/com/google/common/primitives/UnsignedInts.java
index ec6474e20..0d556bab4 100644
--- a/guava/src/com/google/common/primitives/UnsignedInts.java
+++ b/guava/src/com/google/common/primitives/UnsignedInts.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
@@ -45,7 +44,6 @@ import java.util.Comparator;
* @author Louis Wasserman
* @since 11.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class UnsignedInts {
diff --git a/guava/src/com/google/common/primitives/UnsignedLongs.java b/guava/src/com/google/common/primitives/UnsignedLongs.java
index 31c51cc34..04631ee9d 100644
--- a/guava/src/com/google/common/primitives/UnsignedLongs.java
+++ b/guava/src/com/google/common/primitives/UnsignedLongs.java
@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.math.BigInteger;
@@ -48,7 +47,6 @@ import java.util.Comparator;
* @author Colin Evans
* @since 10.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class UnsignedLongs {
diff --git a/guava/src/com/google/common/primitives/package-info.java b/guava/src/com/google/common/primitives/package-info.java
index 9504fa79b..ad38c1113 100644
--- a/guava/src/com/google/common/primitives/package-info.java
+++ b/guava/src/com/google/common/primitives/package-info.java
@@ -13,10 +13,10 @@
*/
/**
- * Static utilities for working with the eight primitive types and {@code void}, and value types for
- * treating them as unsigned.
+ * Static utilities for the eight primitive types and {@code void}, and value types for treating
+ * them as unsigned or storing them in immutable arrays.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*
* <p>See the Guava User Guide article on <a
@@ -24,40 +24,43 @@
*
* <h2>Contents</h2>
*
- * <h3>General static utilities</h3>
+ * <h3>Value types</h3>
*
* <ul>
- * <li>{@link com.google.common.primitives.Primitives}
+ * <li>{@link ImmutableDoubleArray}
+ * <li>{@link ImmutableIntArray}
+ * <li>{@link ImmutableLongrray}
+ * <li>{@link UnsignedInteger}
+ * <li>{@link UnsignedLong}
* </ul>
*
* <h3>Per-type static utilities</h3>
*
* <ul>
- * <li>{@link com.google.common.primitives.Booleans}
- * <li>{@link com.google.common.primitives.Bytes}
+ * <li>{@link Booleans}
+ * <li>{@link Bytes}
* <ul>
- * <li>{@link com.google.common.primitives.SignedBytes}
- * <li>{@link com.google.common.primitives.UnsignedBytes}
+ * <li>{@link SignedBytes}
+ * <li>{@link UnsignedBytes}
* </ul>
- * <li>{@link com.google.common.primitives.Chars}
- * <li>{@link com.google.common.primitives.Doubles}
- * <li>{@link com.google.common.primitives.Floats}
- * <li>{@link com.google.common.primitives.Ints}
+ * <li>{@link Chars}
+ * <li>{@link Doubles}
+ * <li>{@link Floats}
+ * <li>{@link Ints}
* <ul>
- * <li>{@link com.google.common.primitives.UnsignedInts}
+ * <li>{@link UnsignedInts}
* </ul>
- * <li>{@link com.google.common.primitives.Longs}
+ * <li>{@link Longs}
* <ul>
- * <li>{@link com.google.common.primitives.UnsignedLongs}
+ * <li>{@link UnsignedLongs}
* </ul>
- * <li>{@link com.google.common.primitives.Shorts}
+ * <li>{@link Shorts}
* </ul>
*
- * <h3>Value types</h3>
+ * <h3>General static utilities</h3>
*
* <ul>
- * <li>{@link com.google.common.primitives.UnsignedInteger}
- * <li>{@link com.google.common.primitives.UnsignedLong}
+ * <li>{@link Primitives}
* </ul>
*/
@ParametersAreNonnullByDefault
diff --git a/guava/src/com/google/common/reflect/IgnoreJRERequirement.java b/guava/src/com/google/common/reflect/IgnoreJRERequirement.java
new file mode 100644
index 000000000..8b03ca332
--- /dev/null
+++ b/guava/src/com/google/common/reflect/IgnoreJRERequirement.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019 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.reflect;
+
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Target;
+
+/**
+ * Disables Animal Sniffer's checking of compatibility with older versions of Java/Android.
+ *
+ * <p>Each package's copy of this annotation needs to be listed in our {@code pom.xml}.
+ */
+@Target({METHOD, CONSTRUCTOR, TYPE})
+@ElementTypesAreNonnullByDefault
+@interface IgnoreJRERequirement {}
diff --git a/guava/src/com/google/common/reflect/Invokable.java b/guava/src/com/google/common/reflect/Invokable.java
index e6d3b6c53..29f4a4ed9 100644
--- a/guava/src/com/google/common/reflect/Invokable.java
+++ b/guava/src/com/google/common/reflect/Invokable.java
@@ -16,7 +16,6 @@ package com.google.common.reflect;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Annotation;
@@ -63,7 +62,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 14.0 (no longer implements {@link AccessibleObject} or {@code GenericDeclaration} since
* 31.0)
*/
-@Beta
@ElementTypesAreNonnullByDefault
public abstract class Invokable<T, R> implements AnnotatedElement, Member {
private final AccessibleObject accessibleObject;
@@ -273,10 +271,12 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
* of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden {@code
* this} parameter of the enclosing class is excluded from the returned parameters.
*/
+ @IgnoreJRERequirement
public final ImmutableList<Parameter> getParameters() {
Type[] parameterTypes = getGenericParameterTypes();
Annotation[][] annotations = getParameterAnnotations();
- AnnotatedType[] annotatedTypes = getAnnotatedParameterTypes();
+ @Nullable Object[] annotatedTypes =
+ ANNOTATED_TYPE_EXISTS ? getAnnotatedParameterTypes() : new Object[parameterTypes.length];
ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
for (int i = 0; i < parameterTypes.length; i++) {
builder.add(
@@ -341,6 +341,8 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
abstract Type[] getGenericParameterTypes();
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
abstract AnnotatedType[] getAnnotatedParameterTypes();
/** This should never return a type that's not a subtype of Throwable. */
@@ -350,6 +352,15 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
abstract Type getGenericReturnType();
+ /**
+ * Returns the {@link AnnotatedType} for the return type.
+ *
+ * <p>This method will fail if run under an Android VM.
+ *
+ * @since 14.0 for guava-jre (available since 32.0.0 in guava-android)
+ */
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
public abstract AnnotatedType getAnnotatedReturnType();
static class MethodInvokable<T> extends Invokable<T, Object> {
@@ -379,11 +390,15 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
}
@Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
AnnotatedType[] getAnnotatedParameterTypes() {
return method.getAnnotatedParameterTypes();
}
@Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker", "DoNotCall"})
+ @IgnoreJRERequirement
public AnnotatedType getAnnotatedReturnType() {
return method.getAnnotatedReturnType();
}
@@ -466,11 +481,15 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
}
@Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
AnnotatedType[] getAnnotatedParameterTypes() {
return constructor.getAnnotatedParameterTypes();
}
@Override
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker", "DoNotCall"})
+ @IgnoreJRERequirement
public AnnotatedType getAnnotatedReturnType() {
return constructor.getAnnotatedReturnType();
}
@@ -538,4 +557,15 @@ public abstract class Invokable<T, R> implements AnnotatedElement, Member {
}
}
}
+
+ private static final boolean ANNOTATED_TYPE_EXISTS = initAnnotatedTypeExists();
+
+ private static boolean initAnnotatedTypeExists() {
+ try {
+ Class.forName("java.lang.reflect.AnnotatedType");
+ } catch (ClassNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
}
diff --git a/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java b/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
index 9542e0a7e..7690d2eef 100644
--- a/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
+++ b/guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
@@ -27,47 +27,45 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A mutable type-to-instance map. See also {@link ImmutableTypeToInstanceMap}.
*
- * <p>This implementation <i>does</i> support null values, despite how it is annotated; see
- * discussion at {@link TypeToInstanceMap}.
- *
* @author Ben Yu
* @since 13.0
*/
@ElementTypesAreNonnullByDefault
-public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B>
- implements TypeToInstanceMap<B> {
+public final class MutableTypeToInstanceMap<B extends @Nullable Object>
+ extends ForwardingMap<TypeToken<? extends @NonNull B>, B> implements TypeToInstanceMap<B> {
- private final Map<TypeToken<? extends B>, B> backingMap = Maps.newHashMap();
+ private final Map<TypeToken<? extends @NonNull B>, B> backingMap = Maps.newHashMap();
@Override
@CheckForNull
- public <T extends B> T getInstance(Class<T> type) {
+ public <T extends @NonNull B> T getInstance(Class<T> type) {
return trustedGet(TypeToken.of(type));
}
@Override
@CheckForNull
- public <T extends B> T getInstance(TypeToken<T> type) {
+ public <T extends @NonNull B> T getInstance(TypeToken<T> type) {
return trustedGet(type.rejectTypeVariables());
}
@Override
@CanIgnoreReturnValue
@CheckForNull
- public <T extends B> T putInstance(Class<T> type, T value) {
+ public <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value) {
return trustedPut(TypeToken.of(type), value);
}
@Override
@CanIgnoreReturnValue
@CheckForNull
- public <T extends B> T putInstance(TypeToken<T> type, T value) {
- return trustedPut(type.rejectTypeVariables(), value);
+ public <T extends B> T putInstance(TypeToken<@NonNull T> type, @ParametricNullness T value) {
+ return this.<T>trustedPut(type.rejectTypeVariables(), value);
}
/**
@@ -81,7 +79,7 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
- public B put(TypeToken<? extends B> key, B value) {
+ public B put(TypeToken<? extends @NonNull B> key, @ParametricNullness B value) {
throw new UnsupportedOperationException("Please use putInstance() instead.");
}
@@ -94,37 +92,39 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
- public void putAll(Map<? extends TypeToken<? extends B>, ? extends B> map) {
+ public void putAll(Map<? extends TypeToken<? extends @NonNull B>, ? extends B> map) {
throw new UnsupportedOperationException("Please use putInstance() instead.");
}
@Override
- public Set<Entry<TypeToken<? extends B>, B>> entrySet() {
+ public Set<Entry<TypeToken<? extends @NonNull B>, B>> entrySet() {
return UnmodifiableEntry.transformEntries(super.entrySet());
}
@Override
- protected Map<TypeToken<? extends B>, B> delegate() {
+ protected Map<TypeToken<? extends @NonNull B>, B> delegate() {
return backingMap;
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@CheckForNull
- private <T extends B> T trustedPut(TypeToken<T> type, T value) {
+ private <T extends B> T trustedPut(TypeToken<@NonNull T> type, @ParametricNullness T value) {
return (T) backingMap.put(type, value);
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@CheckForNull
- private <T extends B> T trustedGet(TypeToken<T> type) {
+ private <T extends @NonNull B> T trustedGet(TypeToken<T> type) {
return (T) backingMap.get(type);
}
- private static final class UnmodifiableEntry<K, V> extends ForwardingMapEntry<K, V> {
+ private static final class UnmodifiableEntry<K, V extends @Nullable Object>
+ extends ForwardingMapEntry<K, V> {
private final Entry<K, V> delegate;
- static <K, V> Set<Entry<K, V>> transformEntries(Set<Entry<K, V>> entries) {
+ static <K, V extends @Nullable Object> Set<Entry<K, V>> transformEntries(
+ Set<Entry<K, V>> entries) {
return new ForwardingSet<Map.Entry<K, V>>() {
@Override
protected Set<Entry<K, V>> delegate() {
@@ -157,7 +157,8 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
};
}
- private static <K, V> Iterator<Entry<K, V>> transformEntries(Iterator<Entry<K, V>> entries) {
+ private static <K, V extends @Nullable Object> Iterator<Entry<K, V>> transformEntries(
+ Iterator<Entry<K, V>> entries) {
return Iterators.transform(entries, UnmodifiableEntry::new);
}
@@ -171,7 +172,8 @@ public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<?
}
@Override
- public V setValue(V value) {
+ @ParametricNullness
+ public V setValue(@ParametricNullness V value) {
throw new UnsupportedOperationException();
}
}
diff --git a/guava/src/com/google/common/reflect/Parameter.java b/guava/src/com/google/common/reflect/Parameter.java
index c3c46eca9..c80d18571 100644
--- a/guava/src/com/google/common/reflect/Parameter.java
+++ b/guava/src/com/google/common/reflect/Parameter.java
@@ -15,8 +15,8 @@
package com.google.common.reflect;
import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import java.lang.annotation.Annotation;
@@ -28,14 +28,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Represents a method or constructor parameter.
*
- * <p><b>Note:</b> Since Java 8 introduced {@link java.lang.reflect.Parameter} to represent method
- * and constructor parameters, this class is no longer necessary. We intend to deprecate it in a
- * future version.
- *
* @author Ben Yu
* @since 14.0
*/
-@Beta
@ElementTypesAreNonnullByDefault
public final class Parameter implements AnnotatedElement {
@@ -43,14 +38,22 @@ public final class Parameter implements AnnotatedElement {
private final int position;
private final TypeToken<?> type;
private final ImmutableList<Annotation> annotations;
- private final AnnotatedType annotatedType;
+
+ /**
+ * An {@link AnnotatedType} instance, or {@code null} under Android VMs (possible only when using
+ * the Android flavor of Guava). The field is declared with a type of {@code Object} to avoid
+ * compatibility problems on Android VMs. The corresponding accessor method, however, can have the
+ * more specific return type as long as users are careful to guard calls to it with version checks
+ * or reflection: Android VMs ignore the types of elements that aren't used.
+ */
+ private final @Nullable Object annotatedType;
Parameter(
Invokable<?, ?> declaration,
int position,
TypeToken<?> type,
Annotation[] annotations,
- AnnotatedType annotatedType) {
+ @Nullable Object annotatedType) {
this.declaration = declaration;
this.position = position;
this.type = type;
@@ -91,21 +94,18 @@ public final class Parameter implements AnnotatedElement {
}
/** @since 18.0 */
- // @Override on JDK8
@Override
public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
return getDeclaredAnnotationsByType(annotationType);
}
/** @since 18.0 */
- // @Override on JDK8
@Override
public Annotation[] getDeclaredAnnotations() {
return annotations.toArray(new Annotation[0]);
}
/** @since 18.0 */
- // @Override on JDK8
@Override
@CheckForNull
public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationType) {
@@ -114,7 +114,6 @@ public final class Parameter implements AnnotatedElement {
}
/** @since 18.0 */
- // @Override on JDK8
@Override
public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationType) {
@Nullable
@@ -124,10 +123,17 @@ public final class Parameter implements AnnotatedElement {
return cast;
}
- /** @since 25.1 */
- // @Override on JDK8
+ /**
+ * Returns the {@link AnnotatedType} of the parameter.
+ *
+ * <p>This method will fail if run under an Android VM.
+ *
+ * @since 25.1 for guava-jre (available since 32.0.0 in guava-android)
+ */
+ @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"})
+ @IgnoreJRERequirement
public AnnotatedType getAnnotatedType() {
- return annotatedType;
+ return requireNonNull((AnnotatedType) annotatedType);
}
@Override
diff --git a/guava/src/com/google/common/reflect/ParametricNullness.java b/guava/src/com/google/common/reflect/ParametricNullness.java
index b6331ac26..372a53bb6 100644
--- a/guava/src/com/google/common/reflect/ParametricNullness.java
+++ b/guava/src/com/google/common/reflect/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/reflect/Reflection.java b/guava/src/com/google/common/reflect/Reflection.java
index 954496348..09e966d12 100644
--- a/guava/src/com/google/common/reflect/Reflection.java
+++ b/guava/src/com/google/common/reflect/Reflection.java
@@ -54,7 +54,7 @@ public final class Reflection {
*
* <p>WARNING: Normally it's a smell if a class needs to be explicitly initialized, because static
* state hurts system maintainability and testability. In cases when you have no choice while
- * inter-operating with a legacy framework, this method helps to keep the code less ugly.
+ * interoperating with a legacy framework, this method helps to keep the code less ugly.
*
* @throws ExceptionInInitializerError if an exception is thrown during initialization of a class
*/
diff --git a/guava/src/com/google/common/reflect/TypeResolver.java b/guava/src/com/google/common/reflect/TypeResolver.java
index 32517eb87..e9c3a1d19 100644
--- a/guava/src/com/google/common/reflect/TypeResolver.java
+++ b/guava/src/com/google/common/reflect/TypeResolver.java
@@ -42,7 +42,7 @@ import javax.annotation.CheckForNull;
*
* <p>Note that usually type mappings are already implied by the static type hierarchy (for example,
* the {@code E} type variable declared by class {@code List} naturally maps to {@code String} in
- * the context of {@code class MyStringList implements List<String>}. In such case, prefer to use
+ * the context of {@code class MyStringList implements List<String>}). In such case, prefer to use
* {@link TypeToken#resolveType} since it's simpler and more type safe. This class should only be
* used when the type mapping isn't implied by the static type hierarchy, but provided through other
* means such as an annotation or external configuration file.
@@ -426,7 +426,7 @@ public final class TypeResolver {
if (var.equalsType(t)) {
// cycle detected, remove the entire cycle from the mapping so that
// each type variable resolves deterministically to itself.
- // Otherwise, a F -> T cycle will end up resolving both F and T
+ // Otherwise, an F -> T cycle will end up resolving both F and T
// nondeterministically to either F or T.
for (Type x = arg; x != null; x = mappings.remove(TypeVariableKey.forLookup(x))) {}
return;
diff --git a/guava/src/com/google/common/reflect/TypeToInstanceMap.java b/guava/src/com/google/common/reflect/TypeToInstanceMap.java
index 8a418df2a..fe61a2cc5 100644
--- a/guava/src/com/google/common/reflect/TypeToInstanceMap.java
+++ b/guava/src/com/google/common/reflect/TypeToInstanceMap.java
@@ -18,6 +18,8 @@ import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Map;
import javax.annotation.CheckForNull;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A map, each entry of which maps a {@link TypeToken} to an instance of that type. In addition to
@@ -34,16 +36,14 @@ import javax.annotation.CheckForNull;
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries for primitive types,
* and a primitive type and its corresponding wrapper type may map to different values.
*
- * <p>This class's support for {@code null} requires some explanation. For details, see {@link
- * ClassToInstanceMap}. Its explanation applies equally well to {@code TypeToInstanceMap}.
- *
* @param <B> the common supertype that all entries must share; often this is simply {@link Object}
* @author Ben Yu
* @since 13.0
*/
@DoNotMock("Use ImmutableTypeToInstanceMap or MutableTypeToInstanceMap")
@ElementTypesAreNonnullByDefault
-public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
+public interface TypeToInstanceMap<B extends @Nullable Object>
+ extends Map<TypeToken<? extends @NonNull B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no entry for this class
@@ -54,7 +54,7 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
* getInstance(TypeToken.of(Foo.class))}.
*/
@CheckForNull
- <T extends B> T getInstance(Class<T> type);
+ <T extends @NonNull B> T getInstance(Class<T> type);
/**
* Returns the value the specified type is mapped to, or {@code null} if no entry for this type is
@@ -62,7 +62,7 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
* may have been bound to a subtype.
*/
@CheckForNull
- <T extends B> T getInstance(TypeToken<T> type);
+ <T extends @NonNull B> T getInstance(TypeToken<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate this value with any
@@ -76,7 +76,7 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
*/
@CanIgnoreReturnValue
@CheckForNull
- <T extends B> T putInstance(Class<T> type, T value);
+ <T extends B> T putInstance(Class<@NonNull T> type, @ParametricNullness T value);
/**
* Maps the specified type to the specified value. Does <i>not</i> associate this value with any
@@ -87,5 +87,5 @@ public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
*/
@CanIgnoreReturnValue
@CheckForNull
- <T extends B> T putInstance(TypeToken<T> type, T value);
+ <T extends B> T putInstance(TypeToken<@NonNull T> type, @ParametricNullness T value);
}
diff --git a/guava/src/com/google/common/reflect/TypeToken.java b/guava/src/com/google/common/reflect/TypeToken.java
index fea1d53a2..6ac3385e8 100644
--- a/guava/src/com/google/common/reflect/TypeToken.java
+++ b/guava/src/com/google/common/reflect/TypeToken.java
@@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
@@ -32,6 +31,7 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
@@ -89,7 +89,7 @@ import javax.annotation.CheckForNull;
*
* <p>{@code TypeToken} is serializable when no type variable is contained in the type.
*
- * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class except
+ * <p>Note to Guice users: {@code TypeToken} is similar to Guice's {@code TypeLiteral} class except
* that it is serializable and offers numerous additional utility methods.
*
* @author Bob Lee
@@ -104,10 +104,10 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
private final Type runtimeType;
/** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */
- @CheckForNull private transient TypeResolver invariantTypeResolver;
+ @LazyInit @CheckForNull private transient TypeResolver invariantTypeResolver;
/** Resolver for resolving covariant types with {@link #runtimeType} as context. */
- @CheckForNull private transient TypeResolver covariantTypeResolver;
+ @LazyInit @CheckForNull private transient TypeResolver covariantTypeResolver;
/**
* Constructs a new type token of {@code T}.
@@ -590,7 +590,6 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
*
* @since 14.0
*/
- @Beta
public final Invokable<T, Object> method(Method method) {
checkArgument(
this.someRawTypeIsSubclassOf(method.getDeclaringClass()),
@@ -630,7 +629,6 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
*
* @since 14.0
*/
- @Beta
public final Invokable<T, T> constructor(Constructor<?> constructor) {
checkArgument(
constructor.getDeclaringClass() == getRawType(),
@@ -1316,7 +1314,7 @@ public abstract class TypeToken<T> extends TypeCapture<T> implements Serializabl
}
/**
- * Collects parent types from a sub type.
+ * Collects parent types from a subtype.
*
* @param <K> The type "kind". Either a TypeToken, or Class.
*/
diff --git a/guava/src/com/google/common/reflect/Types.java b/guava/src/com/google/common/reflect/Types.java
index e69b42a8e..7a1357d66 100644
--- a/guava/src/com/google/common/reflect/Types.java
+++ b/guava/src/com/google/common/reflect/Types.java
@@ -160,7 +160,7 @@ final class Types {
}
/**
- * Returns human readable string representation of {@code type}.
+ * Returns a human-readable string representation of {@code type}.
*
* <p>The format is subject to change.
*/
diff --git a/guava/src/com/google/common/reflect/package-info.java b/guava/src/com/google/common/reflect/package-info.java
index 6b6047169..1fc793e2a 100644
--- a/guava/src/com/google/common/reflect/package-info.java
+++ b/guava/src/com/google/common/reflect/package-info.java
@@ -13,8 +13,8 @@
*/
/**
- * This package contains utilities to work with Java reflection. It is a part of the open-source <a
- * href="http://github.com/google/guava">Guava</a> library.
+ * Utilities for reflection. This package is a part of the open-source <a
+ * href="https://github.com/google/guava">Guava</a> library.
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
diff --git a/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java b/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
index 76eada214..e5df53835 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
@@ -19,6 +19,7 @@ import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.MoreExecutors.rejectionPropagatingExecutor;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.util.concurrent.Platform.isInstanceOfThrowableClass;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
@@ -107,7 +108,7 @@ abstract class AbstractCatchingFuture<
+ e.getClass()
+ " without a cause");
}
- } catch (Throwable e) { // this includes cancellation exception
+ } catch (RuntimeException | Error e) { // this includes cancellation exception
throwable = e;
}
@@ -132,6 +133,7 @@ abstract class AbstractCatchingFuture<
try {
fallbackResult = doFallback(localFallback, castThrowable);
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
setException(t);
return;
} finally {
diff --git a/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java b/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
index df5b462d3..c52f9d456 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
@@ -14,9 +14,10 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
+
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Supplier;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.time.Duration;
import java.util.concurrent.Executor;
@@ -34,6 +35,7 @@ import java.util.logging.Logger;
* @since 1.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractExecutionThreadService implements Service {
private static final Logger logger =
@@ -44,49 +46,41 @@ public abstract class AbstractExecutionThreadService implements Service {
new AbstractService() {
@Override
protected final void doStart() {
- Executor executor =
- MoreExecutors.renamingDecorator(
- executor(),
- new Supplier<String>() {
- @Override
- public String get() {
- return serviceName();
- }
- });
+ Executor executor = MoreExecutors.renamingDecorator(executor(), () -> serviceName());
executor.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- startUp();
- notifyStarted();
- // If stopAsync() is called while starting we may be in the STOPPING state in
- // which case we should skip right down to shutdown.
- if (isRunning()) {
+ () -> {
+ try {
+ startUp();
+ notifyStarted();
+ // If stopAsync() is called while starting we may be in the STOPPING state in
+ // which case we should skip right down to shutdown.
+ if (isRunning()) {
+ try {
+ AbstractExecutionThreadService.this.run();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
try {
- AbstractExecutionThreadService.this.run();
- } catch (Throwable t) {
- try {
- shutDown();
- } catch (Exception ignored) {
- // TODO(lukes): if guava ever moves to java7, this would be a good
- // candidate for a suppressed exception, or maybe we could generalize
- // Closer.Suppressor
- logger.log(
- Level.WARNING,
- "Error while attempting to shut down the service after failure.",
- ignored);
- }
- notifyFailed(t);
- return;
+ shutDown();
+ } catch (Exception ignored) {
+ restoreInterruptIfIsInterruptedException(ignored);
+ // TODO(lukes): if guava ever moves to java7, this would be a good
+ // candidate for a suppressed exception, or maybe we could generalize
+ // Closer.Suppressor
+ logger.log(
+ Level.WARNING,
+ "Error while attempting to shut down the service after failure.",
+ ignored);
}
+ notifyFailed(t);
+ return;
}
-
- shutDown();
- notifyStopped();
- } catch (Throwable t) {
- notifyFailed(t);
}
+
+ shutDown();
+ notifyStopped();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -148,7 +142,6 @@ public abstract class AbstractExecutionThreadService implements Service {
* implementing {@code stopping}. Note, however, that {@code stopping} does not run at exactly the
* same times as {@code triggerShutdown}.
*/
- @Beta
protected void triggerShutdown() {}
/**
@@ -162,12 +155,7 @@ public abstract class AbstractExecutionThreadService implements Service {
* to the string returned by {@link #serviceName}
*/
protected Executor executor() {
- return new Executor() {
- @Override
- public void execute(Runnable command) {
- MoreExecutors.newThread(serviceName(), command).start();
- }
- };
+ return command -> MoreExecutors.newThread(serviceName(), command).start();
}
@Override
diff --git a/guava/src/com/google/common/util/concurrent/AbstractFuture.java b/guava/src/com/google/common/util/concurrent/AbstractFuture.java
index fc408a92d..42ec5264c 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractFuture.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractFuture.java
@@ -15,14 +15,12 @@
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedNull;
import static java.lang.Integer.toHexString;
import static java.lang.System.identityHashCode;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
@@ -159,7 +157,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
try {
helper = new UnsafeAtomicHelper();
- } catch (Throwable unsafeFailure) {
+ } catch (RuntimeException | Error unsafeFailure) {
thrownUnsafeFailure = unsafeFailure;
// catch absolutely everything and fall through to our 'SafeAtomicHelper'
// The access control checks that ARFU does means the caller class has to be AbstractFuture
@@ -172,7 +170,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
newUpdater(AbstractFuture.class, Waiter.class, "waiters"),
newUpdater(AbstractFuture.class, Listener.class, "listeners"),
newUpdater(AbstractFuture.class, Object.class, "value"));
- } catch (Throwable atomicReferenceFieldUpdaterFailure) {
+ } catch (RuntimeException | Error atomicReferenceFieldUpdaterFailure) {
// Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause
// getDeclaredField to throw a NoSuchFieldException when the field is definitely there.
// For these users fallback to a suboptimal implementation, based on synchronized. This will
@@ -357,7 +355,13 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
}
Object valueToSet = getFutureValue(future);
if (ATOMIC_HELPER.casValue(owner, this, valueToSet)) {
- complete(owner);
+ complete(
+ owner,
+ /*
+ * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so
+ * don't invoke interruptTask.
+ */
+ false);
}
}
}
@@ -401,7 +405,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
// Timed Get
// There are a few design constraints to consider
// * We want to be responsive to small timeouts, unpark() has non trivial latency overheads (I
- // have observed 12 micros on 64 bit linux systems to wake up a parked thread). So if the
+ // have observed 12 micros on 64-bit linux systems to wake up a parked thread). So if the
// timeout is small we shouldn't park(). This needs to be traded off with the cpu overhead of
// spinning, so we use SPIN_THRESHOLD_NANOS which is what AbstractQueuedSynchronizer uses for
// similar purposes.
@@ -657,12 +661,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
while (true) {
if (ATOMIC_HELPER.casValue(abstractFuture, localValue, valueToSet)) {
rValue = true;
- // We call interruptTask before calling complete(), which is consistent with
- // FutureTask
- if (mayInterruptIfRunning) {
- abstractFuture.interruptTask();
- }
- complete(abstractFuture);
+ complete(abstractFuture, mayInterruptIfRunning);
if (localValue instanceof SetFuture) {
// propagate cancellation to the future set in setfuture, this is racy, and we don't
// care if we are successful or not.
@@ -780,7 +779,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
protected boolean set(@ParametricNullness V value) {
Object valueToSet = value == null ? NULL : value;
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
- complete(this);
+ complete(this, /*callInterruptTask=*/ false);
return true;
}
return false;
@@ -805,7 +804,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
protected boolean setException(Throwable throwable) {
Object valueToSet = new Failure(checkNotNull(throwable));
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
- complete(this);
+ complete(this, /*callInterruptTask=*/ false);
return true;
}
return false;
@@ -848,7 +847,13 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
if (future.isDone()) {
Object value = getFutureValue(future);
if (ATOMIC_HELPER.casValue(this, null, value)) {
- complete(this);
+ complete(
+ this,
+ /*
+ * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so
+ * don't invoke interruptTask.
+ */
+ false);
return true;
}
return false;
@@ -859,14 +864,14 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
// since all we are doing is unpacking a completed future which should be fast.
try {
future.addListener(valueToSet, DirectExecutor.INSTANCE);
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
// addListener has thrown an exception! SetFuture.run can't throw any exceptions so this
// must have been caused by addListener itself. The most likely explanation is a
// misconfigured mock. Try to switch to Failure.
Failure failure;
try {
failure = new Failure(t);
- } catch (Throwable oomMostLikely) {
+ } catch (RuntimeException | Error oomMostLikely) {
failure = Failure.FALLBACK_INSTANCE;
}
// Note: The only way this CAS could fail is if cancel() has raced with us. That is ok.
@@ -961,7 +966,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
cancellation));
}
return new Cancellation(false, cancellation);
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
return new Failure(t);
}
}
@@ -990,7 +995,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
}
/** Unblocks all threads and runs all listeners. */
- private static void complete(AbstractFuture<?> param) {
+ private static void complete(AbstractFuture<?> param, boolean callInterruptTask) {
// Declare a "true" local variable so that the Checker Framework will infer nullness.
AbstractFuture<?> future = param;
@@ -998,6 +1003,18 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
outer:
while (true) {
future.releaseWaiters();
+ /*
+ * We call interruptTask() immediately before afterDone() so that migrating between the two
+ * can be a no-op.
+ */
+ if (callInterruptTask) {
+ future.interruptTask();
+ /*
+ * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so don't
+ * invoke interruptTask on any subsequent futures.
+ */
+ callInterruptTask = false;
+ }
// We call this before the listeners in order to avoid needing to manage a separate stack data
// structure for them. Also, some implementations rely on this running prior to listeners
// so that the cleanup work is visible to listeners.
@@ -1029,7 +1046,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
continue outer;
}
}
- // other wise the future we were trying to set is already done.
+ // otherwise the future we were trying to set is already done.
} else {
/*
* requireNonNull is safe because the listener stack never contains TOMBSTONE until after
@@ -1053,7 +1070,6 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
*
* @since 20.0
*/
- @Beta
@ForOverride
protected void afterDone() {}
@@ -1120,7 +1136,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
@CheckForNull
private Listener clearListeners(@CheckForNull Listener onto) {
// We need to
- // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that to
+ // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that
// to synchronize with us
// 2. reverse the linked list, because despite our rather clear contract, people depend on us
// executing listeners in the order they were added
@@ -1152,7 +1168,7 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
} else if (isDone()) {
addDoneString(builder);
} else {
- addPendingString(builder); // delegates to addDoneString if future completes mid-way
+ addPendingString(builder); // delegates to addDoneString if future completes midway
}
return builder.append("]").toString();
}
@@ -1280,10 +1296,10 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
}
private abstract static class AtomicHelper {
- /** Non volatile write of the thread to the {@link Waiter#thread} field. */
+ /** Non-volatile write of the thread to the {@link Waiter#thread} field. */
abstract void putThread(Waiter waiter, Thread newValue);
- /** Non volatile write of the waiter to the {@link Waiter#next} field. */
+ /** Non-volatile write of the waiter to the {@link Waiter#next} field. */
abstract void putNext(Waiter waiter, @CheckForNull Waiter newValue);
/** Performs a CAS operation on the {@link #waiters} field. */
@@ -1353,9 +1369,10 @@ public abstract class AbstractFuture<V extends @Nullable Object> extends Interna
WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread"));
WAITER_NEXT_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("next"));
UNSAFE = unsafe;
- } catch (Exception e) {
- throwIfUnchecked(e);
+ } catch (NoSuchFieldException e) {
throw new RuntimeException(e);
+ } catch (RuntimeException e) {
+ throw e;
}
}
diff --git a/guava/src/com/google/common/util/concurrent/AbstractIdleService.java b/guava/src/com/google/common/util/concurrent/AbstractIdleService.java
index fe9faf9e5..c1d32eefe 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractIdleService.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractIdleService.java
@@ -14,7 +14,10 @@
package com.google.common.util.concurrent;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
+
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Supplier;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
@@ -26,12 +29,13 @@ import java.util.concurrent.TimeoutException;
/**
* Base class for services that do not need a thread while "running" but may need one during startup
* and shutdown. Subclasses can implement {@link #startUp} and {@link #shutDown} methods, each which
- * run in a executor which by default uses a separate thread for each method.
+ * run in an executor which by default uses a separate thread for each method.
*
* @author Chris Nokleberg
* @since 1.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractIdleService implements Service {
@@ -55,15 +59,13 @@ public abstract class AbstractIdleService implements Service {
protected final void doStart() {
MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- startUp();
- notifyStarted();
- } catch (Throwable t) {
- notifyFailed(t);
- }
+ () -> {
+ try {
+ startUp();
+ notifyStarted();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -72,15 +74,13 @@ public abstract class AbstractIdleService implements Service {
protected final void doStop() {
MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- shutDown();
- notifyStopped();
- } catch (Throwable t) {
- notifyFailed(t);
- }
+ () -> {
+ try {
+ shutDown();
+ notifyStopped();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -108,12 +108,7 @@ public abstract class AbstractIdleService implements Service {
* stopped, and should return promptly.
*/
protected Executor executor() {
- return new Executor() {
- @Override
- public void execute(Runnable command) {
- MoreExecutors.newThread(threadNameSupplier.get(), command).start();
- }
- };
+ return command -> MoreExecutors.newThread(threadNameSupplier.get(), command).start();
}
@Override
diff --git a/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java b/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java
index fd5c5c911..113665b91 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractListeningExecutorService.java
@@ -14,9 +14,10 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.CheckReturnValue;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.RunnableFuture;
@@ -33,37 +34,46 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Chris Povirk
* @since 14.0
*/
-@Beta
-@CanIgnoreReturnValue
+@CheckReturnValue
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractListeningExecutorService extends AbstractExecutorService
implements ListeningExecutorService {
- /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
+ /**
+ * @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0)
+ */
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
protected final <T extends @Nullable Object> RunnableFuture<T> newTaskFor(
Runnable runnable, @ParametricNullness T value) {
return TrustedListenableFutureTask.create(runnable, value);
}
- /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
+ /**
+ * @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0)
+ */
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
protected final <T extends @Nullable Object> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return TrustedListenableFutureTask.create(callable);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public ListenableFuture<?> submit(Runnable task) {
return (ListenableFuture<?>) super.submit(task);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public <T extends @Nullable Object> ListenableFuture<T> submit(
Runnable task, @ParametricNullness T result) {
return (ListenableFuture<T>) super.submit(task, result);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public <T extends @Nullable Object> ListenableFuture<T> submit(Callable<T> task) {
return (ListenableFuture<T>) super.submit(task);
diff --git a/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java b/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
index db5bf2912..164a6dbb4 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
@@ -19,11 +19,12 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.immediateCancelledFuture;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtIncompatible;
-import com.google.common.base.Supplier;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.WeakOuter;
@@ -101,6 +102,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractScheduledService implements Service {
private static final Logger logger = Logger.getLogger(AbstractScheduledService.class.getName());
@@ -232,9 +234,11 @@ public abstract class AbstractScheduledService implements Service {
}
AbstractScheduledService.this.runOneIteration();
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
try {
shutDown();
} catch (Exception ignored) {
+ restoreInterruptIfIsInterruptedException(ignored);
logger.log(
Level.WARNING,
"Error while attempting to shut down the service after failure.",
@@ -254,32 +258,28 @@ public abstract class AbstractScheduledService implements Service {
@Override
protected final void doStart() {
executorService =
- MoreExecutors.renamingDecorator(
- executor(),
- new Supplier<String>() {
- @Override
- public String get() {
- return serviceName() + " " + state();
- }
- });
+ MoreExecutors.renamingDecorator(executor(), () -> serviceName() + " " + state());
executorService.execute(
- new Runnable() {
- @Override
- public void run() {
- lock.lock();
- try {
- startUp();
- runningTask = scheduler().schedule(delegate, executorService, task);
- notifyStarted();
- } catch (Throwable t) {
- notifyFailed(t);
- if (runningTask != null) {
- // prevent the task from running if possible
- runningTask.cancel(false);
- }
- } finally {
- lock.unlock();
+ () -> {
+ lock.lock();
+ try {
+ startUp();
+ /*
+ * requireNonNull is safe because executorService is never cleared after the
+ * assignment above.
+ */
+ requireNonNull(executorService);
+ runningTask = scheduler().schedule(delegate, executorService, task);
+ notifyStarted();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
+ if (runningTask != null) {
+ // prevent the task from running if possible
+ runningTask.cancel(false);
}
+ } finally {
+ lock.unlock();
}
});
}
@@ -291,27 +291,25 @@ public abstract class AbstractScheduledService implements Service {
requireNonNull(executorService);
runningTask.cancel(false);
executorService.execute(
- new Runnable() {
- @Override
- public void run() {
+ () -> {
+ try {
+ lock.lock();
try {
- lock.lock();
- try {
- if (state() != State.STOPPING) {
- // This means that the state has changed since we were scheduled. This implies
- // that an execution of runOneIteration has thrown an exception and we have
- // transitioned to a failed state, also this means that shutDown has already
- // been called, so we do not want to call it again.
- return;
- }
- shutDown();
- } finally {
- lock.unlock();
+ if (state() != State.STOPPING) {
+ // This means that the state has changed since we were scheduled. This implies
+ // that an execution of runOneIteration has thrown an exception and we have
+ // transitioned to a failed state, also this means that shutDown has already
+ // been called, so we do not want to call it again.
+ return;
}
- notifyStopped();
- } catch (Throwable t) {
- notifyFailed(t);
+ shutDown();
+ } finally {
+ lock.unlock();
}
+ notifyStopped();
+ } catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
+ notifyFailed(t);
}
});
}
@@ -377,7 +375,7 @@ public abstract class AbstractScheduledService implements Service {
}
final ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl());
- // Add a listener to shutdown the executor after the service is stopped. This ensures that the
+ // Add a listener to shut down the executor after the service is stopped. This ensures that the
// JVM shutdown will not be prevented from exiting after this service has stopped or failed.
// Technically this listener is added after start() was called so it is a little gross, but it
// is called within doStart() so we know that the service cannot terminate or fail concurrently
@@ -595,6 +593,7 @@ public abstract class AbstractScheduledService implements Service {
try {
schedule = CustomScheduler.this.getNextSchedule();
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
service.notifyFailed(t);
return new FutureAsCancellable(immediateCancelledFuture());
}
@@ -607,7 +606,7 @@ public abstract class AbstractScheduledService implements Service {
lock.lock();
try {
toReturn = initializeOrUpdateCancellationDelegate(schedule);
- } catch (Throwable e) {
+ } catch (RuntimeException | Error e) {
// If an exception is thrown by the subclass then we need to make sure that the service
// notices and transitions to the FAILED state. We do it by calling notifyFailed directly
// because the service does not monitor the state of the future so if the exception is not
diff --git a/guava/src/com/google/common/util/concurrent/AbstractService.java b/guava/src/com/google/common/util/concurrent/AbstractService.java
index ae400963c..424206ef5 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractService.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractService.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import static com.google.common.util.concurrent.Service.State.FAILED;
import static com.google.common.util.concurrent.Service.State.NEW;
import static com.google.common.util.concurrent.Service.State.RUNNING;
@@ -25,8 +26,8 @@ import static com.google.common.util.concurrent.Service.State.STOPPING;
import static com.google.common.util.concurrent.Service.State.TERMINATED;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.util.concurrent.Monitor.Guard;
import com.google.common.util.concurrent.Service.State; // javadoc needs this
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -50,6 +51,7 @@ import javax.annotation.CheckForNull;
* @since 1.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public abstract class AbstractService implements Service {
private static final ListenerCallQueue.Event<Listener> STARTING_EVENT =
@@ -237,7 +239,6 @@ public abstract class AbstractService implements Service {
*
* @since 27.0
*/
- @Beta
@ForOverride
protected void doCancelStart() {}
@@ -250,6 +251,7 @@ public abstract class AbstractService implements Service {
enqueueStartingEvent();
doStart();
} catch (Throwable startupFailure) {
+ restoreInterruptIfIsInterruptedException(startupFailure);
notifyFailed(startupFailure);
} finally {
monitor.leave();
@@ -289,6 +291,7 @@ public abstract class AbstractService implements Service {
throw new AssertionError("isStoppable is incorrectly implemented, saw: " + previous);
}
} catch (Throwable shutdownFailure) {
+ restoreInterruptIfIsInterruptedException(shutdownFailure);
notifyFailed(shutdownFailure);
} finally {
monitor.leave();
@@ -323,7 +326,7 @@ public abstract class AbstractService implements Service {
monitor.leave();
}
} else {
- // It is possible due to races the we are currently in the expected state even though we
+ // It is possible due to races that we are currently in the expected state even though we
// timed out. e.g. if we weren't event able to grab the lock within the timeout we would never
// even check the guard. I don't think we care too much about this use case but it could lead
// to a confusing error message.
@@ -356,7 +359,7 @@ public abstract class AbstractService implements Service {
monitor.leave();
}
} else {
- // It is possible due to races the we are currently in the expected state even though we
+ // It is possible due to races that we are currently in the expected state even though we
// timed out. e.g. if we weren't event able to grab the lock within the timeout we would never
// even check the guard. I don't think we care too much about this use case but it could lead
// to a confusing error message.
diff --git a/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java b/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
index dd6879159..5581b5fae 100644
--- a/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
+++ b/guava/src/com/google/common/util/concurrent/AbstractTransformFuture.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.MoreExecutors.rejectionPropagatingExecutor;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
@@ -121,6 +122,7 @@ abstract class AbstractTransformFuture<
try {
transformResult = doTransform(localFunction, sourceResult);
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
// This exception is irrelevant in this thread, but useful for the client.
setException(t);
return;
diff --git a/guava/src/com/google/common/util/concurrent/AggregateFuture.java b/guava/src/com/google/common/util/concurrent/AggregateFuture.java
index 6d2ed9c8e..ec96cbb89 100644
--- a/guava/src/com/google/common/util/concurrent/AggregateFuture.java
+++ b/guava/src/com/google/common/util/concurrent/AggregateFuture.java
@@ -268,7 +268,7 @@ abstract class AggregateFuture<InputT extends @Nullable Object, OutputT extends
collectOneValue(index, getDone(future));
} catch (ExecutionException e) {
handleException(e.getCause());
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
handleException(t);
}
}
@@ -357,7 +357,7 @@ abstract class AggregateFuture<InputT extends @Nullable Object, OutputT extends
* We've seen this, so we've seen its causes, too. No need to re-add them. (There's one case
* where this isn't true, but we ignore it: If we record an exception, then someone calls
* initCause() on it, and then we examine it again, we'll conclude that we've seen the whole
- * chain before when it fact we haven't. But this should be rare.)
+ * chain before when in fact we haven't. But this should be rare.)
*/
return false;
}
diff --git a/guava/src/com/google/common/util/concurrent/AggregateFutureState.java b/guava/src/com/google/common/util/concurrent/AggregateFutureState.java
index ee23ca021..7bdec0135 100644
--- a/guava/src/com/google/common/util/concurrent/AggregateFutureState.java
+++ b/guava/src/com/google/common/util/concurrent/AggregateFutureState.java
@@ -61,7 +61,7 @@ abstract class AggregateFutureState<OutputT extends @Nullable Object>
new SafeAtomicHelper(
newUpdater(AggregateFutureState.class, Set.class, "seenExceptions"),
newUpdater(AggregateFutureState.class, "remaining"));
- } catch (Throwable reflectionFailure) {
+ } catch (RuntimeException | Error reflectionFailure) {
// Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause
// getDeclaredField to throw a NoSuchFieldException when the field is definitely there.
// For these users fallback to a suboptimal implementation, based on synchronized. This will
diff --git a/guava/src/com/google/common/util/concurrent/AtomicDouble.java b/guava/src/com/google/common/util/concurrent/AtomicDouble.java
index 56360a870..7e3cb2303 100644
--- a/guava/src/com/google/common/util/concurrent/AtomicDouble.java
+++ b/guava/src/com/google/common/util/concurrent/AtomicDouble.java
@@ -19,6 +19,7 @@ import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.ReflectionSupport;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
@@ -55,6 +56,7 @@ import java.util.function.DoubleUnaryOperator;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ReflectionSupport(value = ReflectionSupport.Level.FULL)
@ElementTypesAreNonnullByDefault
public class AtomicDouble extends Number implements java.io.Serializable {
diff --git a/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java b/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
index 6cc28aad0..6f8867189 100644
--- a/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
+++ b/guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
@@ -18,6 +18,7 @@ import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.ImmutableLongArray;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.atomic.AtomicLongArray;
@@ -47,6 +48,7 @@ import java.util.function.DoubleUnaryOperator;
* @since 11.0
*/
@GwtIncompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public class AtomicDoubleArray implements java.io.Serializable {
private static final long serialVersionUID = 0L;
@@ -191,7 +193,7 @@ public class AtomicDoubleArray implements java.io.Serializable {
/**
* Atomically updates the element at index {@code i} with the results of applying the given
- * function to the curernt and given values.
+ * function to the current and given values.
*
* @param i the index to update
* @param x the update value
@@ -207,7 +209,7 @@ public class AtomicDoubleArray implements java.io.Serializable {
/**
* Atomically updates the element at index {@code i} with the results of applying the given
- * function to the curernt and given values.
+ * function to the current and given values.
*
* @param i the index to update
* @param x the update value
@@ -223,7 +225,7 @@ public class AtomicDoubleArray implements java.io.Serializable {
/**
* Atomically updates the element at index {@code i} with the results of applying the given
- * function to the curernt value.
+ * function to the current value.
*
* @param i the index to update
* @param updaterFunction the update function
@@ -245,7 +247,7 @@ public class AtomicDoubleArray implements java.io.Serializable {
/**
* Atomically updates the element at index {@code i} with the results of applying the given
- * function to the curernt value.
+ * function to the current value.
*
* @param i the index to update
* @param updaterFunction the update function
diff --git a/guava/src/com/google/common/util/concurrent/AtomicLongMap.java b/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
index 456b3aceb..28481cca5 100644
--- a/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
+++ b/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
@@ -18,9 +18,10 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
@@ -44,6 +45,8 @@ import javax.annotation.CheckForNull;
* <p>Instances of this class may be used by multiple threads concurrently. All operations are
* atomic unless otherwise noted.
*
+ * <p>Instances of this class are serializable if the keys are serializable.
+ *
* <p><b>Note:</b> If your values are always positive and less than 2^31, you may wish to use a
* {@link com.google.common.collect.Multiset} such as {@link
* com.google.common.collect.ConcurrentHashMultiset} instead.
@@ -55,6 +58,7 @@ import javax.annotation.CheckForNull;
* @since 11.0
*/
@GwtCompatible
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class AtomicLongMap<K> implements Serializable {
private final ConcurrentHashMap<K, Long> map;
@@ -238,7 +242,6 @@ public final class AtomicLongMap<K> implements Serializable {
*
* @since 20.0
*/
- @Beta
@CanIgnoreReturnValue
public boolean removeIfZero(K key) {
return remove(key, 0);
@@ -263,7 +266,7 @@ public final class AtomicLongMap<K> implements Serializable {
return map.values().stream().mapToLong(Long::longValue).sum();
}
- @CheckForNull private transient Map<K, Long> asMap;
+ @LazyInit @CheckForNull private transient Map<K, Long> asMap;
/** Returns a live, read-only view of the map backing this {@code AtomicLongMap}. */
public Map<K, Long> asMap() {
diff --git a/guava/src/com/google/common/util/concurrent/Callables.java b/guava/src/com/google/common/util/concurrent/Callables.java
index 3b52c2e98..6a586bb2e 100644
--- a/guava/src/com/google/common/util/concurrent/Callables.java
+++ b/guava/src/com/google/common/util/concurrent/Callables.java
@@ -16,9 +16,9 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Supplier;
import java.util.concurrent.Callable;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -47,7 +47,7 @@ public final class Callables {
*
* @since 20.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible
public static <T extends @Nullable Object> AsyncCallable<T> asAsyncCallable(
Callable<T> callable, ListeningExecutorService listeningExecutorService) {
@@ -64,6 +64,7 @@ public final class Callables {
* @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
* for each invocation of the wrapped callable.
*/
+ @J2ktIncompatible
@GwtIncompatible // threads
static <T extends @Nullable Object> Callable<T> threadRenaming(
Callable<T> callable, Supplier<String> nameSupplier) {
@@ -91,6 +92,7 @@ public final class Callables {
* @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once
* for each invocation of the wrapped callable.
*/
+ @J2ktIncompatible
@GwtIncompatible // threads
static Runnable threadRenaming(Runnable task, Supplier<String> nameSupplier) {
checkNotNull(nameSupplier);
@@ -110,6 +112,7 @@ public final class Callables {
}
/** Tries to set name of the given {@link Thread}, returns true if successful. */
+ @J2ktIncompatible
@GwtIncompatible // threads
private static boolean trySetName(String threadName, Thread currentThread) {
/*
diff --git a/guava/src/com/google/common/util/concurrent/ClosingFuture.java b/guava/src/com/google/common/util/concurrent/ClosingFuture.java
index fbd604cea..79aa0aa0e 100644
--- a/guava/src/com/google/common/util/concurrent/ClosingFuture.java
+++ b/guava/src/com/google/common/util/concurrent/ClosingFuture.java
@@ -32,12 +32,13 @@ import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.nonCancellationPropagating;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ClosingFuture.Combiner.AsyncCombiningCallable;
@@ -190,6 +191,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*/
// TODO(dpb): Consider reusing one CloseableList for the entire pipeline, modulo combinations.
@DoNotMock("Use ClosingFuture.from(Futures.immediate*Future)")
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
// TODO(dpb): GWT compatibility.
public final class ClosingFuture<V extends @Nullable Object> {
@@ -252,7 +254,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -271,7 +273,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -290,7 +292,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to an input, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -309,7 +311,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to an input, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable, Executor)
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
* closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
* not before this method completes), even if this method throws or the pipeline is cancelled.
*/
@@ -352,7 +354,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Starts closing all closeable objects captured during the {@link ClosingFuture}'s asynchronous
* operation on the {@link Executor}s specified by calls to {@link
- * DeferredCloser#eventuallyClose(Closeable, Executor)}.
+ * DeferredCloser#eventuallyClose(Object, Executor)}.
*
* <p>If any such calls specified {@link MoreExecutors#directExecutor()}, those objects will be
* closed synchronously.
@@ -415,14 +417,14 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Starts a {@link ClosingFuture} pipeline with a {@link ListenableFuture}.
*
- * <p>If {@code future} succeeds, its value will be closed (using {@code closingExecutor)} when
+ * <p>If {@code future} succeeds, its value will be closed (using {@code closingExecutor)}) when
* the pipeline is done, even if the pipeline is canceled or fails.
*
* <p>Cancelling the pipeline will not cancel {@code future}, so that the pipeline can access its
* value in order to close it.
*
* @param future the future to create the {@code ClosingFuture} from. For discussion of the
- * future's result type {@code C}, see {@link DeferredCloser#eventuallyClose(Closeable,
+ * future's result type {@code C}, see {@link DeferredCloser#eventuallyClose(Object,
* Executor)}.
* @param closingExecutor the future's result will be closed on this executor
* @deprecated Creating {@link Future}s of closeable types is dangerous in general because the
@@ -730,7 +732,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #transform(ClosingFunction,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor) closer.eventuallyClose()}
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
* for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
@@ -811,7 +813,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
*
* <ul>
* <li>It does not need to capture any {@link Closeable} objects by calling {@link
- * DeferredCloser#eventuallyClose(Closeable, Executor)}.
+ * DeferredCloser#eventuallyClose(Object, Executor)}.
* <li>It returns a {@link ListenableFuture}.
* </ul>
*
@@ -928,7 +930,7 @@ public final class ClosingFuture<V extends @Nullable Object> {
* {@code ClosingFuture}. If possible, prefer calling {@link #catching(Class,
* ClosingFunction, Executor)} instead, with a function that returns the next value
* directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor) closer.eventuallyClose()}
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
* for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
@@ -1244,10 +1246,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*
* @param peeker used to get the value of any of the input futures
*/
@@ -1265,10 +1267,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Computes a {@link ClosingFuture} result, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*
* @param peeker used to get the value of any of the input futures
*/
@@ -1347,9 +1349,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1383,16 +1384,11 @@ public final class ClosingFuture<V extends @Nullable Object> {
: Futures.whenAllComplete(inputFutures());
}
- private static final Function<ClosingFuture<?>, FluentFuture<?>> INNER_FUTURE =
- new Function<ClosingFuture<?>, FluentFuture<?>>() {
- @Override
- public FluentFuture<?> apply(ClosingFuture<?> future) {
- return future.future;
- }
- };
private ImmutableList<FluentFuture<?>> inputFutures() {
- return FluentIterable.from(inputs).transform(INNER_FUTURE).toList();
+ return FluentIterable.from(inputs)
+ .<FluentFuture<?>>transform(future -> future.future)
+ .toList();
}
}
@@ -1422,10 +1418,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to two inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
@@ -1447,10 +1443,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to two inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
@@ -1523,9 +1519,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1581,10 +1576,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to three inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(
@@ -1613,10 +1608,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to three inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer,
@@ -1699,9 +1694,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1767,10 +1761,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to four inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(
@@ -1803,10 +1797,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to four inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer,
@@ -1896,9 +1890,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -1970,10 +1963,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to five inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
@ParametricNullness
U apply(
@@ -2009,10 +2002,10 @@ public final class ClosingFuture<V extends @Nullable Object> {
/**
* Applies this function to five inputs, or throws an exception if unable to do so.
*
- * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Closeable,
- * Executor) closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline
- * is done (but not before this method completes), even if this method throws or the pipeline
- * is cancelled.
+ * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
+ * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
+ * (but not before this method completes), even if this method throws or the pipeline is
+ * cancelled.
*/
ClosingFuture<U> apply(
DeferredCloser closer,
@@ -2109,9 +2102,8 @@ public final class ClosingFuture<V extends @Nullable Object> {
* <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
* {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
* Executor)} instead, with a function that returns the next value directly.
- * <li>Call {@link DeferredCloser#eventuallyClose(Closeable, Executor)
- * closer.eventuallyClose()} for every closeable object this step creates in order to
- * capture it for later closing.
+ * <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
+ * for every closeable object this step creates in order to capture it for later closing.
* <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
* ClosingFuture} call {@link #from(ListenableFuture)}.
* </ul>
@@ -2163,14 +2155,12 @@ public final class ClosingFuture<V extends @Nullable Object> {
}
try {
executor.execute(
- new Runnable() {
- @Override
- public void run() {
- try {
- closeable.close();
- } catch (Exception e) {
- logger.log(WARNING, "thrown by close()", e);
- }
+ () -> {
+ try {
+ closeable.close();
+ } catch (Exception e) {
+ restoreInterruptIfIsInterruptedException(e);
+ logger.log(WARNING, "thrown by close()", e);
}
});
} catch (RejectedExecutionException e) {
diff --git a/guava/src/com/google/common/util/concurrent/CollectionFuture.java b/guava/src/com/google/common/util/concurrent/CollectionFuture.java
index c106c157e..062aee7a7 100644
--- a/guava/src/com/google/common/util/concurrent/CollectionFuture.java
+++ b/guava/src/com/google/common/util/concurrent/CollectionFuture.java
@@ -32,7 +32,7 @@ abstract class CollectionFuture<V extends @Nullable Object, C extends @Nullable
extends AggregateFuture<V, C> {
/*
* We access this field racily but safely. For discussion of a similar situation, see the comments
- * on the fields of TimeoutFuture. This field is slightly different than the fields discussed
+ * on the fields of TimeoutFuture. This field is slightly different from the fields discussed
* there: cancel() never reads this field, only writes to it. That makes the race here completely
* harmless, rather than just 99.99% harmless.
*/
@@ -102,9 +102,9 @@ abstract class CollectionFuture<V extends @Nullable Object, C extends @Nullable
/** The result of a successful {@code Future}. */
private static final class Present<V extends @Nullable Object> {
- V value;
+ @ParametricNullness final V value;
- Present(V value) {
+ Present(@ParametricNullness V value) {
this.value = value;
}
}
diff --git a/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java b/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
index decb5f1b1..0ec799cc4 100644
--- a/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
+++ b/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
@@ -17,8 +17,8 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
@@ -27,7 +27,6 @@ import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.Weak;
import java.util.ArrayList;
import java.util.Arrays;
@@ -160,8 +159,7 @@ import javax.annotation.CheckForNull;
* @author Darick Tong
* @since 13.0
*/
-@Beta
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class CycleDetectingLockFactory {
@@ -173,7 +171,6 @@ public class CycleDetectingLockFactory {
*
* @since 13.0
*/
- @Beta
public interface Policy {
/**
@@ -193,7 +190,6 @@ public class CycleDetectingLockFactory {
*
* @since 13.0
*/
- @Beta
public enum Policies implements Policy {
/**
* When potential deadlock is detected, this policy results in the throwing of the {@code
@@ -394,7 +390,6 @@ public class CycleDetectingLockFactory {
* @param <E> The Enum type representing the explicit lock ordering.
* @since 13.0
*/
- @Beta
public static final class WithExplicitOrdering<E extends Enum<E>>
extends CycleDetectingLockFactory {
@@ -534,7 +529,6 @@ public class CycleDetectingLockFactory {
*
* @since 13.0
*/
- @Beta
public static final class PotentialDeadlockException extends ExampleStackTrace {
private final ExampleStackTrace conflictingStackTrace;
diff --git a/guava/src/com/google/common/util/concurrent/ExecutionError.java b/guava/src/com/google/common/util/concurrent/ExecutionError.java
index deaff15a4..303383039 100644
--- a/guava/src/com/google/common/util/concurrent/ExecutionError.java
+++ b/guava/src/com/google/common/util/concurrent/ExecutionError.java
@@ -33,7 +33,7 @@ public class ExecutionError extends Error {
/*
* Ideally, this class would have exposed only constructors that require a non-null cause. We
* might try to move in that direction, but there are complications. See
- * https://github.com/jspecify/nullness-checker-for-checker-framework/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
+ * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
*/
/** Creates a new instance with {@code null} as its detail message. */
diff --git a/guava/src/com/google/common/util/concurrent/ExecutionList.java b/guava/src/com/google/common/util/concurrent/ExecutionList.java
index 96fc51ca8..645817c4a 100644
--- a/guava/src/com/google/common/util/concurrent/ExecutionList.java
+++ b/guava/src/com/google/common/util/concurrent/ExecutionList.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.concurrent.Executor;
import java.util.logging.Level;
@@ -39,6 +40,7 @@ import javax.annotation.CheckForNull;
* @author Sven Mawson
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ExecutionList {
diff --git a/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java b/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java
index 80c777934..c335711c0 100644
--- a/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java
+++ b/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java
@@ -25,8 +25,10 @@ import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.Objects.requireNonNull;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
+import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -54,7 +56,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* (However, cancellation can prevent an <i>unstarted</i> task from running.) Therefore, the
* next task will wait for any running callable (or pending {@code Future} returned by an
* {@code AsyncCallable}) to complete, without interrupting it (and without calling {@code
- * cancel} on the {@code Future}). So beware: <i>Even if you cancel every precededing {@code
+ * cancel} on the {@code Future}). So beware: <i>Even if you cancel every preceding {@code
* Future} returned by this class, the next task may still have to wait.</i>.
* <li>Once an {@code AsyncCallable} returns a {@code Future}, this class considers that task to
* be "done" as soon as <i>that</i> {@code Future} completes in any way. Notably, a {@code
@@ -84,6 +86,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @since 26.0
*/
@ElementTypesAreNonnullByDefault
+@J2ktIncompatible
public final class ExecutionSequencer {
private ExecutionSequencer() {}
@@ -250,7 +253,7 @@ public final class ExecutionSequencer {
taskFuture.cancel(false);
}
};
- // Adding the listener to both futures guarantees that newFuture will aways be set. Adding to
+ // Adding the listener to both futures guarantees that newFuture will always be set. Adding to
// taskFuture guarantees completion if the callable is invoked, and adding to outputFuture
// propagates cancellation if the callable has not yet been invoked.
outputFuture.addListener(listener, directExecutor());
diff --git a/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java b/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
index ddc944018..1c16cfb14 100644
--- a/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
+++ b/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
@@ -15,9 +15,10 @@
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -34,11 +35,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jens Nyman
* @since 1.0
*/
-@Beta
-@CanIgnoreReturnValue
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class FakeTimeLimiter implements TimeLimiter {
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public <T> T newProxy(
T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit) {
@@ -48,6 +49,7 @@ public final class FakeTimeLimiter implements TimeLimiter {
return target; // ha ha
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
@ParametricNullness
public <T extends @Nullable Object> T callWithTimeout(
@@ -59,16 +61,14 @@ public final class FakeTimeLimiter implements TimeLimiter {
} catch (RuntimeException e) {
throw new UncheckedExecutionException(e);
} catch (Exception e) {
+ restoreInterruptIfIsInterruptedException(e);
throw new ExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
- } catch (Throwable e) {
- // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend
- // Exception, so we'll treat it like an Exception.
- throw new ExecutionException(e);
}
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
@ParametricNullness
public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
@@ -86,10 +86,6 @@ public final class FakeTimeLimiter implements TimeLimiter {
throw new UncheckedExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
- } catch (Throwable e) {
- // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend
- // Exception, so we'll treat it like a RuntimeException.
- throw new UncheckedExecutionException(e);
}
}
diff --git a/guava/src/com/google/common/util/concurrent/FluentFuture.java b/guava/src/com/google/common/util/concurrent/FluentFuture.java
index b47e67927..9dbbca37f 100644
--- a/guava/src/com/google/common/util/concurrent/FluentFuture.java
+++ b/guava/src/com/google/common/util/concurrent/FluentFuture.java
@@ -17,9 +17,9 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
@@ -184,8 +184,8 @@ public abstract class FluentFuture<V extends @Nullable Object>
* {@code get()} throws a different kind of exception, that exception itself.
* @param executor the executor that runs {@code fallback} if the input fails
*/
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
- @Beta
public final <X extends Throwable> FluentFuture<V> catching(
Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor) {
return (FluentFuture<V>) Futures.catching(this, exceptionType, fallback, executor);
@@ -249,8 +249,8 @@ public abstract class FluentFuture<V extends @Nullable Object>
* {@code get()} throws a different kind of exception, that exception itself.
* @param executor the executor that runs {@code fallback} if the input fails
*/
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
- @Beta
public final <X extends Throwable> FluentFuture<V> catchingAsync(
Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) {
return (FluentFuture<V>) Futures.catchingAsync(this, exceptionType, fallback, executor);
@@ -266,8 +266,8 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @param scheduledExecutor The executor service to enforce the timeout.
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // ScheduledExecutorService
- @Beta
public final FluentFuture<V> withTimeout(
Duration timeout, ScheduledExecutorService scheduledExecutor) {
return withTimeout(toNanosSaturated(timeout), TimeUnit.NANOSECONDS, scheduledExecutor);
@@ -283,9 +283,9 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @param unit the time unit of the time parameter
* @param scheduledExecutor The executor service to enforce the timeout.
*/
+ @J2ktIncompatible
@GwtIncompatible // ScheduledExecutorService
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
- @Beta
public final FluentFuture<V> withTimeout(
long timeout, TimeUnit unit, ScheduledExecutorService scheduledExecutor) {
return (FluentFuture<V>) Futures.withTimeout(this, timeout, unit, scheduledExecutor);
@@ -330,7 +330,6 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @return A future that holds result of the function (if the input succeeded) or the original
* input's failure (if not)
*/
- @Beta
public final <T extends @Nullable Object> FluentFuture<T> transformAsync(
AsyncFunction<? super V, T> function, Executor executor) {
return (FluentFuture<T>) Futures.transformAsync(this, function, executor);
@@ -368,7 +367,6 @@ public abstract class FluentFuture<V extends @Nullable Object>
* @param executor Executor to run the function in.
* @return A future that holds result of the transformation.
*/
- @Beta
public final <T extends @Nullable Object> FluentFuture<T> transform(
Function<? super V, T> function, Executor executor) {
return (FluentFuture<T>) Futures.transform(this, function, executor);
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java b/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java
index d0d72a815..13aa80b51 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingBlockingDeque.java
@@ -17,6 +17,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ForwardingDeque;
import java.util.Collection;
import java.util.concurrent.BlockingDeque;
@@ -44,6 +45,7 @@ import javax.annotation.CheckForNull;
* @author Emily Soldal
* @since 21.0 (since 14.0 as {@link com.google.common.collect.ForwardingBlockingDeque})
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingDeque<E> extends ForwardingDeque<E>
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java b/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
index dc8511d94..79ec94a1e 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ForwardingQueue;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
@@ -36,7 +37,7 @@ import javax.annotation.CheckForNull;
* @param <E> the type of elements held in this collection
* @since 4.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
@@ -48,21 +49,25 @@ public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
@Override
protected abstract BlockingQueue<E> delegate();
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
return delegate().drainTo(c, maxElements);
}
+ @CanIgnoreReturnValue
@Override
public int drainTo(Collection<? super E> c) {
return delegate().drainTo(c);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return delegate().offer(e, timeout, unit);
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
@CheckForNull
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
@@ -79,6 +84,7 @@ public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
return delegate().remainingCapacity();
}
+ @CanIgnoreReturnValue // TODO(kak): consider removing this
@Override
public E take() throws InterruptedException {
return delegate().take();
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingCondition.java b/guava/src/com/google/common/util/concurrent/ForwardingCondition.java
index d17f98cf2..885cca7fc 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingCondition.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingCondition.java
@@ -14,11 +14,13 @@
package com.google.common.util.concurrent;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
/** Forwarding wrapper around a {@code Condition}. */
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
abstract class ForwardingCondition implements Condition {
abstract Condition delegate();
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java b/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
index ed78b8685..986278daf 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
@@ -15,8 +15,10 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ForwardingObject;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.errorprone.annotations.CheckReturnValue;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
@@ -32,10 +34,14 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* should override one or more methods to modify the behavior of the backing executor service as
* desired per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
+ * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
+ * default} methods. Instead, it inherits their default implementations. When those implementations
+ * invoke methods, they invoke methods on the {@code ForwardingExecutorService}.
+ *
* @author Kurt Alfred Kluever
* @since 10.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingExecutorService extends ForwardingObject
@@ -46,6 +52,7 @@ public abstract class ForwardingExecutorService extends ForwardingObject
@Override
protected abstract ExecutorService delegate();
+ @CheckReturnValue
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return delegate().awaitTermination(timeout, unit);
@@ -93,6 +100,7 @@ public abstract class ForwardingExecutorService extends ForwardingObject
}
@Override
+ @CanIgnoreReturnValue
public List<Runnable> shutdownNow() {
return delegate().shutdownNow();
}
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingFuture.java b/guava/src/com/google/common/util/concurrent/ForwardingFuture.java
index 47002b03a..635c4f6eb 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingFuture.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingFuture.java
@@ -34,7 +34,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Sven Mawson
* @since 1.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
@GwtCompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingFuture<V extends @Nullable Object> extends ForwardingObject
@@ -46,6 +45,7 @@ public abstract class ForwardingFuture<V extends @Nullable Object> extends Forwa
protected abstract Future<? extends V> delegate();
@Override
+ @CanIgnoreReturnValue
public boolean cancel(boolean mayInterruptIfRunning) {
return delegate().cancel(mayInterruptIfRunning);
}
@@ -61,12 +61,14 @@ public abstract class ForwardingFuture<V extends @Nullable Object> extends Forwa
}
@Override
+ @CanIgnoreReturnValue
@ParametricNullness
public V get() throws InterruptedException, ExecutionException {
return delegate().get();
}
@Override
+ @CanIgnoreReturnValue
@ParametricNullness
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java b/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
index 386809194..ccd2dd7b1 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
@@ -16,7 +16,6 @@ package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -30,7 +29,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Shardul Deo
* @since 4.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
@GwtCompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingListenableFuture<V extends @Nullable Object>
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java b/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
index fe25b867a..25dbf0de7 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
@@ -15,7 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -25,10 +25,14 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* executor service as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
+ * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
+ * default} methods. Instead, it inherits their default implementations. When those implementations
+ * invoke methods, they invoke methods on the {@code ForwardingListeningExecutorService}.
+ *
* @author Isaac Shum
* @since 10.0
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingListeningExecutorService extends ForwardingExecutorService
diff --git a/guava/src/com/google/common/util/concurrent/ForwardingLock.java b/guava/src/com/google/common/util/concurrent/ForwardingLock.java
index db2026ab4..558b6e3de 100644
--- a/guava/src/com/google/common/util/concurrent/ForwardingLock.java
+++ b/guava/src/com/google/common/util/concurrent/ForwardingLock.java
@@ -14,11 +14,13 @@
package com.google.common.util.concurrent;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/** Forwarding wrapper around a {@code Lock}. */
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
abstract class ForwardingLock implements Lock {
abstract Lock delegate();
diff --git a/guava/src/com/google/common/util/concurrent/Futures.java b/guava/src/com/google/common/util/concurrent/Futures.java
index 09b5c3c1a..31889609a 100644
--- a/guava/src/com/google/common/util/concurrent/Futures.java
+++ b/guava/src/com/google/common/util/concurrent/Futures.java
@@ -21,9 +21,9 @@ import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
@@ -106,7 +106,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
// (hypothetical) unsafe read by our caller. Note: adding 'volatile' does not fix this issue,
// it would just add an edge such that if done() observed non-null, then it would also
// definitely observe all earlier writes, but we still have no guarantee that done() would see
- // the inital write (just stronger guarantees if it does).
+ // the initial write (just stronger guarantees if it does).
//
// See: http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013800.html
// For a (long) discussion about this specific issue and the general futility of life.
@@ -225,6 +225,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @throws RejectedExecutionException if the task cannot be scheduled for execution
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
// TODO(cpovirk): Return ListenableScheduledFuture?
public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
@@ -238,6 +239,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @throws RejectedExecutionException if the task cannot be scheduled for execution
* @since 23.0
*/
+ @J2ktIncompatible
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
// TODO(cpovirk): Return ListenableScheduledFuture?
@@ -247,16 +249,12 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
TimeUnit timeUnit,
ScheduledExecutorService executorService) {
TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
- final Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
- task.addListener(
- new Runnable() {
- @Override
- public void run() {
- // Don't want to interrupt twice
- scheduled.cancel(false);
- }
- },
- directExecutor());
+ Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
+ /*
+ * Even when the user interrupts the task, we pass `false` to `cancel` so that we don't
+ * interrupt a second time after the interruption performed by TrustedListenableFutureTask.
+ */
+ task.addListener(() -> scheduled.cancel(false), directExecutor());
return task;
}
@@ -296,7 +294,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @param executor the executor that runs {@code fallback} if {@code input} fails
* @since 19.0
*/
- @Beta
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catching(
ListenableFuture<? extends V> input,
@@ -361,7 +359,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @param executor the executor that runs {@code fallback} if {@code input} fails
* @since 19.0 (similar functionality in 14.0 as {@code withFallback})
*/
- @Beta
+ @J2ktIncompatible
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catchingAsync(
ListenableFuture<? extends V> input,
@@ -378,11 +376,11 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* <p>The delegate future is interrupted and cancelled if it times out.
*
* @param delegate The future to delegate to.
- * @param time when to timeout the future
+ * @param time when to time out the future
* @param scheduledExecutor The executor service to enforce the timeout.
* @since 28.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
ListenableFuture<V> delegate, Duration time, ScheduledExecutorService scheduledExecutor) {
@@ -396,12 +394,12 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* <p>The delegate future is interrupted and cancelled if it times out.
*
* @param delegate The future to delegate to.
- * @param time when to timeout the future
+ * @param time when to time out the future
* @param unit the time unit of the time parameter
* @param scheduledExecutor The executor service to enforce the timeout.
* @since 19.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
@@ -447,7 +445,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* input's failure (if not)
* @since 19.0 (in 11.0 as {@code transform})
*/
- @Beta
public static <I extends @Nullable Object, O extends @Nullable Object>
ListenableFuture<O> transformAsync(
ListenableFuture<I> input,
@@ -485,7 +482,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return A future that holds result of the transformation.
* @since 9.0 (in 2.0 as {@code compose})
*/
- @Beta
public static <I extends @Nullable Object, O extends @Nullable Object>
ListenableFuture<O> transform(
ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
@@ -512,7 +508,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return A future that returns the result of the transformation.
* @since 10.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static <I extends @Nullable Object, O extends @Nullable Object> Future<O> lazyTransform(
final Future<I> input, final Function<? super I, ? extends O> function) {
@@ -549,7 +545,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
private O applyTransformation(I input) throws ExecutionException {
try {
return function.apply(input);
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
throw new ExecutionException(t);
}
}
@@ -572,7 +568,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
ListenableFuture<? extends V>... futures) {
@@ -600,7 +595,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
ListenableFuture<List<@Nullable V>> nullable =
@@ -619,7 +613,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
ListenableFuture<? extends V>... futures) {
@@ -634,7 +627,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
@@ -647,7 +639,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
ListenableFuture<? extends V>... futures) {
@@ -661,7 +652,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
@@ -693,8 +683,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
*
* @since 20.0
*/
- @Beta
- @CanIgnoreReturnValue // TODO(cpovirk): Consider removing, especially if we provide run(Runnable)
@GwtCompatible
public static final class FutureCombiner<V extends @Nullable Object> {
private final boolean allMustSucceed;
@@ -719,6 +707,12 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* ExecutionException} that gets thrown by the returned combined future.
*
* <p>Canceling this future will attempt to cancel all the component futures.
+ *
+ * @return a future whose result is based on {@code combiner} (or based on the input futures
+ * passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
+ * FutureCombiner}). Even if you don't care about the value of the future, you should
+ * typically check whether it failed: See <a
+ * href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
*/
public <C extends @Nullable Object> ListenableFuture<C> callAsync(
AsyncCallable<C> combiner, Executor executor) {
@@ -738,8 +732,13 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* ExecutionException} that gets thrown by the returned combined future.
*
* <p>Canceling this future will attempt to cancel all the component futures.
+ *
+ * @return a future whose result is based on {@code combiner} (or based on the input futures
+ * passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
+ * FutureCombiner}). Even if you don't care about the value of the future, you should
+ * typically check whether it failed: See <a
+ * href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Remove this
public <C extends @Nullable Object> ListenableFuture<C> call(
Callable<C> combiner, Executor executor) {
return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
@@ -755,6 +754,11 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* <p>Canceling this Future will attempt to cancel all the component futures.
*
* @since 23.6
+ * @return a future whose result is based on {@code combiner} (or based on the input futures
+ * passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
+ * FutureCombiner}). Even though the future never produces a value other than {@code null},
+ * you should typically check whether it failed: See <a
+ * href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
*/
public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
return call(
@@ -840,7 +844,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
@SafeVarargs
public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
ListenableFuture<? extends V>... futures) {
@@ -877,7 +880,6 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
- @Beta
public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), false);
@@ -917,14 +919,7 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
for (int i = 0; i < copy.length; i++) {
final int localI = i;
- copy[i].addListener(
- new Runnable() {
- @Override
- public void run() {
- state.recordInputCompletion(delegates, localI);
- }
- },
- directExecutor());
+ copy[i].addListener(() -> state.recordInputCompletion(delegates, localI), directExecutor());
}
@SuppressWarnings("unchecked")
@@ -1223,8 +1218,8 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* does not have a suitable constructor
* @since 19.0 (in 10.0 as {@code get})
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // reflection
@ParametricNullness
public static <V extends @Nullable Object, X extends Exception> V getChecked(
@@ -1275,8 +1270,8 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* does not have a suitable constructor
* @since 28.0
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // reflection
@ParametricNullness
public static <V extends @Nullable Object, X extends Exception> V getChecked(
@@ -1327,8 +1322,8 @@ public final class Futures extends GwtFuturesCatchingSpecialization {
* does not have a suitable constructor
* @since 19.0 (in 10.0 as {@code get} and with different parameter order)
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // reflection
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@ParametricNullness
diff --git a/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java b/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
index 6f09b8066..c512d82ee 100644
--- a/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
+++ b/guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
@@ -19,6 +19,7 @@ import static java.lang.Thread.currentThread;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
@@ -39,6 +40,7 @@ import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Static methods used to implement {@link Futures#getChecked(Future, Class)}. */
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class FuturesGetChecked {
@@ -193,7 +195,9 @@ final class FuturesGetChecked {
Class<? extends Enum> theClass =
Class.forName(CLASS_VALUE_VALIDATOR_NAME).asSubclass(Enum.class);
return (GetCheckedTypeValidator) theClass.getEnumConstants()[0];
- } catch (Throwable t) { // ensure we really catch *everything*
+ } catch (ClassNotFoundException
+ | RuntimeException
+ | Error t) { // ensure we really catch *everything*
return weakSetValidator();
}
}
@@ -221,7 +225,7 @@ final class FuturesGetChecked {
try {
Exception unused = newWithCause(exceptionClass, new Exception());
return true;
- } catch (Exception e) {
+ } catch (RuntimeException | Error e) {
return false;
}
}
@@ -254,12 +258,8 @@ final class FuturesGetChecked {
private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST =
Ordering.natural()
.onResultOf(
- new Function<Constructor<?>, Boolean>() {
- @Override
- public Boolean apply(Constructor<?> input) {
- return asList(input.getParameterTypes()).contains(String.class);
- }
- })
+ (Function<Constructor<?>, Boolean>)
+ input -> asList(input.getParameterTypes()).contains(String.class))
.reverse();
@CheckForNull
diff --git a/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java b/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
index d29a673dd..fdbe50909 100644
--- a/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
+++ b/guava/src/com/google/common/util/concurrent/GwtFluentFutureCatchingSpecialization.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -23,6 +24,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* FluentFuture.catching} family of methods. Those versions have slightly different signatures.
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible // Super-sourced
@ElementTypesAreNonnullByDefault
abstract class GwtFluentFutureCatchingSpecialization<V extends @Nullable Object>
extends AbstractFuture<V> {
diff --git a/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java b/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
index 95131cec3..35adfdb67 100644
--- a/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
+++ b/guava/src/com/google/common/util/concurrent/GwtFuturesCatchingSpecialization.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.J2ktIncompatible;
/**
* Hidden superclass of {@link Futures} that provides us a place to declare special GWT versions of
@@ -23,6 +24,7 @@ import com.google.common.annotations.GwtCompatible;
* different signatures.
*/
@GwtCompatible(emulated = true)
+@J2ktIncompatible // Super-sourced
@ElementTypesAreNonnullByDefault
abstract class GwtFuturesCatchingSpecialization {
/*
diff --git a/guava/src/com/google/common/util/concurrent/ImmediateFuture.java b/guava/src/com/google/common/util/concurrent/ImmediateFuture.java
index 8b1c17ae4..f09816c4e 100644
--- a/guava/src/com/google/common/util/concurrent/ImmediateFuture.java
+++ b/guava/src/com/google/common/util/concurrent/ImmediateFuture.java
@@ -23,6 +23,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Implementation of {@link Futures#immediateFuture}. */
@@ -98,7 +99,8 @@ class ImmediateFuture<V extends @Nullable Object> implements ListenableFuture<V>
}
static final class ImmediateCancelledFuture<V extends @Nullable Object> extends TrustedFuture<V> {
- static final @Nullable ImmediateCancelledFuture<Object> INSTANCE =
+ @CheckForNull
+ static final ImmediateCancelledFuture<Object> INSTANCE =
AbstractFuture.GENERATE_CANCELLATION_CAUSES ? null : new ImmediateCancelledFuture<>();
ImmediateCancelledFuture() {
diff --git a/guava/src/com/google/common/util/concurrent/Internal.java b/guava/src/com/google/common/util/concurrent/Internal.java
index 06bee2ea0..1fc3f4f8c 100644
--- a/guava/src/com/google/common/util/concurrent/Internal.java
+++ b/guava/src/com/google/common/util/concurrent/Internal.java
@@ -15,9 +15,11 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.time.Duration;
/** This class is for {@code com.google.common.util.concurrent} use only! */
+@J2ktIncompatible
@GwtIncompatible // java.time.Duration
@ElementTypesAreNonnullByDefault
final class Internal {
diff --git a/guava/src/com/google/common/util/concurrent/InterruptibleTask.java b/guava/src/com/google/common/util/concurrent/InterruptibleTask.java
index bcec00730..6f33c5032 100644
--- a/guava/src/com/google/common/util/concurrent/InterruptibleTask.java
+++ b/guava/src/com/google/common/util/concurrent/InterruptibleTask.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.NullnessCasts.uncheckedCastNullableTToT;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
@@ -74,6 +75,7 @@ abstract class InterruptibleTask<T extends @Nullable Object>
result = runInterruptibly();
}
} catch (Throwable t) {
+ restoreInterruptIfIsInterruptedException(t);
error = t;
} finally {
// Attempt to set the task as done so that further attempts to interrupt will fail.
@@ -231,6 +233,11 @@ abstract class InterruptibleTask<T extends @Nullable Object>
super.setExclusiveOwnerThread(thread);
}
+ @VisibleForTesting
+ Thread getOwner() {
+ return super.getExclusiveOwnerThread();
+ }
+
@Override
public String toString() {
return task.toString();
diff --git a/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java b/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
index 0b0db4573..33403c978 100644
--- a/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
+++ b/guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
@@ -17,8 +17,9 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -31,10 +32,13 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* that, whenever possible, it is strongly preferred to modify those libraries to return {@code
* ListenableFuture} directly.
*
+ * <p>For interoperability between {@code ListenableFuture} and <b>{@code CompletableFuture}</b>,
+ * consider <a href="https://github.com/lukas-krecan/future-converter">Future Converter</a>.
+ *
* @author Sven Mawson
* @since 10.0 (replacing {@code Futures.makeListenable}, which existed in 1.0)
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class JdkFutureAdapters {
@@ -158,9 +162,10 @@ public final class JdkFutureAdapters {
* to return a proper ListenableFuture instead of using listenInPoolThread.
*/
getUninterruptibly(delegate);
- } catch (Throwable e) {
- // ExecutionException / CancellationException / RuntimeException / Error
+ } catch (ExecutionException | RuntimeException | Error e) {
+ // (including CancellationException)
// The task is presumably done, run the listeners.
+ // TODO(cpovirk): Do *something* in case of Error (and maybe RuntimeException)?
}
executionList.execute();
});
diff --git a/guava/src/com/google/common/util/concurrent/ListenableFuture.java b/guava/src/com/google/common/util/concurrent/ListenableFuture.java
index a8d9dd4de..cdc2ee110 100644
--- a/guava/src/com/google/common/util/concurrent/ListenableFuture.java
+++ b/guava/src/com/google/common/util/concurrent/ListenableFuture.java
@@ -36,10 +36,11 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
* asynchronous operations. You can chain them together manually with calls to methods like {@link
- * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)
- * Futures.transform}, but you will often find it easier to use a framework. Frameworks automate the
- * process, often adding features like monitoring, debugging, and cancellation. Examples of
- * frameworks include:
+ * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor) Futures.transform}
+ * (or {@link FluentFuture#transform(com.google.common.base.Function, Executor)
+ * FluentFuture.transform}), but you will often find it easier to use a framework. Frameworks
+ * automate the process, often adding features like monitoring, debugging, and cancellation.
+ * Examples of frameworks include:
*
* <ul>
* <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
diff --git a/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java b/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java
index 678a6c671..161fa895f 100644
--- a/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java
+++ b/guava/src/com/google/common/util/concurrent/ListenableFutureTask.java
@@ -18,6 +18,7 @@ import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -40,6 +41,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Sven Mawson
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class ListenableFutureTask<V extends @Nullable Object> extends FutureTask<V>
diff --git a/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java b/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
index ed8c9065a..4ef7ed36c 100644
--- a/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
+++ b/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.common.collect.Queues;
import com.google.errorprone.annotations.concurrent.GuardedBy;
@@ -52,6 +53,7 @@ import java.util.logging.Logger;
* the listeners can be delayed slightly so that locks can be dropped. Also, because {@link
* #dispatch} is expected to be called concurrently, it is idempotent.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class ListenerCallQueue<L> {
@@ -147,7 +149,7 @@ final class ListenerCallQueue<L> {
this.executor = checkNotNull(executor);
}
- /** Enqueues a event to be run. */
+ /** Enqueues an event to be run. */
synchronized void add(ListenerCallQueue.Event<L> event, Object label) {
waitQueue.add(event);
labelQueue.add(label);
diff --git a/guava/src/com/google/common/util/concurrent/ListeningExecutorService.java b/guava/src/com/google/common/util/concurrent/ListeningExecutorService.java
index 83ea759f8..b870e34fe 100644
--- a/guava/src/com/google/common/util/concurrent/ListeningExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/ListeningExecutorService.java
@@ -14,15 +14,21 @@
package com.google.common.util.concurrent;
+import static com.google.common.util.concurrent.Internal.toNanosSaturated;
+
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.DoNotMock;
+import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
@@ -106,4 +112,37 @@ public interface ListeningExecutorService extends ExecutorService {
<T extends @Nullable Object> List<Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException;
+
+ /**
+ * Duration-based overload of {@link #invokeAll(Collection, long, TimeUnit)}.
+ *
+ * @since 32.1.0
+ */
+ @J2ktIncompatible
+ default <T extends @Nullable Object> List<Future<T>> invokeAll(
+ Collection<? extends Callable<T>> tasks, Duration timeout) throws InterruptedException {
+ return invokeAll(tasks, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
+ }
+
+ /**
+ * Duration-based overload of {@link #invokeAny(Collection, long, TimeUnit)}.
+ *
+ * @since 32.1.0
+ */
+ @J2ktIncompatible
+ default <T extends @Nullable Object> T invokeAny(
+ Collection<? extends Callable<T>> tasks, Duration timeout)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ return invokeAny(tasks, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
+ }
+
+ /**
+ * Duration-based overload of {@link #awaitTermination(long, TimeUnit)}.
+ *
+ * @since 32.1.0
+ */
+ @J2ktIncompatible
+ default boolean awaitTermination(Duration timeout) throws InterruptedException {
+ return awaitTermination(toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
+ }
}
diff --git a/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java b/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java
index 25185b91a..19f9a8c32 100644
--- a/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/ListeningScheduledExecutorService.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
@@ -32,6 +33,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Chris Povirk
* @since 10.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface ListeningScheduledExecutorService
diff --git a/guava/src/com/google/common/util/concurrent/Monitor.java b/guava/src/com/google/common/util/concurrent/Monitor.java
index d01c6faa2..2ed31eda4 100644
--- a/guava/src/com/google/common/util/concurrent/Monitor.java
+++ b/guava/src/com/google/common/util/concurrent/Monitor.java
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Longs;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.Weak;
@@ -199,6 +200,7 @@ import javax.annotation.CheckForNull;
* @author Martin Buchholz
* @since 10.0
*/
+@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress.
@ElementTypesAreNonnullByDefault
@@ -1121,7 +1123,7 @@ public final class Monitor {
private boolean isSatisfied(Guard guard) {
try {
return guard.isSatisfied();
- } catch (Throwable throwable) {
+ } catch (RuntimeException | Error throwable) {
signalAllWaiters();
throw throwable;
}
diff --git a/guava/src/com/google/common/util/concurrent/MoreExecutors.java b/guava/src/com/google/common/util/concurrent/MoreExecutors.java
index 90776bc9e..ea3536957 100644
--- a/guava/src/com/google/common/util/concurrent/MoreExecutors.java
+++ b/guava/src/com/google/common/util/concurrent/MoreExecutors.java
@@ -17,10 +17,11 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
+import static java.util.Objects.requireNonNull;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
@@ -80,7 +81,7 @@ public final class MoreExecutors {
* @return an unmodifiable version of the input which will not hang the JVM
* @since 28.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ExecutorService getExitingExecutorService(
ThreadPoolExecutor executor, Duration terminationTimeout) {
@@ -101,7 +102,7 @@ public final class MoreExecutors {
* @param timeUnit unit of time for the time parameter
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static ExecutorService getExitingExecutorService(
@@ -122,7 +123,7 @@ public final class MoreExecutors {
* @param executor the executor to modify to make sure it exits when the application is finished
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
return new Application().getExitingExecutorService(executor);
@@ -141,7 +142,7 @@ public final class MoreExecutors {
* @return an unmodifiable version of the input which will not hang the JVM
* @since 28.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // java.time.Duration
public static ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor, Duration terminationTimeout) {
@@ -162,7 +163,7 @@ public final class MoreExecutors {
* @param timeUnit unit of time for the time parameter
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static ScheduledExecutorService getExitingScheduledExecutorService(
@@ -184,7 +185,7 @@ public final class MoreExecutors {
* @param executor the executor to modify to make sure it exits when the application is finished
* @return an unmodifiable version of the input which will not hang the JVM
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor) {
@@ -202,7 +203,7 @@ public final class MoreExecutors {
* JVM
* @since 28.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // java.time.Duration
public static void addDelayedShutdownHook(ExecutorService service, Duration terminationTimeout) {
addDelayedShutdownHook(service, toNanosSaturated(terminationTimeout), TimeUnit.NANOSECONDS);
@@ -219,7 +220,7 @@ public final class MoreExecutors {
* JVM
* @param timeUnit unit of time for the time parameter
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static void addDelayedShutdownHook(
@@ -228,6 +229,7 @@ public final class MoreExecutors {
}
/** Represents the current application to register shutdown hooks. */
+ @J2ktIncompatible
@GwtIncompatible // TODO
@VisibleForTesting
static class Application {
@@ -288,6 +290,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static void useDaemonThreadFactory(ThreadPoolExecutor executor) {
executor.setThreadFactory(
@@ -298,6 +301,7 @@ public final class MoreExecutors {
}
// See newDirectExecutorService javadoc for behavioral notes.
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static final class DirectExecutorService extends AbstractListeningExecutorService {
/** Lock used whenever accessing the state variables (runningTasks, shutdown) of the executor */
@@ -426,6 +430,7 @@ public final class MoreExecutors {
*
* @since 18.0 (present as MoreExecutors.sameThreadExecutor() since 10.0)
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ListeningExecutorService newDirectExecutorService() {
return new DirectExecutorService();
@@ -447,10 +452,10 @@ public final class MoreExecutors {
* complete, the listener runs immediately in that thread.
* <li>When a thread attaches a listener to a {@code ListenableFuture} that's
* <em>in</em>complete and the {@code ListenableFuture} later completes normally, the
- * listener runs in the the thread that completes the {@code ListenableFuture}.
+ * listener runs in the thread that completes the {@code ListenableFuture}.
* <li>When a listener is attached to a {@code ListenableFuture} and the {@code
- * ListenableFuture} gets cancelled, the listener runs immediately in the the thread
- * that cancelled the {@code Future}.
+ * ListenableFuture} gets cancelled, the listener runs immediately in the thread that
+ * cancelled the {@code Future}.
* </ol>
* Given all these possibilities, it is frequently possible for listeners to execute in UI
* threads, RPC network threads, or other latency-sensitive threads. In those cases, slow
@@ -540,6 +545,7 @@ public final class MoreExecutors {
*
* @since 23.3 (since 23.1 as {@code sequentialExecutor})
*/
+ @J2ktIncompatible
@GwtIncompatible
public static Executor newSequentialExecutor(Executor delegate) {
return new SequentialExecutor(delegate);
@@ -560,6 +566,7 @@ public final class MoreExecutors {
*
* @since 10.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ListeningExecutorService listeningDecorator(ExecutorService delegate) {
return (delegate instanceof ListeningExecutorService)
@@ -585,6 +592,7 @@ public final class MoreExecutors {
*
* @since 10.0
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
public static ListeningScheduledExecutorService listeningDecorator(
ScheduledExecutorService delegate) {
@@ -593,6 +601,7 @@ public final class MoreExecutors {
: new ScheduledListeningDecorator(delegate);
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static class ListeningDecorator extends AbstractListeningExecutorService {
private final ExecutorService delegate;
@@ -637,6 +646,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static final class ScheduledListeningDecorator extends ListeningDecorator
implements ListeningScheduledExecutorService {
@@ -715,6 +725,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static final class NeverSuccessfulListenableFutureTask
extends AbstractFuture.TrustedFuture<@Nullable Void> implements Runnable {
@@ -728,9 +739,9 @@ public final class MoreExecutors {
public void run() {
try {
delegate.run();
- } catch (Throwable t) {
+ } catch (RuntimeException | Error t) {
setException(t);
- throw Throwables.propagate(t);
+ throw t;
}
}
@@ -756,6 +767,7 @@ public final class MoreExecutors {
* An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService}
* implementations.
*/
+ @J2ktIncompatible
@GwtIncompatible
@ParametricNullness
static <T extends @Nullable Object> T invokeAnyImpl(
@@ -773,6 +785,7 @@ public final class MoreExecutors {
* implementations.
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
+ @J2ktIncompatible
@GwtIncompatible
@ParametricNullness
static <T extends @Nullable Object> T invokeAnyImpl(
@@ -854,6 +867,7 @@ public final class MoreExecutors {
/**
* Submits the task and adds a listener that adds the future to {@code queue} when it completes.
*/
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static <T extends @Nullable Object> ListenableFuture<T> submitAndAddQueueListener(
ListeningExecutorService executorService,
@@ -881,7 +895,7 @@ public final class MoreExecutors {
*
* @since 14.0
*/
- @Beta
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static ThreadFactory platformThreadFactory() {
if (!isAppEngineWithApiClasses()) {
@@ -908,6 +922,7 @@ public final class MoreExecutors {
}
}
+ @J2ktIncompatible
@GwtIncompatible // TODO
private static boolean isAppEngineWithApiClasses() {
if (System.getProperty("com.google.appengine.runtime.environment") == null) {
@@ -943,11 +958,13 @@ public final class MoreExecutors {
* Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} unless
* changing the name is forbidden by the security manager.
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static Thread newThread(String name, Runnable runnable) {
checkNotNull(name);
checkNotNull(runnable);
- Thread result = platformThreadFactory().newThread(runnable);
+ // TODO(b/139726489): Confirm that null is impossible here.
+ Thread result = requireNonNull(platformThreadFactory().newThread(runnable));
try {
result.setName(name);
} catch (SecurityException e) {
@@ -970,6 +987,7 @@ public final class MoreExecutors {
* @param executor The executor to decorate
* @param nameSupplier The source of names for each task
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) {
checkNotNull(executor);
@@ -993,6 +1011,7 @@ public final class MoreExecutors {
* @param service The executor to decorate
* @param nameSupplier The source of names for each task
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static ExecutorService renamingDecorator(
final ExecutorService service, final Supplier<String> nameSupplier) {
@@ -1022,6 +1041,7 @@ public final class MoreExecutors {
* @param service The executor to decorate
* @param nameSupplier The source of names for each task
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
static ScheduledExecutorService renamingDecorator(
final ScheduledExecutorService service, final Supplier<String> nameSupplier) {
@@ -1063,8 +1083,8 @@ public final class MoreExecutors {
* if the call timed out or was interrupted
* @since 28.0
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // java.time.Duration
public static boolean shutdownAndAwaitTermination(ExecutorService service, Duration timeout) {
return shutdownAndAwaitTermination(service, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -1094,8 +1114,8 @@ public final class MoreExecutors {
* if the call timed out or was interrupted
* @since 17.0
*/
- @Beta
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean shutdownAndAwaitTermination(
diff --git a/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java b/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java
index 3038ab7bd..905726597 100644
--- a/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java
+++ b/guava/src/com/google/common/util/concurrent/OverflowAvoidingLockSupport.java
@@ -16,6 +16,7 @@ package com.google.common.util.concurrent;
import static java.lang.Math.min;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.locks.LockSupport;
import javax.annotation.CheckForNull;
@@ -23,6 +24,7 @@ import javax.annotation.CheckForNull;
* Works around an android bug, where parking for more than INT_MAX seconds can produce an abort
* signal on 32 bit devices running Android Q.
*/
+@J2ktIncompatible
@ElementTypesAreNonnullByDefault
final class OverflowAvoidingLockSupport {
// Represents the max nanoseconds representable on a linux timespec with a 32 bit tv_sec
diff --git a/guava/src/com/google/common/util/concurrent/ParametricNullness.java b/guava/src/com/google/common/util/concurrent/ParametricNullness.java
index a745bf7bb..e8fcce6ee 100644
--- a/guava/src/com/google/common/util/concurrent/ParametricNullness.java
+++ b/guava/src/com/google/common/util/concurrent/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/util/concurrent/Platform.java b/guava/src/com/google/common/util/concurrent/Platform.java
index cfb96a0ad..92d2d12db 100644
--- a/guava/src/com/google/common/util/concurrent/Platform.java
+++ b/guava/src/com/google/common/util/concurrent/Platform.java
@@ -14,6 +14,9 @@
package com.google.common.util.concurrent;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.lang.Thread.currentThread;
+
import com.google.common.annotations.GwtCompatible;
import javax.annotation.CheckForNull;
@@ -26,5 +29,12 @@ final class Platform {
return expectedClass.isInstance(t);
}
+ static void restoreInterruptIfIsInterruptedException(Throwable t) {
+ checkNotNull(t); // to satisfy NullPointerTester
+ if (t instanceof InterruptedException) {
+ currentThread().interrupt();
+ }
+ }
+
private Platform() {}
}
diff --git a/guava/src/com/google/common/util/concurrent/RateLimiter.java b/guava/src/com/google/common/util/concurrent/RateLimiter.java
index 4b8b02554..1dd733f3b 100644
--- a/guava/src/com/google/common/util/concurrent/RateLimiter.java
+++ b/guava/src/com/google/common/util/concurrent/RateLimiter.java
@@ -23,6 +23,7 @@ import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.SmoothRateLimiter.SmoothBursty;
@@ -93,6 +94,7 @@ import javax.annotation.CheckForNull;
// TODO(user): switch to nano precision. A natural unit of cost is "bytes", and a micro precision
// would mean a maximum rate of "1MB/s", which might be small in some cases.
@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class RateLimiter {
diff --git a/guava/src/com/google/common/util/concurrent/Runnables.java b/guava/src/com/google/common/util/concurrent/Runnables.java
index 5503f68ae..f5b27f8af 100644
--- a/guava/src/com/google/common/util/concurrent/Runnables.java
+++ b/guava/src/com/google/common/util/concurrent/Runnables.java
@@ -14,7 +14,6 @@
package com.google.common.util.concurrent;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
@@ -22,7 +21,6 @@ import com.google.common.annotations.GwtCompatible;
*
* @since 16.0
*/
-@Beta
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Runnables {
diff --git a/guava/src/com/google/common/util/concurrent/SequentialExecutor.java b/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
index d0b600be8..c842d7e07 100644
--- a/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
+++ b/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
@@ -22,6 +22,7 @@ import static com.google.common.util.concurrent.SequentialExecutor.WorkerRunning
import static java.lang.System.identityHashCode;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.RetainedWith;
@@ -47,6 +48,7 @@ import javax.annotation.CheckForNull;
* If an {@code Error} is thrown, the error will propagate and execution will stop until it is
* restarted by a call to {@link #execute}.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class SequentialExecutor implements Executor {
diff --git a/guava/src/com/google/common/util/concurrent/Service.java b/guava/src/com/google/common/util/concurrent/Service.java
index dd0c7e6d9..9ca205de6 100644
--- a/guava/src/com/google/common/util/concurrent/Service.java
+++ b/guava/src/com/google/common/util/concurrent/Service.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.time.Duration;
@@ -55,6 +56,7 @@ import java.util.concurrent.TimeoutException;
* @since 9.0 (in 1.0 as {@code com.google.common.base.Service})
*/
@DoNotMock("Create an AbstractIdleService")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface Service {
diff --git a/guava/src/com/google/common/util/concurrent/ServiceManager.java b/guava/src/com/google/common/util/concurrent/ServiceManager.java
index 5ab95ffa6..42652c967 100644
--- a/guava/src/com/google/common/util/concurrent/ServiceManager.java
+++ b/guava/src/com/google/common/util/concurrent/ServiceManager.java
@@ -32,6 +32,7 @@ import static com.google.common.util.concurrent.Service.State.TERMINATED;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Stopwatch;
@@ -120,6 +121,7 @@ import java.util.logging.Logger;
* @author Luke Sandberg
* @since 14.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ServiceManager implements ServiceManagerBridge {
diff --git a/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java b/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java
index 7ae430e3d..71fe01c0b 100644
--- a/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java
+++ b/guava/src/com/google/common/util/concurrent/ServiceManagerBridge.java
@@ -17,6 +17,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.util.concurrent.Service.State;
@@ -25,6 +26,7 @@ import com.google.common.util.concurrent.Service.State;
* servicesByState()}, to ensure binary compatibility with older Guava versions that specified
* {@code servicesByState()} to return {@code ImmutableMultimap}.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
interface ServiceManagerBridge {
diff --git a/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java b/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
index c6ade6a3a..5d8df0777 100644
--- a/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
+++ b/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
@@ -16,9 +16,10 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -45,7 +46,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jens Nyman
* @since 1.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class SimpleTimeLimiter implements TimeLimiter {
@@ -111,6 +112,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
return interfaceType.cast(object);
}
+ @ParametricNullness
private <T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
throws Exception {
@@ -121,16 +123,12 @@ public final class SimpleTimeLimiter implements TimeLimiter {
Future<T> future = executor.submit(callable);
try {
- if (amInterruptible) {
- try {
- return future.get(timeoutDuration, timeoutUnit);
- } catch (InterruptedException e) {
- future.cancel(true);
- throw e;
- }
- } else {
- return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
- }
+ return amInterruptible
+ ? future.get(timeoutDuration, timeoutUnit)
+ : getUninterruptibly(future, timeoutDuration, timeoutUnit);
+ } catch (InterruptedException e) {
+ future.cancel(true);
+ throw e;
} catch (ExecutionException e) {
throw throwCause(e, true /* combineStackTraces */);
} catch (TimeoutException e) {
@@ -141,6 +139,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
@CanIgnoreReturnValue
@Override
+ @ParametricNullness
public <T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException, ExecutionException {
@@ -163,6 +162,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
@CanIgnoreReturnValue
@Override
+ @ParametricNullness
public <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, ExecutionException {
@@ -173,7 +173,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
Future<T> future = executor.submit(callable);
try {
- return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
+ return getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
@@ -213,7 +213,7 @@ public final class SimpleTimeLimiter implements TimeLimiter {
Future<?> future = executor.submit(runnable);
try {
- Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
+ getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
diff --git a/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java b/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
index ca7890590..6f21ab6a3 100644
--- a/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
+++ b/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
@@ -18,9 +18,11 @@ import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.math.LongMath;
import java.util.concurrent.TimeUnit;
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class SmoothRateLimiter extends RateLimiter {
diff --git a/guava/src/com/google/common/util/concurrent/Striped.java b/guava/src/com/google/common/util/concurrent/Striped.java
index 2ea61cb32..37fa2fd7e 100644
--- a/guava/src/com/google/common/util/concurrent/Striped.java
+++ b/guava/src/com/google/common/util/concurrent/Striped.java
@@ -16,8 +16,8 @@ package com.google.common.util.concurrent;
import static com.google.common.collect.Lists.newArrayList;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
@@ -82,7 +82,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Dimitris Andreou
* @since 13.0
*/
-@Beta
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class Striped<L> {
diff --git a/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java b/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
index 091f56e79..80727c59a 100644
--- a/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
+++ b/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
@@ -19,8 +19,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
-import com.google.errorprone.annotations.CheckReturnValue;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
import java.util.concurrent.Executors;
@@ -45,7 +45,7 @@ import javax.annotation.CheckForNull;
* @author Kurt Alfred Kluever
* @since 4.0
*/
-@CanIgnoreReturnValue
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ThreadFactoryBuilder {
@@ -69,6 +69,7 @@ public final class ThreadFactoryBuilder {
* "rpc-pool-1"}, {@code "rpc-pool-2"}, etc.
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setNameFormat(String nameFormat) {
String unused = format(nameFormat, 0); // fail fast if the format is bad or null
this.nameFormat = nameFormat;
@@ -81,6 +82,7 @@ public final class ThreadFactoryBuilder {
* @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
@@ -89,9 +91,13 @@ public final class ThreadFactoryBuilder {
/**
* Sets the priority for new threads created with this ThreadFactory.
*
+ * <p><b>Warning:</b> relying on the thread scheduler is <a
+ * href="http://errorprone.info/bugpattern/ThreadPriorityCheck">discouraged</a>.
+ *
* @param priority the priority for new Threads created with this ThreadFactory
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setPriority(int priority) {
// Thread#setPriority() already checks for validity. These error messages
// are nicer though and will fail-fast.
@@ -116,6 +122,7 @@ public final class ThreadFactoryBuilder {
* this ThreadFactory
* @return this for the builder pattern
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setUncaughtExceptionHandler(
UncaughtExceptionHandler uncaughtExceptionHandler) {
this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler);
@@ -131,6 +138,7 @@ public final class ThreadFactoryBuilder {
* @return this for the builder pattern
* @see MoreExecutors
*/
+ @CanIgnoreReturnValue
public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) {
this.backingThreadFactory = checkNotNull(backingThreadFactory);
return this;
@@ -143,7 +151,6 @@ public final class ThreadFactoryBuilder {
*
* @return the fully constructed {@link ThreadFactory}
*/
- @CheckReturnValue
public ThreadFactory build() {
return doBuild(this);
}
@@ -164,6 +171,8 @@ public final class ThreadFactoryBuilder {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = backingThreadFactory.newThread(runnable);
+ // TODO(b/139735208): Figure out what to do when the factory returns null.
+ requireNonNull(thread);
if (nameFormat != null) {
// requireNonNull is safe because we create `count` if (and only if) we have a nameFormat.
thread.setName(format(nameFormat, requireNonNull(count).getAndIncrement()));
diff --git a/guava/src/com/google/common/util/concurrent/TimeLimiter.java b/guava/src/com/google/common/util/concurrent/TimeLimiter.java
index 0245fec3c..babb63431 100644
--- a/guava/src/com/google/common/util/concurrent/TimeLimiter.java
+++ b/guava/src/com/google/common/util/concurrent/TimeLimiter.java
@@ -16,8 +16,8 @@ package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.Internal.toNanosSaturated;
-import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.time.Duration;
@@ -34,8 +34,8 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @author Jens Nyman
* @since 1.0
*/
-@Beta
@DoNotMock("Use FakeTimeLimiter")
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface TimeLimiter {
@@ -146,6 +146,7 @@ public interface TimeLimiter {
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@CanIgnoreReturnValue
+ @ParametricNullness
<T extends @Nullable Object> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException, ExecutionException;
@@ -167,6 +168,7 @@ public interface TimeLimiter {
* @since 28.0
*/
@CanIgnoreReturnValue
+ @ParametricNullness
default <T extends @Nullable Object> T callWithTimeout(Callable<T> callable, Duration timeout)
throws TimeoutException, InterruptedException, ExecutionException {
return callWithTimeout(callable, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -193,6 +195,7 @@ public interface TimeLimiter {
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@CanIgnoreReturnValue
+ @ParametricNullness
<T extends @Nullable Object> T callUninterruptiblyWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, ExecutionException;
@@ -216,6 +219,7 @@ public interface TimeLimiter {
* @since 28.0
*/
@CanIgnoreReturnValue
+ @ParametricNullness
default <T extends @Nullable Object> T callUninterruptiblyWithTimeout(
Callable<T> callable, Duration timeout) throws TimeoutException, ExecutionException {
return callUninterruptiblyWithTimeout(
diff --git a/guava/src/com/google/common/util/concurrent/TimeoutFuture.java b/guava/src/com/google/common/util/concurrent/TimeoutFuture.java
index ed8a7bfdb..aca623054 100644
--- a/guava/src/com/google/common/util/concurrent/TimeoutFuture.java
+++ b/guava/src/com/google/common/util/concurrent/TimeoutFuture.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -34,6 +35,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* in an {@link ExecutionException}) if the specified duration expires. The delegate future is
* interrupted and cancelled if it times out.
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class TimeoutFuture<V extends @Nullable Object> extends FluentFuture.TrustedFuture<V> {
diff --git a/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java b/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
index a1add8bcb..1dc1094d4 100644
--- a/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
+++ b/guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
@@ -17,6 +17,7 @@ package com.google.common.util.concurrent;
import static java.util.logging.Level.SEVERE;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Locale;
@@ -28,6 +29,7 @@ import java.util.logging.Logger;
* @author Gregory Kick
* @since 8.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class UncaughtExceptionHandlers {
@@ -68,7 +70,7 @@ public final class UncaughtExceptionHandlers {
try {
logger.log(
SEVERE, String.format(Locale.ROOT, "Caught an exception in %s. Shutting down.", t), e);
- } catch (Throwable errorInLogging) {
+ } catch (RuntimeException | Error errorInLogging) {
// If logging fails, e.g. due to missing memory, at least try to log the
// message and the cause for the failed logging.
System.err.println(e.getMessage());
diff --git a/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java b/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
index 713f4a69e..a0ec427ee 100644
--- a/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
+++ b/guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
@@ -38,7 +38,7 @@ public class UncheckedExecutionException extends RuntimeException {
/*
* Ideally, this class would have exposed only constructors that require a non-null cause. We
* might try to move in that direction, but there are complications. See
- * https://github.com/jspecify/nullness-checker-for-checker-framework/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
+ * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecTransfer.java#L789
*/
/** Creates a new instance with {@code null} as its detail message. */
diff --git a/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java b/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
index 8e30fca37..181de101f 100644
--- a/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
+++ b/guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
@@ -15,6 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import javax.annotation.CheckForNull;
/**
@@ -23,6 +24,7 @@ import javax.annotation.CheckForNull;
* @author Kevin Bourrillion
* @since 1.0
*/
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public class UncheckedTimeoutException extends RuntimeException {
diff --git a/guava/src/com/google/common/util/concurrent/Uninterruptibles.java b/guava/src/com/google/common/util/concurrent/Uninterruptibles.java
index 09ace92fa..f95678bae 100644
--- a/guava/src/com/google/common/util/concurrent/Uninterruptibles.java
+++ b/guava/src/com/google/common/util/concurrent/Uninterruptibles.java
@@ -20,6 +20,7 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.time.Duration;
@@ -52,6 +53,7 @@ public final class Uninterruptibles {
// methods is identical, save for method being invoked.
/** Invokes {@code latch.}{@link CountDownLatch#await() await()} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void awaitUninterruptibly(CountDownLatch latch) {
boolean interrupted = false;
@@ -77,7 +79,7 @@ public final class Uninterruptibles {
*
* @since 28.0
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static boolean awaitUninterruptibly(CountDownLatch latch, Duration timeout) {
return awaitUninterruptibly(latch, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -87,7 +89,7 @@ public final class Uninterruptibles {
* Invokes {@code latch.}{@link CountDownLatch#await(long, TimeUnit) await(timeout, unit)}
* uninterruptibly.
*/
- @CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean awaitUninterruptibly(CountDownLatch latch, long timeout, TimeUnit unit) {
@@ -118,6 +120,7 @@ public final class Uninterruptibles {
*
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static boolean awaitUninterruptibly(Condition condition, Duration timeout) {
return awaitUninterruptibly(condition, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -129,6 +132,7 @@ public final class Uninterruptibles {
*
* @since 23.6
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean awaitUninterruptibly(Condition condition, long timeout, TimeUnit unit) {
@@ -153,6 +157,7 @@ public final class Uninterruptibles {
}
/** Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void joinUninterruptibly(Thread toJoin) {
boolean interrupted = false;
@@ -178,6 +183,7 @@ public final class Uninterruptibles {
*
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void joinUninterruptibly(Thread toJoin, Duration timeout) {
joinUninterruptibly(toJoin, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -187,6 +193,7 @@ public final class Uninterruptibles {
* Invokes {@code unit.}{@link TimeUnit#timedJoin(Thread, long) timedJoin(toJoin, timeout)}
* uninterruptibly.
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static void joinUninterruptibly(Thread toJoin, long timeout, TimeUnit unit) {
@@ -269,6 +276,7 @@ public final class Uninterruptibles {
* @since 28.0
*/
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // java.time.Duration
@ParametricNullness
public static <V extends @Nullable Object> V getUninterruptibly(
@@ -295,6 +303,7 @@ public final class Uninterruptibles {
* @throws TimeoutException if the wait timed out
*/
@CanIgnoreReturnValue
+ @J2ktIncompatible
@GwtIncompatible // TODO
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@ParametricNullness
@@ -322,6 +331,7 @@ public final class Uninterruptibles {
}
/** Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static <E> E takeUninterruptibly(BlockingQueue<E> queue) {
boolean interrupted = false;
@@ -348,6 +358,7 @@ public final class Uninterruptibles {
* @throws IllegalArgumentException if some property of the specified element prevents it from
* being added to the given queue
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) {
boolean interrupted = false;
@@ -373,6 +384,7 @@ public final class Uninterruptibles {
*
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void sleepUninterruptibly(Duration sleepFor) {
sleepUninterruptibly(toNanosSaturated(sleepFor), TimeUnit.NANOSECONDS);
@@ -380,6 +392,7 @@ public final class Uninterruptibles {
// TODO(user): Support Sleeper somehow (wrapper or interface method)?
/** Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} uninterruptibly. */
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
@@ -410,6 +423,7 @@ public final class Uninterruptibles {
*
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static boolean tryAcquireUninterruptibly(Semaphore semaphore, Duration timeout) {
return tryAcquireUninterruptibly(semaphore, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -421,6 +435,7 @@ public final class Uninterruptibles {
*
* @since 18.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean tryAcquireUninterruptibly(
@@ -434,6 +449,7 @@ public final class Uninterruptibles {
*
* @since 28.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static boolean tryAcquireUninterruptibly(
Semaphore semaphore, int permits, Duration timeout) {
@@ -447,6 +463,7 @@ public final class Uninterruptibles {
*
* @since 18.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean tryAcquireUninterruptibly(
@@ -478,6 +495,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static boolean tryLockUninterruptibly(Lock lock, Duration timeout) {
return tryLockUninterruptibly(lock, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
@@ -489,6 +507,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean tryLockUninterruptibly(Lock lock, long timeout, TimeUnit unit) {
@@ -518,6 +537,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static void awaitTerminationUninterruptibly(ExecutorService executor) {
// TODO(cpovirk): We could optimize this to avoid calling nanoTime() at all.
@@ -530,6 +550,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
public static boolean awaitTerminationUninterruptibly(
ExecutorService executor, Duration timeout) {
@@ -542,6 +563,7 @@ public final class Uninterruptibles {
*
* @since 30.0
*/
+ @J2ktIncompatible
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime")
public static boolean awaitTerminationUninterruptibly(
diff --git a/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java b/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
index 5a3c3927a..d6684b809 100644
--- a/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
@@ -16,8 +16,10 @@ package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
+import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
@@ -41,7 +43,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Chris Nokleberg
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class WrappingExecutorService implements ExecutorService {
@@ -67,6 +69,7 @@ abstract class WrappingExecutorService implements ExecutorService {
try {
wrapped.call();
} catch (Exception e) {
+ restoreInterruptIfIsInterruptedException(e);
throwIfUnchecked(e);
throw new RuntimeException(e);
}
@@ -143,6 +146,7 @@ abstract class WrappingExecutorService implements ExecutorService {
}
@Override
+ @CanIgnoreReturnValue
public final List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
diff --git a/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java b/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
index 48f23c12c..d533fc632 100644
--- a/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
+++ b/guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
@@ -15,7 +15,7 @@
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtIncompatible;
-import com.google.errorprone.annotations.CanIgnoreReturnValue;
+import com.google.common.annotations.J2ktIncompatible;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -30,7 +30,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
*
* @author Luke Sandberg
*/
-@CanIgnoreReturnValue // TODO(cpovirk): Consider being more strict.
+@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
abstract class WrappingScheduledExecutorService extends WrappingExecutorService
diff --git a/guava/src/com/google/common/util/concurrent/package-info.java b/guava/src/com/google/common/util/concurrent/package-info.java
index a2533c1fc..7df382a54 100644
--- a/guava/src/com/google/common/util/concurrent/package-info.java
+++ b/guava/src/com/google/common/util/concurrent/package-info.java
@@ -15,14 +15,13 @@
/**
* Concurrency utilities.
*
- * <p>Commonly used types include {@link com.google.common.util.concurrent.ListenableFuture} and
- * {@link com.google.common.util.concurrent.Service}.
+ * <p>Commonly used types include {@link ClosingFuture}, {@link ListenableFuture}, and {@link
+ * Service}.
*
- * <p>Commonly used utilities include {@link com.google.common.util.concurrent.Futures}, {@link
- * com.google.common.util.concurrent.MoreExecutors}, and {@link
- * com.google.common.util.concurrent.ThreadFactoryBuilder}.
+ * <p>Commonly used utilities include {@link Futures}, {@link MoreExecutors}, {@link
+ * ThreadFactoryBuilder}, and {@link Uninterruptibles}.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/guava/src/com/google/common/xml/ParametricNullness.java b/guava/src/com/google/common/xml/ParametricNullness.java
index e4e5d12f0..439707a2e 100644
--- a/guava/src/com/google/common/xml/ParametricNullness.java
+++ b/guava/src/com/google/common/xml/ParametricNullness.java
@@ -26,23 +26,56 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
- * Marks a "top-level" type-variable usage as the closest we can get to "non-nullable when
- * non-nullable; nullable when nullable" (like the Android <a
- * href="https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/NullFromTypeParam.java">{@code
- * NullFromTypeParam}</a>).
+ * Annotates a "top-level" type-variable usage that takes its nullness from the type argument
+ * supplied by the user of the class. For example, {@code Multiset.Entry.getElement()} returns
+ * {@code @ParametricNullness E}, which means:
+ *
+ * <ul>
+ * <li>{@code getElement} on a {@code Multiset.Entry<@NonNull String>} returns {@code @NonNull
+ * String}.
+ * <li>{@code getElement} on a {@code Multiset.Entry<@Nullable String>} returns {@code @Nullable
+ * String}.
+ * </ul>
+ *
+ * This is the same behavior as type-variable usages have to Kotlin and to the Checker Framework.
+ * Contrast the method above to:
+ *
+ * <ul>
+ * <li>methods whose return type is a type variable but which can never return {@code null},
+ * typically because the type forbids nullable type arguments: For example, {@code
+ * ImmutableList.get} returns {@code E}, but that value is never {@code null}. (Accordingly,
+ * {@code ImmutableList} is declared to forbid {@code ImmutableList<@Nullable String>}.)
+ * <li>methods whose return type is a type variable but which can return {@code null} regardless
+ * of the type argument supplied by the user of the class: For example, {@code
+ * ImmutableMap.get} returns {@code @Nullable E} because the method can return {@code null}
+ * even on an {@code ImmutableMap<K, @NonNull String>}.
+ * </ul>
*
* <p>Consumers of this annotation include:
*
* <ul>
* <li>Kotlin, for which it makes the type-variable usage (a) a Kotlin platform type when the type
* argument is non-nullable and (b) nullable when the type argument is nullable. We use this
- * to "undo" {@link ElementTypesAreNonnullByDefault}.
+ * to "undo" {@link ElementTypesAreNonnullByDefault}. It is the best we can do for Kotlin
+ * under our current constraints.
+ * <li>NullAway, which will <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1204399671">treat it
+ * identically to {@code Nullable} as of version 0.9.9</a>. To treat it that way before then,
+ * you can set {@code
+ * -XepOpt:NullAway:CustomNullableAnnotations=com.google.common.base.ParametricNullness,...,com.google.common.util.concurrent.ParametricNullness},
+ * where the {@code ...} contains the names of all the other {@code ParametricNullness}
+ * annotations in Guava. Or you might prefer to omit Guava from your {@code AnnotatedPackages}
+ * list.
* <li><a href="https://developers.google.com/j2objc">J2ObjC</a>
* <li>{@code NullPointerTester}, at least in the Android backport (where the type-use annotations
* {@code NullPointerTester} would need are not available) and in case of <a
* href="https://bugs.openjdk.java.net/browse/JDK-8202469">JDK-8202469</a>
* </ul>
*
+ * <p>This annotation is a temporary hack. We will remove it after we're able to adopt the <a
+ * href="https://jspecify.dev/">JSpecify</a> nullness annotations and <a
+ * href="https://github.com/google/guava/issues/6126#issuecomment-1203145963">tools no longer need
+ * it</a>.
*/
@GwtCompatible
@Retention(RUNTIME)
diff --git a/guava/src/com/google/common/xml/package-info.java b/guava/src/com/google/common/xml/package-info.java
index bd4c95216..869327627 100644
--- a/guava/src/com/google/common/xml/package-info.java
+++ b/guava/src/com/google/common/xml/package-info.java
@@ -17,7 +17,7 @@
* for
* XML.
*
- * <p>This package is a part of the open-source <a href="http://github.com/google/guava">Guava</a>
+ * <p>This package is a part of the open-source <a href="https://github.com/google/guava">Guava</a>
* library.
*/
@CheckReturnValue
diff --git a/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java b/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java
index c987065e4..e728822a8 100644
--- a/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java
+++ b/guava/src/com/google/thirdparty/publicsuffix/PublicSuffixPatterns.java
@@ -42,7 +42,13 @@ public final class PublicSuffixPatterns {
/** If a hostname is contained as a key in this map, it is a public suffix. */
public static final ImmutableMap<String, PublicSuffixType> EXACT =
TrieParser.parseTrie(
- "a&0&0trk9--nx?27qjf--nx?e9ebgn--nx?nbb0c7abgm--nx??1&2oa08--nx?apg6qpcbgm--nx?hbbgm--nx?rdceqa08--nx??2&8ugbgm--nx?eyh3la2ckx--nx?qbd9--nx??3&2wqq1--nx?60a0y8--nx??4x1d77xrck--nx?6&1f4a3abgm--nx?2yqyn--nx?5b06t--nx?axq--nx?ec7q--nx?lbgw--nx??883xnn--nx?9d2c24--nx?a&a?it??b!.&gro?lim?moc?sr,t&en?opsgolb,?ude?vog??abila?c?ihsot?m?n??c!.&b&a?m?n??c&b?g?q??ep?fn?k&s?y??ln?no?oc,p&i-on,ohsdaerpsym,?sn?t&n?opsgolb,?un?ysrab,?i&ma?r&emarp?fa??sroc??naiva?s??d&ats?n&eit?oh??om?sa?tl??eg?f&c?ob??g!emo?naripi?oy??hskihs?i&cnal?dem?hs?k!on??sa!.snduolc,??jnin?k&aso?dov?ede?usto??l!.&c,gro?moc?ofni?r&ep?nb,?t&en?ni??ude?vog??irgnahs?le&nisiuc?rbmuder???m!.&ca?gro?oc?sserp?ten?vog??ahokoy?e00sf7vqn--nx?m??n!.&ac?cc?eman?gro?ibom?loohcs?moc?ni?o&c?fni?rp??r&d?o??s&u?w??vt?xm??av?is?olecrab?tea??p!.&bog?ca?d&em?ls??g&ni?ro??mo&c?n??oba?ten?ude??c?g7hyabgm--nx?ra!.&461e?6pi?iru?nru?rdda-ni?siri???s??q!.&eman?gro?hcs?lim?moc?t&en?opsgolb,?ude?vog???r&az?emac?f4a3abgm--nx?n!d5uhf8le58r4w--nx??u&kas?tan???s!.&bup?dem?gro?hcs?moc?ten?ude?vog??ac!.uban.iu,?iv??t&ad?elhta?led?oyot??u!.&a&cinniv?emirc?i&hzhziropaz?stynniv??s&edo?sedo??tlay?vatlop??bs?cc,d&argovorik?o!roghzu??tl,?e&hzhziropaz?nvir?t??f&i?ni,?g&l?ro??hk?i&stvinrehc?ykstynlemhk??k&c?m?s&nagul?t&enod?ul??v&iknarf-onavi?orteporp&end?ind?????l&iponret?opotsa&bes?ves??p??m&k?oc?s?yrk??n&c?d?i?osrehk?v?ylov??o&c,nvor??p&d?p,z??r&c?imotihz?k?ymotyhz??sk?t&en?l?z??ude?v:c?e&alokin?ik??i&alokym?hinrehc?krahk?vl?yk??k?l?o&g!inrehc??krahk??r?,xc,y&ikstinlemhk?mus?s&akrehc?sakrehc?tvonrehc???z&ib,u????v!aj?bb?et?iv??waniko?x&a?iacal??yogan?z&.&bew?c&a?i&n?rga???gro?l&im?oohcs??m&on?t??o&c!.topsgolb,?gn??radnorg?sin?t&en?la??ude?vog?wal??zip???b&00ave5a9iabgm--nx?1&25qhx--nx?68quv--nx?e2kc1--nx??2xtbgm--nx?3&b2kcc--nx?jca1d--nx??4&6&1rfz--nx?qif--nx??96rzc--nx??7w9u16qlj--nx?88uvor--nx?a&0dc4xbgm--nx?c?her?n?ra?t??b!.&erots?gro?moc?o&c?fni??ten?ude?v&og?t??zib??a??c&j?s??d&hesa08--nx?mi??g?l!.&gro?moc?ten?ude?vog??m??s!.&gro?moc?ten?ude?vog???tc-retarebsnegmrev--nx?u&lc!.&elej,snduolc,y&nop,srab,??smas??p!.ysrab,??wp-gnutarebsnegmrev--nx??c&1&1q54--nx?hbgw--nx??2e9c2czf--nx?4&4ub1km--nx?a1e--nx?byj9q--nx?erd5a9b1kcb--nx??8&4xx2g--nx?c9jrb2h--nx??9jr&b&2h--nx?54--nx?9s--nx??c&eg--nx?h3--nx?s2--nx???a!.&gro?lim?moc?rrd,ten?ude?vog??3a09--nx!.&ca1o--nx?gva1c--nx?h&ca1o--nx?za09--nx??ta1d--nx?ua08--nx???da??b&a?b?ci?f76a0c7ylqbgm--nx?sh??c!.&eugaelysatnaf,gnipparcs,liamwt,nwaps.secnatsni,revres-emag,s&nduolc,otohpym,seccaptf,?xsc,?0atf7b45--nx?a1l--nx??e!.&21k?bog?dem?esab,gro?l&aiciffo,im??moc?nif?o&fni?rp??ten?ude?vog??beuq?n?smoc??fdh?i&l&buperananab?ohtac??n&agro?ilc?osanap??sum?tic??l!.&gro?moc?oc?ten?ude?vog?yo,?l??m!.&mt?ossa??p1akcq--nx??n!.&mon?ossa??i?p??relcel?s!.&gro?moc?ten?ude?vog???t!.&e&m,w,?hc,?s?w??v!.&e0,gro?lim?moc?ten?ude?v&g:.d,,og????wp?yn??d&2urzc--nx?3&1wrpk--nx?c&4b11--nx?9jrcpf--nx???5xq55--nx?697uto--nx?75yrpk--nx?9ctdvkce--nx?a!.mon?d?er?olnwod??b2babgm--nx?c!.vog?g9a2g2b0ae0chclc--nx??e&m!bulc??r!k??sopxe?timil?w??fc?g!.&ude?vog???h&d3tbgm--nx?p?t??i!.&ased?bew?ca?etrof,golbw,hcs?lim?o&c!.topsgolb,?g??palf,r&egolb,o??sepnop?ten?ym?zib??b?ordna?p?rdam??l&iub?og?row??m!.&ed,ot,pj,t&a,opsgolb,???n&a&b?l!.citats:.&setis,ved,?,raas???ob?uf??o&of?rp??r&a&c&tiderc?yalcrab??ugnav??ef506w4b--nx?k!.&oc,ude,?jh3a1habgm--nx??of??s!.&dem?gro?moc?ofni?ten?ude?v&og?t???m!kcrem???t!.topsgolb,excwkcc--nx?l??uolc!.&a&bura-vnej.&1ti,abura.rue.1ti,?tcepsrep,xo:.&ku,nt,?,?b&dnevar,ewilek:.sc,,?citsalej.piv,drayknil,elej,gnitsohdnert.&ed,hc,?letemirp:.ku,,m&edaid,ialcer.&ac,ku,su,??n&evueluk,woru,?r&epolroov,o&pav,tnemele,??tenraxa.1-se,ululetoj,xelpciffart,yawocne.ue,??za5cbgn--nx??e&1&53wlf--nx?7a1hbbgm--nx?ta3kg--nx??2a6a1b6b1i--nx?3ma0e1cvr--nx?418txh--nx?707b0e3--nx?a!.&ca?gro?hcs?lim?oc?t&en?opsgolb,?vog??09--nx??b!.&ca?gnitsohbew,nevueluk.yxorpze,pohsdaerpsym,snoitulostsohretni.duolc,topsgolb,?ortal?ut!uoy???c&0krbd4--nx?a&lp!.oc,?ps!.&lla4sx,rebu,tsafym,?artxe??sla??i!ffo??n&a&d?iler?nif?rusni!efil?srelevart???eics!.oby,??rofria??d!.&1sndnyd,42pi-nyd,7erauqs,amil4,b&ow-nrefeilgitsng--nx,rb-ni,vz-nelletsebgitsng--nx,?decalpb,e&daregtmueart,mohsnd,nihcamyek,?hcierebsnoissuksid,keegnietsi,lsd-ni,moc,n&-i-g-o-l,aw-ym,e&lletsebgitsnüg,sgnutiel,?i&emtsi,lreb-n&i,yd,??norblieh-sh.ti.segap,oitatsksid-ygolonys,pv&-n&i,yd,?nyd,?refeilgitsnüg,?orp-ytinummoc,p&h21,iog:ol,,ohsdaerpsym,?r&e&ntrapdeeps.remotsuc,su&-lautriv,lautriv,?t&adpusnd,tub-ni,uor-ym,?vres&-e&bucl,mohym,?bew-emoh:.nyd,,luhcs,??ogiv-&niem,ym,??s&d-&onys,ygolonys,?nd&-&dd,nufiat,sehcsimanyd,tenretni,yard,?isoc.nyd,ps,yard,?oper-&nvs,tig,?sndd:.&nyd,sndnyd,?,?topsgolb,vresi-&niem,tset,?xi2,y&awetag-&llawerif,ym,?srab,tic-amil,?zten&mitbel,sadtretteuf,??art!.oby,?i&sdoow?ug??nil?on--nx??e!.&bil?dem?eif?gro?irp?kiir?moc!.topsgolb,?pia?ude?vog??ei?ffoc?gg?r&f?ged???f&a&c?s??il??g!.&gro?lim?moc?t&en?vp??ude?vog??a&f?gtrom?p!.&3xlh,detalsnart,grebedoc,kselp,sndp,tengam,xlh,y&cvrp,kcor,???rots?yov??elloc?na&hcxe?ro??roeg?ug??i!.&pohsdaerpsym,topsgolb,vog??tilop?v&bba?om???j!.&fo,gro?oc?ten???k!.&c&a?s??e&m?n??ibom?o&c!.topsgolb,?fni?g??ro??i&b?l?n???l&a&dmrif?s!.rof,rof???b&a?i&b?dua???c&aro?ric??dnik?g!oog??i&bom?ms??l&asal?erauqa??ppa?uhcs?yts!efil???m!.&4&32i,p&ct,v,??66c,ailisarb,b&dnevar,g-raegelif,?ca?duolcsd,e&d-raegelif,i&-raegelif,lpad:.tsohlacol,,?pcm,?g&ro?s-raegelif,?hctilg,k&catsegde,uoc,?noitatsksid,o&bmoy,c!ku,?t&nigol,poh,??p&ion,j-raegelif,ohbew,?qbw,r&aegelif,idcm,ofsnd,?s&dym,ndd,ti!bt,?umhol,?t&en?s&acdnuos,ohon,??u&a-raegelif,de??v&irp?og??y&golonys,olpedew,srab,??a&g?n!.&reh.togrof,sih.togrof,???em?i&rp?twohs??orhc?w??n!goloc?i&lno!.&egats-oree,oree,ysrab,??w??o!.&derno:.gnigats,,ecivres,knilemoh,r&ednu,of,??hp?latipac?ts&der?e&gdirb?rif???z!.&66duolc,amil,sh,???ruoblem??om?p!.&bog?gro?lim?mo&c?n??t&en?opsgolb,?ude??irg?yks??r!.&mo&c?n??ossa?topsgolb,?a&c!htlaeh??pmoc?wtfos??bc?eh?if?ots!.&e&rawpohs,saberots,?yflles,??taeht?u&ces?sni?t&inruf?necca??za???s!.&a!bap.us,?b!ibnal?rofmok??c!a??d!b?n&arb?ubroflanummok???e?f!noc,?g!ro??h!f??i!trap??k!shf??l?m!oc,t??n!mygskurbrutan??o?p!ohsdaerpsym,p??r!owebdluocti,?s!serp?yspoi,?t!opsgolb,?u?vhf?w?x!uvmok??y?z??a&c?el?hc??i&er?urc??nesemoh?roh?uoh??t&a&d?ts&e!laer??lla???is!.&e&lej,nilnigol,r&etnim,ocevon,?winmo,?k&rowtenoilof,wnf,?laicosnepo,n&eyb,oyc,?spvtsaf,thrs,xulel,ysrab,?bew??ov?ra?t&ioled?ol??utitsni??u&lb?qi&nilc?tuob???v!.&21e?b&ew?ib?og??ce&r?t??erots?gro?lim?m&o&c?n??rif??o&c?fni??rar?stra?t&en?ni??ude?vog??as?e3gerb2h--nx?i&l!.xlh,?rd?ssergorp??ol??w&kct--nx?r??xul?y!.&gro?lim?moc?ten?ude?vog????f&0f3rkcg--nx?198xim--nx?280xim--nx?7vqn--nx?a!.&gro?moc?ten?ude?vog???b!.vog?wa9bgm--nx??c!.topsgolb,a1p--nx!.&a14--nx,b8lea1j--nx,c&avc0aaa08--nx,ma09--nx,?f&a1a09--nx,ea1j--nx,?gva1c--nx,nha1h--nx,pda1j--nx,zila1h--nx,??ns??ea1j--nx?g?iam?l&a1d--nx?og??n!.&bew?cer?erots?m&oc?rif??ofni?re&hto?p??stra?ten???orp?p!.&gro?moc?ude???rus?t!w??vd7ckaabgm--nx?w??g&2&4wq55--nx?8zrf6--nx??3&44sd3--nx?91w6j--nx!.&a5wqmg--nx?d&22svcw--nx?5xq55--nx??gla0do--nx?m1qtxm--nx?vta0cu--nx????455ses--nx?5mzt5--nx?69vqhr--nx?7&8a4d5a4prebgm--nx?rb2c--nx??a!.&gro?mo&c?n??oc?ten??vd??b!.&0?1?2?3?4?5?6?7?8?9?a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t!opsgolb,?u?v?w?x?y!srab,?z???c!b?za9a0cbgm--nx??e!.&eman?gro?ics?lim?moc!.topsgolb,?nue?ten?ude?vog??a??g!.&ayc,gro?lenap:.nomead,,oc?saak,ten???i&a?v??k!.&g&olb,ro??ku,lim?moc?oi,pj,su,ten?ude?v&og?t,???m!.&drp?gro?lim?m&o&c?n??t??oc?ude?vog??pk??n!.&dtl,eman?gro?hcs?i!bom??l&im?oc,?m&oc!.topsgolb,?rif,?neg,ogn,ten?ude?vog??aw?i!b!mulp??car?d&art?dew??h&sif?tolc??k&iv?oo&b?c???ls?n&aelc?iart??p!pohs??re&enigne?tac??t&ad?ekram!.&htiw,morf,??hgil?lusnoc?neg?ov?soh!.tfarcnepo,??vi&g?l???o!s??u&rehcisrev?smas?tarebsnegömrev???o&d?lb?og!.&duolc,etalsnart,???r&2n084qlj--nx?ebmoolb?o!.&77ndc.c:sr,,a&remacytirucesym,t&neimip,sivretla,?z,?bew-llams,d&ab-yrev-si,e&sufnocsim,vas-si,?nuof-si,oog-yrev-si,uolc&arfniarodef,mw,??e&a,cin-yrev-si,grof&loot,peh,?l&as-4-ffuts,poeparodef,?m&-morf,agevres,ohruoyslles,?n&ozdop,uma.elet,?r&ehwongniogyldlob,iwym,uces-77ndc.nigiro.lss,?t&adidnac-a-si,is&-ybboh,golb,???fehc-a-si,golbymdaer,k&eeg-a&-si,si,?h,nut,?l&i&amwt,ve-yrev-si,?lawerif&-ym,ym,?sd-ni,?m&acssecca,edom-elbac,?n&af&blm,cfu,egelloc,lfn,s&citlec-a-si,niurb-a-si,tap-a-si,?xos-a-si,?ibptth,o&itatsksid,rviop,?pv-ni,?o&jodsnd,tp&az,oh,??p&i&-on,fles,?o&hbew,tksedeerf,?tf&e&moh,vres,?ym,??r&e&gatop,ppepteews,su-xunil-a-si,?gmtrec,vdmac,?s&a&ila&nyd,snd,?nymsd,?b&alfmw,bevres,?d&ikcet.3s,ylimaf,?eirfotatophcuoc,j,koob-daer,ltbup,nd&-won,deerf,emoh,golb,kcud,mood,nyd:.&emoh,og,?,ps,rvd,tog,uolc,?s&a-skcik,ndd,?tnemhcattaomb,u,?t&ce&jorparodef.&duolc,gts.so.ppa,so.ppa,?riderbew,?e&ews-yrev-si,nretni&ehtfodne,fodne,??hgink-a-si,oi-allizom,s&ixetn&od,seod,?o&h-emag,l-si,?rifyam,??ue:.&a&-q,c,?cm,dc,e&b,d,e,i,m,s,?g&b,n,?hc,i&f,s,?k&d,m,s,u,?l&a,i,n,p,?n&c,i,?o&n,r,ssa,?pj,r&f,g,h,k,t,?s&e,i:rap,,u,?t&a,en,i,l,m,ni,p,?u&a,de,h,l,r,?vl,y&c,m,?z&c,n,??,vresnyd,x&inuemoh,unilemoh,?y&limafxut,srab,???ub&mah?oj???s!.&delacsne,gro?moc?rep?t&en?opsgolb,?ude?vog??gb639j43us5--nx??t?u!.&c&a?s??en?gro?moc?o&c?g??ro?topsgolb,??v!.ta,a1c--nx??wsa08--nx??h&0ee5a3ld2ckx--nx?4wc3o--nx!.&a&2xyc3o--nx?3j0hc3m--nx?ve4b3c0oc21--nx??id1kzuc3h--nx?l8bxi8ifc21--nx?rb0ef1c21--nx???8&8yvfe--nx?a7maabgm--nx??b!.&gro?moc?ten?ude?vog??mg??c!.&7erauqs,amil4,duolc-drayknil,gniksnd,p&h21,ohsdaerpsym,?sndtog,topsgolb,wolf.e&a.1pla,nigneppa,?xi2,ytic-amil,?aoc?et?ir!euz??r&aes!errecnac??uhc??sob?taw!s???d0sbgp--nx?f&2lpbgm--nx?k??g!.&gro?lim?moc?ude?vog???m!a1j--nx??ocir?p!.&gro?i?lim?moc?ogn?ten?ude?vog???s!.&g&nabhsah,ro??l&im?xv,?m&oc?roftalp.&cb,su,tne,ue,??pib,ten?vog?won,yolpedew,?a&c?nom??i&d?f?ri???t!.&ca?enilno,im?ni?o&c?g??pohs,ro?ten??iaf!.oby,?laeh!.arh,?orxer?ra&ba?e???vo!.lopdren,?zb??i&3tupk--nx?7a0oi--nx?a!.&ffo?gro?moc?ten?uwu,?1p--nx?bud?dnuyh?tnihc??b!.&gro?moc?oc?ro?ude??ahduba?o!m!.&duolcsd,ysrab,???s??c!.&ayb-tropora--nx?ca?d&e?m??esserp?gro?ln,moc?nif,o&c?g?ssa??ro?t&en?ni?roporéa??ude?vuog??cug?t??d&dk?ua??e&bhf--nx?piat??f!.&aw5-nenikkh--nx,dnala?i&ki,spak,?mroftalpduolc.if,nenikkäh,pohsdaerpsym,retnecatad.&omed,saap,?topsgolb,yd,?onas??g!.&d&om?tl??gro?moc?ude?vog???h&c&atih?ra??s&abodoy?ibustim???juohs?k!.&gro?moc?ofni?ten?ude?vog?zib??b4gc--nx?iw?nisleh?s?uzus??l!.&aac,topsgolb,?drahcir?iamsi??maim?n!.&b&ew?og??ca?gro?lim?mo&c?n??ni?o&c?fni??pp?t&en?ni??ude?zib??airpic?i&hgrobmal?m??re??om?rarref?s!.&egaptig,ppatig,topsgolb,?ed??t&aresam?i&c?nifni??rahb?tagub??ut?v!.&21k?gro?moc?oc?ten???wik?xa&rp?t??yf??j&6pqgza9iabgm--nx?8da1tabbgl--nx?b!.&ossa?topsgolb,uaerrab?vuog???d?f!.&ca?eman?gro?lim?moc?o&fni?rp??ten?vog?zib???nj?s?t!.&bew?c&a?in??eman?gro?lim?moc?o&c?g??t&en?ni?set??ude?vog?zib???yqx94qit--nx??k&8uxp3--nx?924tcf--nx?arfel?c&a&bdeef?lb??ebdnul?ilc?reme??d!.&erots,ger,mrif,oc,pohsdaerpsym,topsgolb,zib,?t??e&es?samet??h!.&a&4ya0cu--nx?5wqmg--nx??b3qa0do--nx?cni,d&2&2svcw--nx?3rvcl--nx??5xq55--nx?tl,?g&a0nt--nx?la0do--nx?ro??i&050qmg--nx?7a0oi--nx?xa0km--nx??m&1qtxm--nx?oc??npqic--nx?saaces,t&en?opsgolb,?ude?v&di?og?ta0cu--nx??xva0fz--nx?人&个?個?箇??司公?府政?絡&網?网??織&組?组??织&組?组??络&網?网??育&敎?教???n??i&tsob?vdnas??l!.&bew?c&a?os??dtl?gro?hcs?letoh?moc?nssa?ogn?prg?t&en?ni??ude?vog??at?cd?is??m!.&eman?fni?gro?moc?t&en?opsgolb,?ude?vog???n&ab!cfdh?etats?mmoc?t&en?fos??u??i!l!.&noyc,pepym,??p???oob?p!.&b&ew?og??gro?kog?m&af?oc??nog?ofni?pog?sog?ten?ude?vog?zib???row!.&morf,ot,?ten!.&htumiza,nolt,o&c,vra,??doof???s!.topsgolb,?t?u!.&c&a?lp??d&om?tl??e&cilop?m??gro!.&gul:g,,sgul,yr&ettoly&lkeew,tiniffa,?tneelffar,???lenap-tnednepedni,n&noc,oissimmoc-&layor,tnednepedni,??o&c!.&bunsorter.tsuc,e&lddiwg,n&ilnoysrab,ozgniebllew,??krametyb.&hd,mv,?omida,p&i-on,ohsdaerpsym,?t&fihsreyal.j,opsgolb,?vres-hn,ysrab,??rpoc,?psoh,shn?t&en?nmyp,seuqni-tnednepedni,?vog!.&eci&ffoemoh,vres,?ipa,??weiver-tnednepedni,y&riuqni-&cilbup,tnednepedni,?srab,????l&04sr4w--nx?a!.&gro?lim?moc?t&en?opsgolb,?ude?vog??bolg?c?ed?g!el??i&c&nanif!.oc,lpl??os??romem?tnedurp??n&if?oitanretni??t&i&gid!.sppaduolc:.nodnol,,?p&ac?soh???ned?ot??utum!nretsewhtron???c!.&bog?lim?oc?topsgolb,vog???dil?e&datic?n&ahc?nahc!gnikooc?levart?rehtaew???t!ria?tam??vart??f&8f&pbgo--nx?tbgm--nx??a?n??g!.&gro?moc?oc?ten?ude?xx,zib,??h&d?op??i!.&21k?ca?fdi?gro?inum?oc!.&egapvar,redrotibat,topsgolb,??ten?vog??a&f?m&e?g?toh???m?r??l&a&b&esab?t&eksab!.&sua,zn,??oof???c?mt??e&d?hs??ihmailliw?j??m!.&esserp?gro?moc?ten?ude?v&og?uog????n!.&no&med,rtsic,?oc,pohsdaerpsym,retsulc-gnitsoh,topsgolb,yalphk,?o??o&a?btuf?l!.gmo,?o&c!.&ed,rotnemele,??hcs??rit?u??p!.&a&cin&diws?gel??d&g,ortso?urawon??i&dem?mraw?nydg,?k&elo&guld?rtso??slopolam?tsu?ytsyrut??l&ip?o&kzs?w&-awolats?oksnok????n&erapohs,img?zcel,?rog&-ai&bab?nelej??j?z??syn?tsaim?w&a&l&eib?i?o??zsraw??o&namil?tainop,??z&eiwolaib?mol???c&e&iw&alselob?o&nsos?rtso???le&im?zrogz???orw,p??d&em,ia?ragrats?uolc&inu,sds,??e&c&i&lrog?w&ilg,o&hc&arats?orp??klop?tak????yzreibok??i&csjuoniws?ksromop?saldop??l&ahdop?opo??napokaz,tatselaer?z&romop?swozam???g&alble?ezrbo&lok?nrat??ro??hcyzrblaw?i&csomohcurein?grat?klawus??k&e&rut?walcolw??in&byr?diws,sark,?le?o&nas?tsylaib??rob&el?lam??s&als?jazel?nadg,puls?rowezrp???l&colw?e&r?vart??i&am?m???m&o&c?dar?n?tyb??s&g?iruot??t!a???n&a&gaz?nzop,?i&bul?cezczs?lbul,molow?nok?zd&eb?obeiws???uleiw?y&tzslo?z&rtek?seic????o&c,fni?k&celo?zdolk??lkan?n&leim?pek?t&uk?yzczs??z&copo?eing?rowaj???rga?tua?w&ejarg?ogarm???p&e&eb,lks!emoh,??klwwortso?ohs!-ecremmoce,daerpsym,??romophcaz?sos?t&aiwop?en?opos,ra,sezc??ude?v&irp?og!.&a&p?s!w???bni&p?w??ci?dtiw?essp?fiw?g&imu?u??hiiw?m&igu?rio?u!o???nds?o&ks?p!pu??s?wtsorats??p&a?sp!mk?pk?wk??u&m?p??wk?z??r&ksw?s??s&i?oiw?u?zu??talusnok?w&gzr?i&p?rg?w??m?opu?u!imzw???zouw????w&a&l&corw?sizdow??w??o&golg?k&ark,ul?zsurp??r&az?gew??t&rabul,sugua??z&coks?sezr????xes?y&buzsak?d&azczseib?ikseb??hcyt?n&jes?lod-zreimizak??pal?r&ogt?uzam??walup?zutrak??z&am-awar?c&aprak?iwol?zsogdyb??dalezc?ib?s&i&lak?p??uklo????l??r&as?f?s??s!.&gro?moc?ten?ude?vog???t!.vog??ubnatsi?x3b689qq6--nx?yc5rb54--nx??m&00tsb3--nx?1qtxm--nx?981rvj--nx?a!.&aayn,enummoc?gro?moc?o&c?idar,ken,?t&en?opsgolb,??c!bew??dretsma?e&rts?t!.&citsalej,esruocsid,???fma?xq--nx??b!.&gro?moc?ten?ude?vog??i??c!.&moc?oc?ten?vog???d!.&gro?moc?ten?ude?vog???f!.&gro?moc?oidar,ten?ude??i??g!vu96d8syzf--nx??h?i!.&ca?gro?moc?o&c!.&clp?dtl???r,?t&en?t??vt??k?rbg4--nx??k!.&drp?e&rianiretev?sserp??gro?lim?m&o&c?n??t??nicedem?ossa?pooc?s&eriaton?neicamrahp?sa??ude?v&og?uog????l&if?ohkcots??o!.&dem?gro?m&oc?uesum??o&c?rp??ten?ude?vog??b?c!.&2aq,3pmevres,5sndd,a&c&-morf,ir&bafno,fa,??g&-morf,oy-sehcaet,?i-morf,m&-morf,all&-a-si,amai,??p&-morf,c-a-si,?r&emacytirucesym,odih,?s,tadtsudgniht,v-morf,w-morf,z,?b&dnevarym,ew&-sndnyd,draiw.segap,ottad,?ildts.ipa,?c&amytirucesemoh,d-morf,esyrcs,itsalej.omed,n&-morf,vym,?p&kroweht,ytirucesemoh,?q,rievres,s-morf,?d&aerotffuts,e&calpb,ifitrec-&si,ton-si,?llortnocduolc,rewopenignepw:.sj,,tsohecapsppa,?i&-morf,rgevissam.saap,?m-morf,n&-morf,abeht-htiw-si,?s-morf,uolc&-noitatsyalp,hr,iafaw.&d&ej,yr,?nol,?meaeboda,panqym:-&ahpla,ved,?,smetsystuo,tekcilc,ved&j,pw,??vreser,wetomer,?e&butuoyhtiw,ciffo-sndnyd,d:-morf,o&celgoog,n&il.srebmem,neve.&1-&su,ue,?2-&su,ue,?3-&su,ue,?4-&su,ue,????,erf&-sndnyd,sndd,?filflahevres,gnahcxeevres,i&hcet-a-si,p-sekil,?k&auqevres,irtsretnuocevres,?l&bitpa-no,googhtiw,?m&agevres,ina-otni-si,oh-&sndnyd,ta-sndnyd,??n&-morf,ilno&-evreser,ysrab,?og-si,?r&alfduolcyrt,ehwynanohtyp:.ue,,ihcec,?srun-a-si,t&i&nuarepo,s&-ybboh,aloy,tipohs,xiw,??omer-sndnyd,upmocsma,ysgolb,?v&als-elcibuc-a-si,i&lsndd,tavresnoc-a-si,??z&amkcar,eelg,iig,??fehc-a-si,g&ni&gats-&raeghtua,swennwot,?ksndd,robsikrow,tsoh-bt.etis,?o&fgp,lb&-sndnyd,pawodni,sihtsetirw,???h&n-morf,o-morf,?i&fiwehtno,h-morf,kiw-sndnyd,m-morf,pdetsoh,r-morf,w-morf,z&ihcppa,nilppa,??jn-morf,k&a&-morf,erfocsic,?cils-si,eeg&-a&-si,si,?sndd,?h,latsnaebcitsale:.&1-&htuos-pa,lartnec-&ac,ue,?ts&ae&-&as,su,?ht&ron-pa,uos-pa,??ew-&su,ue,vog-su,???2-ts&ae&-su,ht&ron-pa,uos-pa,??ew-&su,ue,??3-ts&aehtron-pa,ew-ue,??,o-morf,r&adhtiwtliub,ow&-&sndnyd,ta-sndnyd,?ten-orehkcats,??u,?l&a&-morf,colottad,rebil-a-si,?f-morf,i&-morf,am&-sndnyd,detsohpw,??l&ecelffaw,uf-ytnuob:.a&hpla,teb,?,?ppmswa,ru-&elpmis,taen,?ssukoreh,xegap,?m&n-morf,pml.ppa,rofe&pyt.orp,rerac-htlaeh,?sacrasevres,uirarret-yltsaf,?n&a&cilbuper-a-si,f&-sllub-a-si,racsan-a-si,?i&cisum-a-si,ratrebil-a-si,??c,dc&hsums,umpw,xirtrepmi,?eerg-a-si,i-morf,m-morf,o&ehtnaptog,isam-al-a-tse,r&italik,tap-el-tse,?s&iam-al-a-tse,replausunu,??pj,t-morf,?o&bordym,c,hce-namtsop,jodsnd,m&-morf,ed-baltlow,?n:iloxip,,ttadym,?p&2pevres,aelutym,i&-sndnyd,fles,ogol,ruoy&esol,hctid,?ym&eerf,teg,??ohsdaerpsym,pa&-rettalp,anis:piv,,esaberif,k1,lortnocduolc,oifilauq,r&aegyks,oetem:.ue,,?tnorfegap,ukoreh,?t&fevres,thevres,??r&a:-morf,tskcor-a-si,,b,e&d&iv&erp-yb-detsoh.saap,orpnwo,?ner&.ppa,no,??e&bevres,nigne-na-si,?ggolb&-a-si,ndi,?h&caet-a-si,pargotohp-a-si,?krow-drah-a-si,n&gised-a-si,ia&rtlanosrep-a-si,tretne-na-si,??p&acsdnal-a-si,eekkoob-a-si,?retac-a-si,subq,tn&ecysrab,iap-a-si,uh-a-si,?vres&-&ki.&cpj-rev-duolcj,duolcj,?s&ndnyd,pvtsaf,??inim,nmad,sak,?y&alp-a-si,wal-a-si,?zilibomdeepsegap,?g,ituob,k,mgrp.nex,o&-morf,sivdalaicnanif-a-si,t&areleccalabolgswa,c&a-na-si,od-a-si,?susaym,??p-morf,u&as-o-nyd,e&tsoh.&duolc-gar,hc-duolc-gar,?ugolb-nom-tse,?omuhevres,??s&a&apod,ila&nyd,snd,?nymsd,vnacremarf,?bbevres,ci&p&-sndnyd,evres,?tcatytiruces,?dylimaf,e&cived-anelab,itilitu3,lahw-eht-sevas,mag-otni-si,t&i&iis,sro,?yskciuq,??i&ht2tniop,pa&elgoog,tneltneg,??jfac,k&-morf,aerf-ten,colb&egrof,pohsym,??m&-morf,cxolb,?n&d&-pmet,dyard,golb,htiwssem,mood,tog,?kselp,nyd,ootrac-otni-si,?o&-xobeerf,xobeerf,?ppa&raeghtua,tneg,?r&ac-otni-si,e&ntrap-paelut,tsohmaerd,??s&e&l-rof-slles,rtca-na-si,?ibodym,?tsaeb-cihtym.&a&llicno,zno,?ilay,lacarac,re&gitnef,motsuc,?sv,toleco,x:n&ihps,yl,?,?u,wanozama.&1-&htuos-pa&-3s,.&3s,etisbew-3s,kcatslaud.3s,??la&nretxe-3s,rtnec-&ac&-3s,.&3s,etisbew-3s,kcatslaud.3s,??ue&-3s,.&3s,etisbew-3s,kcatslaud.3s,????ts&ae&-&as&-&3s,etisbew-3s,?.kcatslaud.3s,?su:-etisbew-3s,.kcatslaud.3s,,?ht&ron-pa&-&3s,etisbew-3s,?.kcatslaud.3s,?uos-pa&-&3s,etisbew-3s,?.kcatslaud.3s,???ew-&su-&3s,etisbew-3s,?ue&-&3s,etisbew-3s,?.kcatslaud.3s,?vog-su-&3s,spif-3s,????2-ts&ae&-su&-3s,.&3s,etisbew-3s,kcatslaud.3s,??ht&ron-pa&-3s,.&3s,etisbew-3s,kcatslaud.3s,??uos-pa&-&3s,etisbew-3s,?.kcatslaud.3s,???ew-&su-&3s,etisbew-3s,?ue&-3s,.&3s,etisbew-3s,kcatslaud.3s,????3&-tsew-ue&-3s,.&3s,etisbew-3s,kcatslaud.3s,??s,??yasdrocsid,?t&arcomed-a-si,c&-morf,etedatad.&ecnatsni,omed,??eel&-si,rebu-si,?hgilfhtiwletoh,m-morf,n&atnuocca-na-si,e&duts-a-si,r-ot-ecaps,tnocresu&buhtig,e&capsppa,donil.pi,lbavresbo.citats,?pl,???ops&edoc,golb,ppa,?s&i&hcrana-&a-si,na-si,?laicos-a-si,pareht-a-si,tra-na-si,xetn&od,seod,??oh&piym,sfn,??u&-morf,nyekcoh-asi,?v-morf,?u&-rof-slles,4,e,h,oynahtretramssi,r:ug-a-si,,?v&n-morf,rdlf,w-morf,?w&o&lpwons-yrt,zok,?ww100,?x&bsbf.sppa,em,i&nuemoh,rtrepmi,?obaniateb,t-morf,unilemoh,?y&a&bnx:.&2u,lacol-2u,?,l&erottad,pezam,?wetag-llawerif,?dnacsekil,fipohsym,k&-morf,niksisnd,?rotceridevitcaym,u:goo,,w-morf,x&alagkeeg,orp&hsilbup,mapson.duolc,???zesdrocsid,?inu??m!.&dna,rof,??or?tsla??p!.nwo,?raf!.jrots,etats??s?t!.&gro?lim?mo&c?n??oc?ten?ude?vog???u&esum!.&a&92chg-seacinumocelet-e-soierroc--nx?atnav?c&i&aduj?rfatsae??rollam??d&anac?enomaledasac?irolf??e&raaihpledalihp?srednu??g&hannavas?oonattahc??hamo?i&auhsu?bmuloc!hsitirb??dem?groeg?hpledalihp?l&artsua?etalif??n&igriv?rofilac??ssur?tsonod??ksa&la?rben??l&lojal?q-snl--nx?uossim!trof???m&a&bala?nap??enic?o&m?r???n&a&cirema?idni??edasap?ilorachtuos?olecrab??r&abrabatnas?ezzivs??su?t&nalta?osennim??zalp??c&dnotgnihsaw?ebeuq?i&depolcycne?ficap?hpargonaeco?lbup?sum?t&carporihc?lec?naltadim??vu??yn??d&a&dhgab?etsmraf?m?orliar??i&rdam?ulegnedleeb??leif?n&a!l&gne?nif?ragyduj?t&ocs?rop??yram???u&brofsdgybmeh?osdnaegami???r&augria?ofxo???e&c&a&l&ap?phtrib??ps??n&a&lubma?tsiser??e&fedlatsaoc?gilletni?ics!foyrotsih????pein?rof??d&nukneklov?revasem??e&rt?tsurt??f&atnas?ildliw??g&a&lliv?tireh!lanoitan???dirbmac?rog??i&cnum?nollaw??koorbrehs?l&ab?bib?cycrotom?i&ssim?txet??oks?tsac??m&affollah?it!iram??utsoc??n&golos?ilno?recul??r&a&uqs?waled!foetats???i&hs&acnal?kroy?pmahwen??otsih??omitlab?ut&an?cetihcra?inruf?luc!irga?su???vuol??s&abatad?iacnarf?sius?uoh!lum???t&a&locohc?rak?ts!e!yrtnuoc!su?????imesoy?tevroc??u&qihpargonaeco?velleb??vit&caretni?omotua???f&iuj?ohgrub??g&n&i&dliub?ginerevmuesum?kiv?lahw?nim?peekemit?vil??ulmmastsnuk??orf?r&ebnrats?u&b&ierf?le?m&ah?uan??ram?s&mailliw!lainoloc??naitsirhc?retepts??zlas??ob&irf?mexul?????h&atu?c&raeser?sirotsih?uot??g&ea1h--nx?rubsttip??si&tirb?wej??t&laeh?ro&n?wtrof??uo&mnom?y????i&d6glbhbd9--nx?iawah?k&nisleh?s??lad!rodavlas??sissa?tannicnic??k&c&nivleeg?olc!-dna-hctaw?dnahctaw???fj?inebis?l&is?ofron??na&rfenna?t??oorbnarc?r&am&ned?reiets??oy!wen????l&a&ci&dem?golo&eahcra?meg?oz??natob?rotsih??ertnom?iromem?noita&cude?n??oc?rutluc?trop?utriv?van??e&nurb?s&ab?surb??utriv??i&artnogero?sarb??l&a&besab?hsnoegrus??e&hs?rdnevle??i&b?m!dniw????o&bup?ohcs?tsirb???m&a&dretsma?ets?h&netlehc?rud???ct?elas!urej??l&if?ohkcots?u??raf?silanruoj?u&esumyrotsihlarutan?ira&tenalp?uqa??terobra???n&a&c!irema!evitan???gihcim?i&dni?tpyge??mfoelsi?wehctaksas??e&d&alokohcs?ews?rag!cinatob?lacinatob?s&nerdlihc?u????gahnepoc?hcneum?laftsew?ppahcsnetewruutan?r&dlihc?ednaalv?hu!dnutamieh???sseig??gised!dn&atra?utsnuk???h&ab!nesie??ojts??i&lreb?tsua??l&eok?ocnil??n&ob?urbneohcs??o&dnol?gero?i&s&iv&dnadnuos?elet??nam??t&a&c&inummoc?ude!tra???dnuof?erc?i&cossa?va??kinummokelet?nissassa?r&belectsevrah?oproc?tsulli??silivic?t&nalp?s??vres&erp?noclatnemnorivne??zilivic??c&elloc?if-ecneics??ibihxe???ri?s&dnah?imaj?reffej?sral??t&erbepac?nilc?sob???r&e&b?dom?tsew?uab?zul??obredap??vahnebeok?wot??o&2a6v-seacinumoc--nx?ablib?c&edtra?ixemwen?sicnarfnas??elap?g&a&cihc?to??eidnas??i&cadnuf?diserp?ratno??llecitnom?mitiram?nirot?r&htna?ienajedoir???pohskrow?qari?r&aw!dloc?livic??dd?e&b&ma?yc??irrac?llimsiwel?naksiznarf?papswen?t&aeht?exe?nec!ecneics?larutluc?muesum?tra??s&ehc&nam?or??neum??upmoc???ia!nepo??obal?u&asonid?obal?takirak???s&a&l&g?l&ad?eh???xet??di&k?pardnarg??e&cneics!larutan??dnal?hcsi&deuj?rotsih!nizidem?rutan??selhcs??itinamuh?l&aw?egnasol?l&e&rutansecneics?xurb??iasrev???r&e&em?ugif??tsac??suohcirotsih?u&en?q&adac?itna!nacirema?su????õçacinumoc!elet-e-soierroc???gnirpsmlap?htab?i&lopanaidni?rap?uoltnias?xa??l&essurb?lod??mraeriflanoitan?n&a&blats?l??erdlihc?oi&snam?tacinummoc!elet-dna-stsop???äl??re&dnalf?lttes?mraf?nim?tnececneics??s&alg?erp??t&farc!dnastra??nalp?olip?ra!e&nif?vitaroced!su???su?xuaeb???u&b!muloc??cric???t&agilltrop?cejorp?dats?e&esum?kramnaidni??iorted?ne&m&elttes?norivne?piuqemraf??vnoc??oped?r&a!drib?enif?gttuts?hsiwej?kcor?n&acirema?ootrac??tamsa?yraropmetnoc??op&aes?snart?wen??ufknarf??s&a&cdaorb?octsae??ewhtuos?ilayol?nuk?r&ohnemled?uhlyram??urt???u&a&bgreb?etalpodaroloc??rmyc??w&ocsom?rn??x&esse?ineohp?nam?tas??y&a&bekaepasehc?w&etag?liar???camrahp?doc?e&hsub?l&ekreb?l&av!eniwydnarb??ort???n&dys?om??rrus?s&nreug?rejwen???golo&e&ahcra?g??motne?nh&cet?te??oz?po&rhtna?t??roh??hpargotohp?l&etalihp?imaf??m&edaca?onortsa??n&atob?yn??ps?r&a&ropmetnoc?tilim??e&diorbme?llag!tra??vocsid??lewej?nosameerf?otsih!dnaecneics?ecneics?gnivil!su??la&col?rutan??retupmoc?su??tsudnidnaecneics??spelipe?t&eicos!lacirotsih??i&nummoc?srevinu??nuoc???z&arg?iewhcs?nil?ojadab?urcatnas??моки?םילשורי???rof??z!.&ca?gro?hcs?lim?moc?o&c?fni??ten?ude?vog?zib????n&315rmi--nx?a&brud?cilbuper?f?grompj?hkaga?idraug?m?ol?ssin?u&hix?qna??varac?yalo??b!.&gro?moc?oc,ten?ude?vog??c??c!.&ah?bh?c&a?s??d&5xq55--nx?g?s?uolctnatsni,?eh?g&la0do--nx?ro??h&a?q?s??i&7a0oi--nx?h??j&b?f?t?x?z??kh?l&h?im?j??m&n?oc!.swanozama.&1-htron-nc.3s,be.1-&htron-nc,tsewhtron-nc,????n&h?l?s?y??om?qc?s&g?j??ten?ude?vog?wt?x&g?j?n?s??z&g?x??司公?絡網?络网??b??d&g!.ypnc,?ka??e&drag?erg?fuak?gawsklov?hctik?i&libommi?w??m!.r&iaper,of,??po?r!ednaalv??sier?ves??g!.&ca?gro?moc?ten?ude?vog??is&ed!.ssb,?irev???h!.&bog?cc,gro?lim?moc?ten?ude???i!.&bew,c&a?in??dni?esabapus,gro?lim?mrif?neg?oc?s&er?nduolc,?t&en?opsgolb,?ude?vog?ysrab,?elknivlac?griv?ks?lreb?p?v?w!.taht,?x??k!.&gro?ten?ude?vog???l&eok?ocnil??m!.&cyn,gro?ude?vog???o&dnol!.&fo,ni,??i&hsaf!.fo,?n&o?utiderc??siv!orue??t&a&cude!.oc,?dnuof?tsyalp??c&etorp?u&a?rtsnoc?????kin?las?mrom?nac?p&q?uoc??s&iam?pe?scire??t&ron?sob??zama??p!.&gro?oc?ten?ude?vog??k??r&e&c?yab??op!.eidni,??s!.&gro?moc?osrep?t&opsgolb,ra??ude?v&inu?uog????t!.&d&ni?uolcegnaro,?gro?ltni?m&oc!nim??siruot??nif?o&fni?srep??sne?t&an?en??vog??m??u&f?r!.&bdnevar,lper,retropno,s&h,revres,?tnempoleved,??stad?xamay?y??v!.&ca?eman?gro?htlaeh?moc?o&fni?rp??t&en?ni?opsgolb,?ude?vog?zib???wo&rc?t!epac????o&76i4orfy--nx?a!.&bp?de?go?oc?ti?vg??boat??b!.&a&ci&sum?tilop??i&c&arcomed?neic??golo&ce?ncet??m&edaca?onoce??rt&ap?sudni??vilob??n&egidni?icidem??serpme?tsiver?vitarepooc??b&ew?og??dulas?e&rbmon?tr&a?op&ed?snart????g&olb?ro??ikiw?l&a&noi&canirulp?seforp??rutan??im??moc?o&fni?lbeup?rga?tneimivom??saiciton?t&askt?en?ni??ude?vt??h?iew?olg??c!.&bew?cer?dr&c,rac,?esabapus,gro?ipym,l&im?per:.di,,?m&o&c!.topsgolb,?n??rif??ofni?s&egap&dael,l,?tra??t&4n,en?ni??ude?vog??a?e?in?mara?s&edarb?ic???d!.&b&ew?og??dls?gro?lim?moc?t&en?ra??ude?vog??agoba?if?zd7acbgm--nx??e&c?d&iv?or??morafla??f!ni!.&e&g&delwonk-fo-l&errab,lerrab,?ellocevoli,?ht-skorg,rom-rof-ereh,tadpusn:d,,?llatiswonk,macrvd,ofni-v,p&i&-on,fles,?ohbew,?ruo-rof,s&iht-skorg,nd&-cimanyd,nyd,uolc,??tsrifyam,ysrab,zmurof,???g&el?n!am?ib???hwsohw?i!.&35nyd,8302,a&minifed,tad-b,?b&altig,uhtig,?czh,d&in,u&olc&iaznab.ppa,ropav,?rd,??e&c&apsinu.1rf-duolc,ivedniser,?donppad.sndnyd,egipa,lej,nilnigol,sufxob,t&i&beulb,snoehtnap,?newtu,ybeeb.saap,??gni&gatsniser.secived,tsohytsoh,?ilpu,k&coregrof.di,orgn,ramytefasresworb,?moc?n&mtsp:.kcom,,yded,?ot&oq,pyrctfihs,?p&opilol,pa&-arusah,e&nalpkcab,tybeeb.1dkes,???r&e&tsneum-hf,vres&cisab,lautriv,??ial.sppa,?s&codehtdaer,gnihtbew,nemeis-om,pparevelc,t&acdnas,ekcit,??t&e&kcubtib,notorp,?i&belet,detfihs,gude,kecaps,?raedon.egats,s&ohg,udgniht.&cersid.&dvreser,tsuc,?dorp.tsuc,gnitset.&dvreser,tsuc,?ved.&dvreser,tsuc,????vgib.0ku,whs,x&bslprbv.g,cq,rotide,?y&olpedew,srab,??b?d&ar?u&a?ts???j?r?syhp??j!.&eman?gro?hcs?lim?moc?ten?ude?vog???ll&ag?o??m!.&gro?moc?ten?ude?vog??g?il?mi?orp??n!.&a&0&b-ekhgnark--nx?c-iehsrgev--nx?g-lksedlig--nx?k-negnanvk--nx??1&p-nedragy--nx?q-&asierrs--nx?grebsnt--nx?lado-rs--nx?n&egnidl--nx?orf-rs--nx??regnayh--nx?ssofenh--nx??r-datsgrt--nx?s-ladrjts--nx?v-y&senner--nx?vrejks--nx???3g-datsobegh--nx?4&5-&dnaleprj--nx?goksnerl--nx?tednalyh--nx??6-neladnjm--nx?s-&antouvachb--nx?impouvtalm--nx??y-&agrjnevvad--nx?ikhvlaraeb--nx???7k-antouvacchb--nx?8&k-rekie-erv--nx?l-ladrua-rs--nx?m-darehsdrk--nx??a!.sg??bct-eimeuvejsemn--nx?d&do?iisevvad?lov?narts?uas??f&1-&l--nx?s--nx??2-h--nx??g&10aq0-ineve--nx?av?ev?lot?r&ajn&evvad?u??ájn&evvad?u????h?iz-lf--nx?j&ddadab?sel??k&el?hoj&sarak?šárák??iiv&ag&na&el?g??ŋ&ael?ág???ran???l&f?lahrevo?o&ms?s??sennev?t-&ilm--nx?tom--nx??u&-edr--nx?s??øms??muar?n&0-tsr--nx?2-dob--nx?5-&asir--nx?tals--nx??a&r!-i-om?f?t??t??douvsatvid?kiv?m&os?øs??n&od?ød??ra?sen?t&aouvatheig?ouv&a&c&ch&ab?áb??h&ab?áb???n??i&ag?ág??sa&mo?ttvid??án???z-rey--nx?ær&f?t???o&p-&ladr--nx?sens--nx??q-nagv--nx?r-asns--nx?s-kjks--nx?v-murb--nx?w-&anr&f--nx?t--nx??ublk--nx???ppol?q&0-t&baol--nx?soum--nx?veib--nx??x-&ipphl--nx?r&embh--nx?imph--nx???y-tinks--nx??r&f-atsr--nx?g-&an&ms--nx?nd--nx??e&drf--nx?ngs--nx??murs--nx?netl--nx?olmb--nx?sorr--nx??h-&a&lms--nx?yrf--nx??emjt--nx??i&-&lboh--nx?rsir--nx?y&d&ar--nx?na--nx??ksa--nx?lem--nx?r&ul--nx?yd--nx????stu??j-&drav--nx?rolf--nx?sdav--nx??kua?l-&drojf--nx?lares--nx??m-tlohr--nx?n-esans--nx?olf?p-sdnil--nx?s-ladrl--nx?tih?v-rvsyt--nx??s&a&ns?ons??i&ar?er&dron?r&os?øs???ár??la&g?h??mor!t??sir?uf?åns??t&koulo&nka?ŋká??la?p-raddjb--nx?r-agrjnu--nx?s&aefr&ammah?ámmáh??orf?r&o?ø???u-vreiks--nx??u&h-dnusel--nx?i-&drojfk--nx?vleslm--nx??j-ekerom--nx?k-rekrem--nx?u-&dnalr--nx?goksr--nx?sensk--nx??v-nekyr--nx?w-&k&abrd--nx?ivjg--nx??oryso--nx??y-y&dnas--nx?mrak--nx?n&art--nx?nif--nx??reva--nx??z-smort--nx??v!.sg?ledatskork?reiks??wh-antouvn--nx?x&9-dlofts--nx.aoq-relv--nx?d-nmaherk--nx?f-dnalnks--nx?h-neltloh--nx?i-drgeppo--nx?j-gve&gnal--nx?lreb--nx??m-negnilr--nx?n-drojfvk--nx??y&7-ujdaehal--nx?8-antouvig--nx?b-&dlofrs--nx?goksmr--nx?kivryr--nx?retslj--nx??e-nejsom--nx?f-y&krajb--nx?re&dni--nx?tso--nx??stivk--nx??g-regark--nx?orf?ørf??z9-drojfstb--nx??b&25-akiivagael--nx?53ay7-olousech--nx?a&iy-gv--nx?le-tl&b--nx?s--nx??n0-ydr--nx??c&0-dnal-erdns--nx?z-netot-erts--nx??g&g-regnarav-rs--nx?o-nejssendnas--nx??ju-erdils-ertsy--nx?nj-dnalh-goksrua--nx?q&q-ladsmor-go-erm--nx.&ari-yreh--nx?ednas??s-neslahsladrjts--nx???ca&4s-atsaefrmmh--nx?8m-dnusynnrb--nx?il-tl--nx?le-slg--nx?n5-rdib--nx?op-drgl--nx?uw-ynnrb--nx??d&a&qx-tggrv--nx?reh!nnivk?sd&ork?ørk??uas??ts&e&bi?kkar?llyh?nnan??g&ort?ørt??k&alf?irderf??levev?mirg?obeg&ah?æh??r&ah?ejg????barm-jdddb--nx?ie!rah?s&etivk?ladman???lof&r&os?øs??ts&ev.ednas?o.relav?ø.relåv???n&a&l&-erd&n&os?øs??ron??adroh.so?dron.&a&g5-b--nx?ri-yreh--nx??ob?y&oreh?øreh??øb??e&m!lejh??pr&oj?øj??vi??gyb?n&aks?åks??o&h-goksrua?rf??r&o?ua?ø??tros?øh-goksrua??rts!e&devt?lab?mloh???s&ellil?naitsirk?rof???u&l!os??s!d&im?lejt??e&guah?l&a?å???kkoh?lavk?naitsirk?r&af?eg&e?ie???tef?y&onnorb?ønnørb?????r&a&blavs!.sg??g&eppo?la???o&j&f&a!dniv?k?vk??die?e&dnas?kkelf??llins?r&iel?ots??s&lab?t&ab?åb??yt??å!k??ævk??les??ts??åg&eppo?lå???ureksub.sen??e&ayb-yrettn--nx?d&ar?lom?r&of?øf??år??g&gyr?nats??i&meuv&ejsem&aan?åån??sekaal??rjea??j&d&ef?oks??les??k&er&aom?åom??hgna&ark?årk??iregnir?kot!s??s&ig?uaf???l&bmab?kyb?l&av?ehtats??oh??m&it?ojt?øjt??n&arg?g&os?øs??meh?reil?te?ummok?yrb??r&dils-erts&ev?y&o?ø???ua?vod??sa&ans?åns??t&robraa?spaav??urg??f&62ats-ugsrop--nx?a&10-ujvrekkhr--nx?7k-tajjrv-attm--nx??o!.sg?h??s!.sg??v!.sg???g&5aly-yr&n--nx?v--nx??a&llor?ve&gnal?lreb???n&av!snellu??org??oks&die?m&or?ør??ner&ol?øl??r&o?ø???r&eb!adnar?edyps?s&die?elf?gnok?n&ot?øt????obspras??uahatsla?åve&gnal?lreb???h&0alu-ysm--nx?7&4ay8-akiivagg--nx?5ay7-atkoulok--nx??a!.sg???i&e&hsr&agev?ågev??rf??k&h&avlaraeb?ávlaraeb??s??lm&a?å??mpouvtal&am?ám??pph&al?ál??rrounaddleid?ssaneve?ššáneve??j&0aoq-ysgv--nx?94bawh-akhojrk--nx??k&a&b&ord?ørd??jks?lleis??iv!aklejps?l&am?evs?u??mag?nel?ojg?r&a&l?n??epok?iel?y&or?ør???s&ah?kel?om??øjg??kabene?ojsarak?ram&deh.&aoq-relv--nx?rel&av?åv??so??e&let.&ag5-b--nx?ob?øb??ra???åjks??l&a!d&anrus?d&numurb?ron??e&gnard?nte?s&meh?sin??ttin??g&is?nyl??kro?l&em?l&ejfttah?of??u&ag-ertdim?s???n&am?era?gos?i&b?nroh?r??kos?nus?oj??o-&dron?r&os?øs???ppo?r&a!l?nram??e&gne?l?v??is?o&jts?ts??u&a-&dron?r&os?øs???h??å?æl?øjts??s&e&jg?nivk?ryf??kav?mor-go-er&om.&ednas?yoreh??øm.&ednas?yøreh???uag??t&las?rajh?suan??v&l&a?e-rots??u-go-eron??yt??ksedlig?res&a?å???bib&eklof?seklyf??es!dah??h!.sg??i&m?syrt??l&ejf?ov&etsua?gnit?ksa?sdie???n!.sg??o!.sg?boh?g?h??r!.sg??å!ksedlig??øboh??m&a&rah?vk??f!.sg??h!.sg??i&e&h&dnort?rtsua?ssej??rkrejb??ksa??ol?t!.sg??u&dom?esum?r&ab?drejg?evle?os?uh?æb?øs??ttals???n&a&g&av?okssman?åv??jlis?or?r&g?rev???e&d&do&sen?ton??lah?r&agy&o?ø??ojfsam???g&iets?n&a&l&as?lab??n&avk?ævk??t&arg?ddosen??v&al?essov???i&d&ol?øl??l&ar?ær???yl??reb??iks?k&srot?y&or?ør???l&a&d&gnos?n&er?ojm?øjm??om??tloh??ug?åtloh??mmard?ojs&om?sendnas??ppolg?s&lahsladr&ojts?øjts??o??t&o&l?t-erts&ev?o?ø???roh?øl??vly&kkys?nav??yam-naj!.sg??øjs&om?sendnas???g&orf?ujb??i&dnaort?vnarg??kob?ladendua?maherk&a?å??n&it?urgsrop??orf-&dron?r&os?øs???r&aieb?evats??sfev?uaks?yrts??o&6axi-ygvtsev--nx?c,d&ob?rav??ievs?kssouf?l&m&ob?øb??ous&adna?ech&ac?áč???so!.sg???msdeks?niekotuak?r&egark?olf?y&oso?øso???s&dav?mort???p&ed?ohsdaerpsym,p&akdron?elk???r&a&d&dj&ab?áb??iab??jtif?luag?mah?vsyt??e&gn&a&k&iel?ro??merb?n&at?mas??rav-r&os?øs??srop?talf?v&ats?el??y&oh?øh???ivsgnok??il?jkniets?k&a&nvej?rem?s&gnir?nellu???ie-er&den?v&o?ø???ram?sa?årem??la&jf?vh??m&b&ah?áh??mahellil??nnul?ts&l&oj?øj??ul??y&o?ø???imp&ah?áh??m!.sg??osir?t!.sg??ádiáb?ævsyt?øsir??s&adnil?en&dnas?e&dga?k&ri&b?k??som??ve??me&h?jg??nroh-go-ejve?s&a?ednil?k&o?ø??of?yt?å??tsev??gv?hf?igaval?o&r&or?ør??sman??so&fen&oh?øh??m?v??uh&lem?sreka.sen??å!dnil???t&a&baol?g&aov?grav??jjr&av-attam?áv-attám??l&a&b?s??ás??soum?ts?v&eib?our???e&dnaly&oh?øh??f?s&nyt?rokomsdeks?sen??vtpiks??in&aks?áks??loh&ar?år??n!.sg??o&m&a?å??psgolb,?s!.sg?efremmah?or?ør??terdi?á&baol?ggráv?lá&b?s??soum?veib???u&b!.sg?alk?e&dna?gnir?nner??les?ælk??dra&b?eb??g&nasrop?vi?ŋásrop??j&daehal&a?á??jedub?v&arekkhar?árekkhár???ksiouf?n&diaegadvoug?taed???v&irp?lesl&am?åm???y&b&essen?nart?sebel?tsev??o&d&ar?na!s??or??gavtsev?k&rajb?sa??lem?mrak?n&art?n&if?orb???r&a&mah?n?v??e&dni?t&so?ton??va??ul?yd??s&am?enner?gav?lrak?tivk??vrejks??ø&d&ar?na!s??ør??gåvtsev?k&rajb?sa??lem?mrak?n&art?n&if?ørb???r&e&dni?t&so?tøn??va??ul?yd?æ&n?v???s&enner?gåv?tivk?åm??vrejks???á&slág?tlá?vreiks??å&gåv?h?jddådåb?lf??ø&d&ob?rav??r&egark?olf??s&dav?mort????aki?i&sac?tal??u??o&b?f?g?hay?o?ttat??r!.&cer?erots?gro?m&o&c?n??rif?t??o&c,fni??pohs,stra?t&n?opsgolb,?www?ysrab,?e&a!.&a&ac?cgd?idem??bulc!orea??ci&ffartria?taborea??e&cn&a&l&lievrus-ria?ubma??netniam?rusni??erefnoc??gnahcxe?mordorea?ni&gne?lria?zagam??rawtfos??gni&d&art?ilg!arap?gnah???l&dnahdnuorg?ledom??noollab?retac?sael?t&lusnoc?uhcarap??vidyks??hcraeser?l&anruoj?euf?icnuoc?ortnoc!-ciffart-ria???n&gised?oi&nu?t&a&cifitrec?ercer?gi&tsevni-tnedicca?van??i&cossa!-regnessap??valivic??redef??cudorp?neverp-tnedicca????ograc?p&ihsnoipmahc?uorg!gnikrow???r&e&dart?enigne?korb?niart?trahc??o&htua?tacude???s&citsigol?e&civres?r??krow?serp!xe??tnega??t&farcr&ia?otor??hgil&f?orcim??liubemoh?n&atlusnoc?e&duts?m&esuma?n&iatretne?revog??piuqe????olip?ropria?si&lanruoj?tneics???w&erc?ohs??y&cnegreme?dobper?tefas????rref?z??p!.&a&aa?ca?pc??dem?ecartsnd.icb,gne?r&ab?uj??snduolc,t&acova?cca?hcer??wal?ysrab,???s!.&em?gro?hcs,moc?ten?ude?vog???t!.&116,ayo,gro?lim?moc?nayn,sulpnpv,t&cennockciuq.tcerid,en??ude?v&dr,og???o&hp?m?v?yk??tol?ua??v&iv?lov??xas?ykot??p&a&ehc?g?m?s??eej?g!.&gro?ibom?moc?ossa?ppa,ten?ude???i&r!.nalc,?v?z??j!.&a&3&5xq6f--nx?xqi0ostn--nx??5wtb6--nx?85uwuu--nx?9xtlk--nx?bihc!.&a&bihciakoy?don?ma&him?ye&ragan?tat???r&a&bom?gan?hihci??u&agedos?kas?ustak???s&os?ufomihs??t&amihcay?iran??w&a&g&im&anah?o??omak??kihci?zustum??ihsak??y&agamak?imonihci???e&akas?nagot??i&azni?esohc?h&asa?s&abanuf?ohc???ka&to?zok??musi?orihs?r&akihabihsokoy?o&dim?tak??ukujuk??usihs??nano&hc?yk??o&d&iakustoy?ustam??hsonhot?k&a&rihs?t??iba??nihsaran?sobimanim?tas&arihsimao?imot??uhc?yihcay??u&kujno?s&ayaru?t&imik?tuf???zarasik????g&as!.&a&gas?m&a&tamah?yik??ihsak??rat?t&a&gatik?hatik??ira!ihsin????e&kaira?nimimak??i&akneg?g&aruyk?o??h&c&amo?uo??siorihs??kaznak?modukuf?ra&gonihsoy?mi???nezih?u&k&at?ohuok??s&ot?tarak?????ihs!.&a&kok?m&a&hagan?yirom??ihsakat??rabiam?wagoton??e&miharot?nokih??houyr?i&azaihsin?esok?kustakat?moihsagih??na&mihcahimo?nok??o&hsia?mag?t&asoyot?ok?tir???us&ay?t&asuk?o??????k&aso!.&a&d&awihsik?eki??k&a&noyot?s&akaayahihc?oihsagih???oadat?uziak??m&ayas!akaso??odak??r&a&bustam?wihsak??ediijuf??t&akarih?i&k?us???wag&ayen?odoyihsagih???e&son?tawanojihs??honim?i&akas?h&cugirom?s&ayabadnot?i&a&kat?t??n??oyimusihsagih???k&a&rabi?sim??ustakat??muzi?r&ijat?otamuk???nan&ak?n&ah?es???o&ay?n&a&ganihcawak?simuzi?tak??eba?ikibah?oyot??t&anim?iad?omamihs??uhc??ust&oimuzi?tes????ou&kuf!.&a&d&amay?eos??g&no?ok?usak??hiku?k&awayim?uzii??ma&kan?y&asih?im???rawak?t&a&gon?ka&h?num?t???umo??wa&g&a&kan?nay?t??ias??ko!rih???y&ihsa?usak???e&m&ay?uruk??taruk?us??i&a&nohs?raihcat??goruk?h&cukuf?s&a&gih?hukuy??in???k&a&gako?muzim??iust?o?ustani??m&anim?otihsoynihs?u??r&ogo?ugasas??usu??ne&siek?zu&b?kihc???o&gukihc?h&ak?ot?ukihc??j&ono?ukihc??kayim?nihsukihc?to?uhc??u&fiazad?gnihs?stoyot????zihs!.&a&bmetog?d&amihs?eijuf?ihsoy?omihs??kouzihs?mihsim?ra&biah?honikam??tawi?wa&g&ekak?ukik??kijuf??yimonijuf??i&a&ra?sok??hcamirom?juf?kaz&eamo?ustam??ma&nnak?ta??nukonuzi?orukuf??nohenawak?o&nosus?ti??u&stamamah?z&a&mun?wak??i!ay?i&hs&agih?in??manim??mihs????????m&a&tias!.&a&d&ihsoy?ot?usah??k&a&dih?sa??o&arihs?s???m&a&tias?y&as?o&rom?tah??ustamihsagih???i&hsagurust?jawak??uri??ni?wa&g&e&ko?man??ikot?o??k&ara?i&hsoy?mak???ru?zorokot??y&a&g&amuk?ihsok?otah??kuf??imo??ziin??e&bakusak?ogawak?sogo?ttas?zokoy??i&baraw?h&cugawak?s&oyim?ubustam???iroy?k&ato?ihs?u&k?stawi???m&akoyr?i&hsoy?juf??uziimak???naznar?o&dakas?ihsay?jnoh?n&a&go?nim??imijuf?nah?oy??r&ihsayim?otagan??t&asim!ak??igus?omatik??zak??u&bihcihc!ihsagih??sonuok?ynah????y&ak&aw!.&a&d&ira?notimak??kadih?ma&h&arihs?im??y&a&kaw?tik??oduk???ru&ustakihcan?y??sauy?wa&g&a&dira?zok??orih??konik??yok?zok??e&banat?dawi??i&garustak?jiat?mani??naniak?o&bog?nimik?t&asim?omihs&ah?uk????ugnihs???o!.&a&jos?koasak?m&ay&ako?ust??ihsayah??r&abi?ukawaihsin??wi&aka?nam???e&gakay?kaw??i&gan?h&cu&kasa?otes??sahakat??k&asim?ihsaruk??miin??n&anemuk?ezib??o&hsotas?jnihs?n&amat?imagak??ohs?uhcibik?????ot!.&a&damay?got?koakat?may&etat?ot??nahoj?riat?waki&inakan?reman???eb&ayo?oruk??i&h&asa?ciimak?sahanuf??kuzanu?m&an&i?ot??ih???nezuyn?otnan?u&hcuf?stimukuf?z&imi?ou???????ihs&o&gak!.&a&m&ayuok?ihsogak??si?yonak??e&banawak?n&at&akan?imanim??uka??tomoonihsin??i&adnesamustas?k&azarukam?oih??m&ama?uzi??usuy??nesi?o&knik?os?tomustam??uzimurat???rih!.&a&ka&n?s??m&ayukuf?i&hsorihihsagih?j&ate?imakikaso????r&a&bohs?h&ekat?im???es??tiak?wiad??e&kato?ruk??i&h&ci&akustah?mono?nihs??s&inares?oyim???manimasa?uk??negokikesnij?o&gnoh?namuk??uhcuf????uk&ot!.&a&bihci?mi&hsu&kot?stamok??m??wagakan??egihsustam?i&gum?h&coganas?soyim??kijaw?m&anim?uzia??ukihsihs??nan&a?iak??o&nati?turan????uf!.&a&batuf?m&a&to?y&enak?irok???ihs&im?ukuf??os?uko??r&aboihsatik?uganat??ta&katik?mawak?rih??w&a&g&akus?emas?uy??k&a&mat?rihs?sa??ihsi??nah??ohs???e&gnabuzia?iman?ta&d?tii???i&adnab?enet?hs&agih?iimagak??k&a&wi?zimuzi??ubay??minuk?r&ook?ustamay???nihsiat?o&g&etomo?ihsin?nan?omihs??no!duruf?rih??rihsawani?ta&may?simuzia???u&rahim?stamakawuzia?zia&ihsin?nay???????nug!.&a&bawak?doyihc?k&anna?oi&hsoy?juf?mot???m&ayakat?ustagaihsagih??n&ihsatak?nak??r&ahonagan?nak?o?u&kati?mamat???t&amun?inomihs?o??w&akubihs?iem?ohs???i&hsa&beam?yabetat??kas&akat?esi??m&akanim?uzio??ogamust?rodim??o&jonakan?n&eu?oyikust??tnihs??u&komnan?stasuk?yrik?????ran!.&a&bihsak?d&akatotamay?u!o???guraki?m&ay&atik&imak?omihs??irokotamay??oki??ra&hihsak?n??wa&geson?knet???e&kayim?ozamay?sog?ustim??i&a&rukas?wak??garustak?h&ciomihs?sinawak??jo?ka&mnak?toruk??makawak?nos?r&net?otakat?ugeh???o&d&na?oyo??gnas?jnihs?nihsoy!ihsagih??tomarawat?yrok????t&ag&amay!.&a&dihsio?k&atarihs?ourust??may&a&kan?rum??enak?onimak??rukho?ta&ga&may?nuf??hakat?kas??wa&g&ekas?orumam??ki&hsin?m??z&anabo?enoy?ot???zuy??e&agas?bonamay?dii?nihsagih?o??i&a&gan?nohs??h&asa?sinawak??nugo??o&dnet?jnihs?ynan??ukohak???iin!.&a&ga?k&ium?oagan??munou!imanim??t&a&bihs?giin??ioy??w&a&gioti?kikes?zuy??irak??yijo??e&kustim?mabust??i&aniat?hcamakot?kaz&awihsak?omuzi??m&a&gat?karum??o???n&anust?esog??o&das?ihcot?jnas?k&ihay?oym??mak?naga?ries??u&ories?steoj?????i&ka!.&a&go?k&asok?oimak??t&ago!rihcah??ika!atik???w&aki?oyk???e&mojog?natim?suranihsagih?t&ado?okoy???i&hsoyirom?magatak?naokimak??nesiad?o&hakin?jnoh!iruy??nuzak?rihson?tasi&juf?m??yjnoh??u&kobmes?oppah????o!.&a&dakatognub?m&asah?ihsemih??su?t&ekat?i&h?o????e&onokok?ustimak??i&jih?k&asinuk?ias?usu??mukust??onoognub?u&fuy?juk?ppeb?suk??????wa&ga&k!.&a&mihsoan?rihotok?waga&kihsagih?ya???emaguram?i&j&nonak?ustnez??kunas?monihcu??o&hsonot?nnam?yotim??u&st&amakat?odat??zatu????nak!.&a&dustam?kus&okoy?tarih??maz?nibe?r&a&gihsaimanim?h&esi?imagas??wa&do?guy???u&im?kamak???tikamay?wa&k&ia?oyik?umas??sijuf??yimonin??e&nokah?saya??i&akan?esiak?gusta?hsuz?kasagihc?o?ukust??o&nadah?sio?tamay?????kihsi!.&a&danihcu?gak?kihs?mijaw?t&abust?ikawak??wazanak??i&gurust?hcionon?mon?ukah??nasukah?o&anan?ton!akan???u&kohak?stamok?z&imana?us?????niko!.&a&han?m&arat?ijemuk?uru??n&e&dak?zi??no??ra&hihsin?rih??wa&kihsi?niko??yehi?zonig??e&osaru?seay??i&hsagih?jomihs?k&a&gihsi?not??ihsakot??m&a&ginuk?kihsug?maz??igo?otekat??nuga!noy???n&a&moti?timoy?wonig??i&jikan?k???o&gan?jnan?tiad&atik?imanim???u&botom?kusug&akan!atik??imot??rab&anoy?eah???????c&204ugv--nx?462a0t7--nx?678z7vq5d--nx?94ptr5--nx?a??d&17sql1--nx?3thr--nx?5&20xbz--nx?40sj5--nx??7&87tlk--nx?ptlk--nx??861ti4--nx?a?e!tfarcdnah,??e&16thr--nx?5&1a4m2--nx?9ny7k--nx??im!.&a&bot?k&asustam?uzus??m&a&him?y&emak?im???ihs??nawuk?wi&em?k???e&bani?ogawak?si!imanim???i&arataw?gusim?h&asa?ciakkoy??k&a&mat?sosik?t??iat??raban??o&dat?hik?n&amuk?ihseru?o&du?mok????ust???lasrepus,mihe!.&a&m&a&h&ataway?iin??yustam??ij&awu?imak???taki!man???ebot?i&anoh?kasam?rabami??n&ania?egokamuk?oot??o&jias?kihcu?nustam?uhcukokihs?yi!es???u&kohik?zo????n!.&nriheg,teniesa.resu,?amihs!.&a&d&amah?ho?usam??kustay?m&a?ihsoni&hsin?ko???wakih??e&namihs?ustam??i&g&aka?usay??konikak?mikih??nannu?o&mu&kay?zi!ihsagih?uko???nawust?tasim??u&stog?yamat?????rotsnoihsaf,tawi!.&a&bahay?d&amay?on??koirom?t&a&honat?katnezukir??imus??w&as&ijuf?uzim??ihs???e&hon&i&hci?n??uk??tawi??i&a&duf?murak?wak??h&custo?si&amak?ukuzihs???j&oboj?uk??k&a&m&anah?uzuk??sagenak??esonihci??m&akatik?uzia&rih?wi????o&kayim?no&rih?t??tanufo??uhso????g&3zsiu--nx?71qstn--nx?l??h&03pv23--nx?13ynr--nx?22tsiu--nx?61qqle--nx??i&54urkm--nx?g&ayim!.&a&dukak?m&a&goihs?kihs??ihsustam!ihsagih??unawi??r&awago?iho??ta&bihs?rum??w&a&gano?kuruf??iat??y&imot?ukaw???e&mot?nimes??i&hsiorihs?ka&monihsi?s&awak?o???mak?r&ataw?o&muram?tan????o&az?jagat?t&asim?omamay???u&fir?k&irnasimanim?uhsakihcihs?????ihcot!.&a&g&a&h?kihsa??ust??kom?m&ay&o?usarak??unak??r&a&boihsusan?watho??iho?ukas??t&akihsin?iay??wa&konimak?zenakat??y&imonustu?oihs???e&iiju?kustomihs?nufawi??i&akihci?g&etom?ihcot?on???o&k&ihsam?kin??nas?sioruk?tab??u&bim?san?????h&c&ia!.&a&dnah?m&a!h&akat?im??yuni??ihs&ibot?ust???r&a&hat?tihs??ik?u&ihsagih?kawi???t&ihc?o&k?yot???wa&koyot?zani??yi&monihci?rak???e&inak?k&aoyot?usa??manokot?noyot??i&a&gusak?kot?sia??eot?h&asairawo?cugo?s&ahoyot?oyim???k&a&mok?zako??ihssi??motay?rogamag??n&an&ikeh?ok??ihssin??o&got?ihsin?jna?rihsnihs?suf?tes??u&bo?raho?s&oyik?takihs??yrihc?zah????ok!.&a&dusay?kadih?mayotom?r&ah&im?usuy??umakan??sot!ihsin??wa&g&atik?odoyin??k&as?o????i&esieg?hco!k??jamu?k&a!sus??usto??ma&gak?k??rahan??o&mukus?n&i?ust!ihsagih???torum?yot!o???u&koknan?zimihsasot????ugamay!.&a&m&ayukot?ihso??toyot??e&bu?subat??i&gah?kesonomihs?nukawi?rakih??nanuhs?otagan?u&ba?foh?otim?stamaduk?uy?????sanamay!.&a&dihsoyijuf?mayabat?r&ahoneu?ustakihsin??w&a&k&ayah?ijuf??suran??ohs???egusok?i&ak?h&cimakan?s&anamay?od???k&asarin?u&feuf?sto????o&k&akanamay?ihcugawakijuf??nihso?t&asimawakihci?ukoh??uhc??spla-imanim?u&b&nan?onim??fok?hsok?rust?????ka&rabi!.&a&bukust?gok?kan!ihcatih??m&a&sak?timo?wi??ihsak?ustomihs??ni?r&a&hihcu?way??u&agimusak?ihcust???t&ag&amay?eman??oihcatih??w&ag&arukas?o??os??yi&moihcatih?rom???e&bomot?dirot?not?tadomihs??i&a&k&as?ot??rao??esukihc?gahakat?h&asa?catih??k&a&rabi?saguyr??ihsani?uy??ma?rukustamat??o&dnab?giad?him?kati?rihsijuf?soj?t&asorihs?im??yihcay??u&fius?kihsu?simak????sagan!.&a&m&abo?ihsust??natawak?r&abamihs?u&mo?ustam???wijihc?yahasi??i&akias?hies?k&asagan?i??masah??neznu?o&besas?darih?t&eso?og!imaknihs????ust&igot?onihcuk?uf????zayim!.&a&biihs?guyh?k&oebon?ustorom??mihsuk?r&emihsin?uatik??ta&katik?mim??wag&atik?odak??ya??e&banakat?sakog??i&hsayabok?kaza&kat?yim??m&animawak?ot&inuk?nihs????nanihcin?o&j&ik?onokayim??n&ibe?ust??tias??urahakat????ro&moa!.&a&dawot?turust?wasim??e&hon&ihc&ah?ihs??nas?og?ukor??sario??i&anarih?ganayati?hsioruk?jehon?kasorih?makihsah?nawo?r&amodakan?omoa???o&gnihs?kkat??u&ragust?stum????ttot!.&a&r&ahawak?uotok??sa&kaw?sim???egok?irottot?nanihcin?o&ganoy?nih?tanimiakas??u&bnan?z&ay?ihc??????ukuf!.&a&deki?gurust?ma&bo?h&akat?im??yustak??sakaw??eabas?i&akas?ho?jiehie?ukuf??nezihce!imanim??ono????k&26rtl8--nx?4&3qtr5--nx?ytjd--nx??522tin--nx?797ti4--nx??l33ussp--nx?m&11tqqq--nx?41s3c--nx??n&30sql1--nx?65zqhe--nx?n7p7qrt0--nx??o&131rot--nx?7qrbk--nx?c?diakkoh!.&a&deki?gakihset?hcebihs?k&adih?u&fib?narihs???m&ayiruk?hot?ihs&orihatik?ukuf??oras?usta??r&ib&a!ka??o?uruf??ozo?u&gakihsagih?oyot???sakim?ta&gikust?mun??w&a&ga&k&an?uf??nus!imak???k&aru?i&h&asa?sagih??kat?mak??omihs?um??zimawi??ine?oyk??yot??e&a&mustam?nan??b&a&kihs?yak??o&noroh?to???ian?k&ihsam?ufoto??nakami?ppoko!ihsin??sotihc?tad!okah??uonikat??i&a&bib?mokamot?n&a&k&kaw?oroh??wi??eomak?ihsatu?okik?usta&moruk?sakan????eib?h&c&ioy?u&bmek?irihs???s&ase?ekka?oknar?uesom???jufirihsir?k&amamihs?i&at?n???m&atik?otoyot??oa&kihs?rihs??r&a&hs?kihsi?mot??ihs&aba?ir??otarib???n&a&hctuk?rorum?se?tokahs??uber??o&kayot?m&ire?ukay??naruf!ima&k?nim???orih?r&ih&ibo?suk??o&bah?h&i&b?hsimak??sa??pnan?yan??umen??t&asoyik?eko?ukoh???u&bassa?kotnihs?m&assaw?uo??pp&akiin?en&ioto?nuk??ip??rato?s&akat?t&eb&e?i&a?hs!a??robon??m&e?o&m?takan???no&h?tamah??o&mik?s?t??u&kir?ppihc?st???onihsnihs?ufuras??uaru??yru!koh??zimihs!ok?????g!oyh!.&a&bmat?dnas?gusak?k&at?o&oyot?y??uzarakat??m&ayasas?irah??wa&g&ani?okak??k&i&hci?mak??oy???yi&hsa?monihsin???i&asak?hs&aka?i&at?nawak???j&awa!imanim??emih??k&a&goa?s&agama?ukuf??wihsin??i&hsog?m???mati?oia?rogimak??n&annas?esnonihs??o&gasa!kat??ka?n&ikat?o?ustat??rihsay?sihs?tomus?yas??u&bay?gnihs?????nagan!.&a&bukah?d&a&w?yim??e&ki?u??ii??k&a&s&ay?uki??zus??ihsoo?ousay??m&ay&akat?ii??i&hsukufosik?jii??ukihc??n&i!hsetat??uzii??r&ah?ugot??saim?t&agamay?oyim??w&a&g&a&kan?n??o??kustam?ziurak??onim!imanim??u&koo?s!omihs????ya&ko?rih???e&akas?nagamok?subo??i&gakat?h&asa?c&a!mo!nanihs???uonamay??sukagot??k&a&kas?mimanim?to??ia&atik?imanim??oa?uzihcom??m&akawak?ijuf?o!t???r&ato?ijoihs?omakat???n&ana?esnoawazon??o&hukas?n&a&gan?kan??i&hc?muza??ustat??romok?si&gan?k??tomustam??u&k&as?ohukihc??stamega????to&mamuk!.&a&gamay?rahihsin?sukama!imak??tamanim??enufim?i&hcukik?k&ihsam?u??nugo!imanim??romakat??o&ara?rihsustay?sa?t&amay?om&amuk?us??u!koyg???yohc??u&sagan?zo????yk!.&a&bmatoyk?k&ies?oemak?uzaw??mayi&h&cukuf?sagih??muk??nihsamay?rawatiju?t&away?ik???e&ba&nat!oyk??ya??di?ni??i&ju?kazamayo?manim??natnan?o&gnatoyk?kum?mak?rihsamayimanim?y&gakan?ka&koagan?s??oj???u&ruziam?z&ayim?ik??????wtc1--nx?ykot!.&a&d&i&hcam?mus??oyihc??k&atim?ihsustak??m&a&t!uko??yarumihsa&gih?sum???i&hs&agoa?ika?o!t??uzuok??ren???r&a&honih?wasago??iadok?umah??ssuf?t&ik?o??wa&g&anihs?ode??k&ara?ihcat???y&agates?ubihs???e&amok?donih?m&o?urukihsagih??soyik??i&enagok?gani?h&ca&da?tinuk??sabati??j&nubukok?oihcah??manigus??o&huzim?jihcah?n&akan?ih!sasum??urika??rugem?t&a&mayihsagih?nim??iat?ok??uhc?yknub??u&fohc?hcuf?kujnihs?????pohs&eht,iiawak,yub,?r&2xro6--nx?g?o??s&9nvfe--nx?xvp4--nx??t&netnocresu,opsgolb,?u&4rvp8--nx?fig!.&a&d&eki?ih??kimot?m&ayakat?ihsah??ne?raha&gi&kes?makak??sak??taga&may?tik??wa&g&ibi?ustakan??karihs!ihsagih????e&katim?uawak??i&gohakas?hc&apna?uonaw??k&ago?es?ot??m&anuzim?ijat??nak?urat??nanig?o&dog?jug?makonim?nim?roy?sihcih??u&fig?s&otom?t&amasak?oay???????x5ytlk--nx?yu6d27srjd--nx?z72thr--nx?井福?京東?分大?取鳥?口山?城&宮?茨??媛愛?山&富?岡?歌和??岡&福?静??島&児鹿?広?徳?福??崎&宮?長??川&奈神?石?香??庫兵?形山?手岩?木栃?本熊?根島?梨山?森青?潟新?玉埼?田秋?知&愛?高??縄沖?良奈?葉千?賀&佐?滋??道海北?都京?重三?野長?阜岐?阪大?馬群???k!.&art?gro?moc?per?ude?vog???l&eh?l??m!.uj,ac?j??nd?o&g?h&pih?s!.&esab,xilpoh,ysrab,???lnud?oc?t!.&lldtn,snd-won,???pa!.&0mroftalp,arusah,bew:erif,,e&gatskrelc,niln&igol,okoob,?tupmocegde,virdhsalfno,?krelc,lecrev,n&aecolatigidno,ur:.a,,?poon,remarf,t&ibelet,xenw,?yfilten,??ra&a?hs??u&ekam?llag?org!.esruocsid,cts?kouk?nayalo???vsr?xece4ibgm--nx??q&a!3a9y--nx??g?i!.&gro?lim?moc?ten?ude?vog???m?se??r&a!.&a&cisum?sanes??bog?gro?l&autum?im??moc!.topsgolb,?pooc?rut?t&e&b?n??ni??ude?vog??4d5a4prebgm--nx?b?c?eydoog?los?t&at?s!uen???ugaj??b!.&21g?a&b&a&coros?iuc??itiruc??cnogoas?dicerapa?gniram?i&naiog?ramatnas??n&erom?irdnol??op?p&acam?irolf?ma&j?s???rief?tsivaob??b!aj?ib?mi?sb??c&ba?e&r?t??js?sp?t!e???d&em?mb?n&f?i??rt??e&dnarganipmac?ficer?ht?llivnioj?rdnaotnas??f&dj?ed?gg?n&e?i???g&e&l!.&a&b,m,p,?bp,c&a,s,?e&c,p,s,?fd,gm,ip,jr,la,ma,nr,o&g,r,t,?p&a,s,?r&p,r,?s&e,m,r,?tm,??s??l&s?z??n&c?e?o??ol!b?f?v??pp?ro??hvp?i&du?kiw?nana?oretin?r&c?eurab??sp?te?xat??l&at&an?rof??el?im?sq??m&a?da?e&gatnoc?leb??f?ic?oc!.&duolclautriv.elacs.sresu,topsgolb,???nce?o&ariebir?c&e?narboir?saso??d&o?ranreboas??e&g?t??i&b?dar?ecam?r??rp?t&a?erpoir???p&er?m!e?t??ooc?pa?se??qra?r&af?ga?o&davlas?j??tn?ut??s&a&ixac?mlap?nipmac??ed?u&anam?j?m???t&am?e&d?n?v??nc?o&f?n??ra?sf??u&caug9?de?ja?rg??v&da?ed?og!.&a&b?m?p??bp?c&a?s??e&c?p?s??fd?gm?ip?jr?la?ma?nr?o&g?r?t??p&a?s??r&p?r??s&e?m?r??tm???rs?t??xiv?z&hb?ls?o&c?f?????c!.&as?ca?de?if?o&c?g??ro???e&bew?ccos?dnik?e&b?n&igne?oip??rac??gni&arg?rheob??h&cor?sok?t&aew?orb???itnorf?k&col?o&p?rb???l&aed?ffeahcs??mal?nes?pinuj?t&a&eht?rebsnegömrev??law?nec?s&acnal?nom?ubkcolb??upmoc??v&o&csid?rdnal??resbo??wulksretlow?ywal?zifp??f!.&aterg?bew-no,drp?e&c&itsuj-reissiuh?narf-ne-setsitned-sneigrurihc,?lipuog,rianiretev??hny,i&cc?rgabmahc??m&o&c?n??t??n&eicamrahp?icedem??ossa?pohsdaerpsym,s&e&lbatpmoc-strepxe?riaton?tsitned-sneigrurihc?uova??o&-x&bf,obeerf,?x&bf,obeerf,???t&acova?o&or-ne,psgolb,?r&epxe-ertemoeg?op!orea????vuog??avc7ylqbgm--nx?s??g!.&gro?moc?t&en?opsgolb,?ude?vog???h!.&e&erf,man??mo&c?rf??topsgolb,zi??ur??i!.&a&61f4a3abgm--nx?rf4a3abgm--nx??ca?di?gro?hcs?oc?ten?vog?نار&يا?یا???a&h?per??ew?lf??k!.&c&a?s??e&n?p?r??gk?iggnoeyg?kub&gn&oeyg?uhc??noej??l&im?uoes??man&gn&oeyg?uhc??noej??n&as&lu?ub??o&e&hcni?jead??wgnag???o&c?g??ro?s&e?h?m??topsgolb,u&gead?j&ej?gnawg????cilf??l!.&gro?moc?ten?ude?vog???m!.&topsgolb,vog???n!.&gro?moc?ofni?ten?ude?vog?zib???o&htua?odtnorf?t&c&a?od??laer???p!.&alsi?ca?eman?forp?gro?moc?o&fni?rp??t&en?se??ude?vog?zib???s?t!.&21k?bew?cn!.vog??eman?gro?kst?l&e&b?t??im?op??moc!.topsgolb,?neg?ofni?pek?rd?sbb?ten?ude?v&a?og?t??zib??f?m??ubad?vd??s&8sqif--nx?9zqif--nx?a!.vog?birappnb?gev?lliv?mtsirhc?s??b!.&ew,gro?moc?ten?ude?vog??c?oj?s?u??c&i&hparg?p?t&sigolyrrek?ylana???od??d&a?d?ik?l?n&iwriaf?omaid??oogemoh?rac??e!.&bog?gro?mo&c!.topsgolb,?n??pohsdaerpsym,ude??civres!.enilnigol,?d&d2bgm--nx?oc??h&ctaw?guh??i&lppus?rtsudni?treporp!yrrek???jaiv?l&aw?cycrotom?etoh?gnis?pats??m&ag?oh?reh??nut?ohs?picer?r&it?ut&cip!.7331,?nev???s!i&rpretne?urc??ruoc??taicossa?vig??g!nidloh??h5c822qif--nx?i!.&ekacpuc,gro?moc?t&en?ni?opsgolb,?ude?vog??a09--nx?nnet?rap?targ??k&c&or!.&ecapsbew,snddym,ytic-amil,??us??hxda08--nx?row??l!.&c&a?s??ed,gro?o&c?fni??ten?ude?vog?zib??a&ed?tner??e&ssurb?toh!yrrek???lahsram?m?oot??m!.&bal,etisinim,gro?moc?ten?ude?vog??b?etsys!.tniopthgink,?ialc??n&a&f?gorf?ol??egassap?i&a&grab?mod??giro??o&it&acav?cudorp?ulos??puoc???o&dnoc?geuj?leuv?ppaz?t&ohp?ua???p!.&ces?gro?moc?olp?ten?ude?vog??i&hsralohcs?lihp?t??u??r!.&au,ca?gro?ni?oc?topsgolb,ude?vog?xo,yldnerb.pohs,?a&c?p?tiug??c?e&dliub!.etisduolc,?erac?gor?levart?mraf?n&niw?trap??wolf??ot&cartnoc?omatat??pj?uot??s!.&em?gro?hcs?moc?ten?ude?vog?zib??alg?e&n&isub!.oc,?tif??rp!xe!nacirema???xnal??iws??t&a&e&b?ytic??ob??ek&cit?ram??fig?h&cay?gilf??n&atnuocca?e&mt&rapa?sevni??ve!.&nibook,oc,????rap??u!.&a&c!.&21k?bil?cc???g!.&21k?bil?cc???i!.&21k?bil?cc???l!.&21k?bil?cc???m!.&21k!.&hcorap?rthc?tvp???bil?cc???p!.&21k?bil?cc???si?v!.&21k?bil?cc???w!.&21k?bil?cc????c&d!.&21k?bil?cc???n!.&21k?bil?cc???s!.&21k?bil?cc????d&e&f?lacsne.xhp,?i!.&21k?bil?cc???m!.&21k?bil?cc???n!.&bil?cc???s!.&bil?cc???u&olcrim,rd,??e&d!.&21k?bil,cc???las-4-&dnal,ffuts,?m!.&21k?bil?cc???n!.&21k?bil?cc????h&n!.&21k?bil?cc???o!.&21k?bil?cc????i&h!.&bil?cc???m!.&21k?bil?c&c?et??goc?n&eg?otae??robra-nna?sum?tsd?wanethsaw???nd?r!.&bil?cc???v!.&21k?bil?cc???w!.&21k?bil?cc????jn!.&21k?bil?cc???k&a!.&21k?bil?cc???o!.&21k?bil?cc????l&a!.&21k?bil?cc???f!.&21k?bil?cc???i!.&21k?bil?cc????mn!.&21k?bil?cc???n&afflog,i!.&21k?bil?cc???m!.&21k?bil?cc???sn?t!.&21k?bil?cc????o&c!.&21k?bil?cc???m!.&21k?bil?cc???ttniop,?p&ion,rettalp,?r&a!.&21k?bil?cc???o!.&21k?bil?cc???p!.&21k?bil?cc????s&a!.&21k?bil?cc???dik?k!.&21k?bil?cc???m!.&21k?bil?cc???nd&deerf,uolc,??t&c!.&21k?bil?cc???m!.&21k?bil?cc???u!.&21k?bil?cc???v!.&21k?bil?cc????ug!.&21k?bil?cc???v&n!.&21k?bil?cc???w!.cc???x&ohparg,t!.&21k?bil?cc????y&b-si,k!.&21k?bil?cc???n!.&21k?bil?cc???w!.&21k?bil?cc????za!.&21k?bil?cc????ah!uab??bria?col?e!.ytrap.resu,?ineserf?lp?xe&l?n???vt?w!.&66duolc,gro?moc?s&ndnyd,tepym,?ten?ude?vog??a?e&iver?n!.elbaeciton,??odniw??y&alcrab?cam?ot???t&0srzc--nx?a!.&amil4,ca!.hts??gni&liamerutuf,tsoherutuf,?o&c!.topsgolb,?fni,?p&h21,ohsdaerpsym,?r&euefknuf.neiw,o??v&g?irp,?xi2,ytic-amil,zib,?c?e!s??hc?if?l!asite??mami?rcomed??b!.&gro?moc?ten?ude?vog??b?gl??c&atnoc?e&les?rid!txen????dimhcs?e!.&eman?gro?moc?ofni?ten?ude?vog?zib??b?em?grat?id?k&circ?ram??n!.&0rab,1rab,2rab,5inu,6vnyd,7&7ndc.r,erauqs,?a&l&-morf,moob,?minifed,remacytirucesym,tadsyawla,z,?b&boi,g,lyltsaf:.pam,,?c&inagro-gnitae,paidemym,?d&ecalpb,irgevissam.saap.&1-&gs,nol,rf,yn,?2-&nol,yn,??nab-eht-ni,uolc&meaeboda,nievas.c&di-etsedron,itsalej,?xednay:.e&garots,tisbew,?,??e&c&narusnihtlaehezitavirp,rofelacs.j,?gdirbtib,ht-no-eciffo,l&acs&liat.ateb,noom,?ibom-eruza,?m&ecnuob,ohtanyd,tcerider,?n&ilno-evreser,ozdop,?rehurht,s:abapus,,tis-repparcs,zamkcar,?f&aeletis,crs.&cos,resu,?ehc-a-si,?g&ni&reesnes,sirkcilc,tsohnnylf,?olb&evres,tsaf,??k&catsvano,eeg-a&-si,si,?u,?l&acolottad,iamwt,s&d-ni,s-77ndc,??m&ac&asac,ih,?urofniem,?n&a&f&agp,lhn,?i&bed,llerk,??dcduabkcalb,i,pv-ni,?o&c-morf,duppa,jodsnd,rp-ytinummoc,ttadym,?p&i&-&etsef,on,?emoh,fles,nwo,?j,mac-dnab-ta,o&-oidar-mah,h&bew,sdaerpsym,??pa&duolc,egde,?tfe&moh,vres,?usnd,?r&e&tsulcyduolc,vres-xnk,?vdslennahc:.u,,?s&a&ila&nyd,snd,?nymsd,?bbevres,dylimaf,e&gde-ndc,suohsyub,t&isbeweruza,ys,??k&catstsaf,ekokohcs,?n&d&-won,d,golb,npv,?oitcnufduolc,?ppacitatseruza:.&2suts&ae,ew,?aisatsae,eporuetsew,sulartnec,?,s&a-skcik,ecca&-citats,duolc,??t,?t&adies,ce&ffeym,jorprot:.segap,,lespohs,?e&nretnifodne,smem,?farcenimevres,i-&ekorb,s&eod,lles,teg,??n&essidym,orfduolc,?r0p3l3t,s&ixetnod,oh&-spv:.citsalej.&cir,lta,sjn,?,gnik,???u&h,nyd,r:eakust.citsalej,,?ved-naissalta.dorp.ndc,x&inuemoh,spym,tsale.&1ots-slj,2ots-slj,3ots-slj,?unilemoh,?y&awetag-llawerif,ffijduolc:.&ed-1arf,su-1tsew,?,ltsaf.&dorp.&a,labolg,?lss.&a,b,labolg,?pam,slteerf,?n&-morf,ofipi,?srab,?z&a-morf,tirfym,???p?tcip?v??f&ig?o&l?sorcim???g!.&bog?dni?ed,g&olb,ro??lim?moc?ot,ten?ude???h!.&dem?gro?l&er?op??m&oc?rif??o&fni?rp?s&rep?sa???po&hs?oc??t&en?luda?ra??ude?vuog???i!.&a&2n-loritds--nx?7e-etsoaellav--nx?8&c-aneseclrof--nx?i-lrofanesec--nx??at?b?c!cul??dv?i&blo&-oipmet?oipmet??cserb?drabmol?g&gof?urep??l&gup?i&cis?me&-oigger?oigger???uig&-&aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf???aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf????n&a&brev?cul?pmac?tac??idras?obrac&-saiselgi?saiselgi??resi??otsip?r&b&alac!-oigger?oigger??mu??dna&-&attelrab-inart?inart-attelrab??attelrabinart?inartattelrab?ssela??epmi?ugil??tnelav&-obiv?obiv??vap?z&e&nev?ps&-al?al???irog???l&iuqa!l??leib??m&or?rap??n!acsot?e&dom?is?sec&-&ilrof?ìlrof??ilrof?ìlrof???g&amor&-ailime?ailime??edras?olob??i&ssem?tal??ne!var??o&cna?merc?rev?vas???oneg?p?r!a&csep?rr&ac&-assam?assam??ef??von??etam?tsailgo!-lled?lled???s!ip?sam&-ararrac?ararrac??u&caris?gar???t!a&cilisab?recam??resac?soa!-&d&-&ellav?lav??ellav?lav??ellav??d&-&ellav?lav??ellav?lav??ellav??te&lrab&-&airdna-inart?inart-airdna??airdnainart?inartairdna??ssinatlac???udap?v!o&dap?neg?tnam???zn&airb&-a&lled-e-aznom?znom??a&lledeaznom?znom??eaznom??e&c&aip?iv??soc?top??om???b&-&23,46,61,?3c-lorit-ds-onitnert--nx?be-etsoa&-ellav--nx?dellav--nx??c!f-anesec-lrof--nx?m-lrof-anesec--nx??he-etsoa-d-ellav--nx?m!u??o2-loritds-nezob--nx?sn-loritds&-nasl&ab--nx?ub--nx??nitnert--nx??v!6-lorit-dsnitnert--nx?7-loritds&-nitnert--nx?onitnert--nx???z&r-lorit-ds&-nitnert--nx?onitnert--nx??s-loritds-onitnert--nx???c&f?is?l?m?p?r?v??d&p?u!olcnys,??e&c!cel?inev?nerolf??f?g!ida&-&a&-onitnert?onitnert??otla!-onitnert?onitnert???a&-onitnert?onitnert??otla!-on&azlob?itnert??onitnert????hcram?l?m!or??n&idu?o&n&edrop?isorf??torc???p?r?s&erav?ilom??t!nomeip?s&eirt?oa!-&d-e&ellav?éllav??e&ellav?éllav???de&ellav?éllav??e&ellav?éllav?????v?znerif??g&a?b?f?il?o?p?r?up?vf??hc?i&b?c?dol?f?l!lecrev?opan?rof&-anesec?anesec???m?n&a&part?rt&-attelrab-airdna?attelrabairdna???imir?ret??p?r!a&b?ilgac?ssas???s!idnirb??t&ei&hc?r??sa??v??l&a!c??b?c?o&m?rit&-&d&eus&-&nitnert?onitnert??nitnert?onitnert??us&-&nitnert?onitnert??nitnert?onitnert??üs&-&nitnert?onitnert??nitnert?onitnert???s&-onitnert?onitnert???d&eus!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??us&-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??üs!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert???s&-onitnert?onitnert?????m&ac?f?i!t.nepo.citsalej.duolc,?ol?r??n&a!lim?sl&ab?ub???b?c?e!en.cj,v?zob??irut?m!p??p?r?t??o&a!v??b!retiv??c!cel??enuc?g!ivor??i&dem&-onadipmac?onadipmac??pmet&-aiblo?aiblo??rdnos?zal??l?m!a&greb?ret??oc?re&f?lap???n!a&dipmac&-oidem?oidem??lim?tsiro?zlob??ecip&-ilocsa?ilocsa??i&bru&-orasep?orasep??lleva?rot?tnert??r&elas?ovil??ulleb??p?r!a&sep&-onibru?onibru??znatac??oun??s!ivert?sabopmac??t!arp?e&nev?ssorg??n&arat?e&girga?rt?veneb????zz&era?urba???p&a?ohsdaerpsym,s?t??qa?r&a!m?s??b!a??c?f?g?k?me?o?p?s?t?v??s&a&b?iselgi&-ainobrac?ainobrac???b?c?elpan?i?m?ot?s?t?v??t&a?b?c?l?m?nomdeip?o!psgolb,?p?v??u&de?l?n?p??v&a?og?p?s?t?v??y&drabmol?ellav&-atsoa?atsoa??licis?nacsut??z&al?b?c?p??ìlrof&-anesec?anesec???derc?er?f?m?utni??je3a3abgm--nx?kh?l!.&topsgolb,vog??uda??m!.&gro?moc!.topsgolb,?ten?ude???n&a&morockivdnas?ruatser?tnuocca??e&g?m&eganam!.retuor,?piuqe??r??i!.ue?m?opdlog??opud?uocsid??o&b?cs!.&ude,vog:.ecivres,,??d?g?h?j?oferab?p&edemoh?s???p!.&emon?gro?lbup?moc?t&en?ni?opsgolb,?ude?vog???r&a!m&law?s???epxe?op&er?pus!.ysrab,?s???s!.&adaxiabme?e&motoas?picnirp?rots??gro?lim?moc?o&c?dalusnoc?hon,?ten?ude??a&cmoc?f??e&b?r?uq??i!rolf?tned??o&h!.&duolc&p,rim,?e&lej,tiseerf,?flah,lrupmet,s&pvtsaf,seccaduolc,?tsafym,vedumpw,??p!sua???urt??t!.&eman?gro?ibom?levart?m&oc?uesum??o&c?fni?r&ea?p???pooc?sboj?t&en?ni??ude?vog?zib??ayh?n?o!bba?irram???uognah?xen?y!.gro,?ztej??u&2&5te9--nx?yssp--nx??a!.&a&s?w??civ?d&i?lq??fnoc?gro?moc!.&pohsdaerpsym,stelduolc.lem,topsgolb,??nsa?ofni?sat?t&ca?en?n??ude!.&a&s?w??ci&lohtac?v??dlq?sat?t&ca?n??wsn!.sloohcs????vog!.&a&s?w??civ?dlq?sat???wsn?zo??ti??c!.&fni?gro?moc?ten?ude?vog??i??d&e!.tir.segap-tig,?iab??e!.&dcym,enozgniebllew,noitatsksid,odagod.citsalej,snd&ps,uolc,?ysrab,??g!.&bew?gro?m&aug?oc??ofni?ten?ude?vog???h!.&0002?a&citore?idem?kitore??edszot?gro?ilus?letoh?m&alker?lif?t?urof??naltagni?o&c?ediv?fni?levynok?nisac??pohs?rarga?s&a&kal?zatu??emag?wen??t&lob?opsgolb,rops??virp?xe&s?zs??ytic?zsagoj??os?sut??l!.topsgolb,?m!.&ca?gro?moc?oc?ro?ten?vog???n!.&duolcesirpretne,eni&esrem,m,?tenkcahs,?em!.ysrab,??o&ggnaw?y!c???r!.&3kl,a&i&kymlak,rikhsab,vodrom,?yegyda,?bps,ca,duolcrim,e&niram,rpcm,?g&bc,nitsohurger.citsalej,ro,?ianatsuk,k&ihclan,s&m,rogitayp,??li&amdlc.bh,m,?moc,natsegad,onijym,pp,ri&b,d&cm:.spv,,orue,?midalv,?s&ar,itym,?t&en,ni,opsgolb,set,?u&4an,de,?vo&g,n,?ynzorg,zakvakidalv,?myc?p?ug??s!.&a&d&golov,nagarak,?gulak,i&groeg,kymlak,lerak,nemra,rikhsab,ssakahk,vodrom,zahkba,?lut,rahkub,vut,yegyda,znep,?bps,da&baghsa,rgonilest,?gunel,i&anatsuk,hcos,ovan,ttailgot,?k&alhsygnam,ihclan,s&legnahkra,m,n&a&mrum,yrb,?i&buytka,nbo,??tiort,vorkop,??l&ocarak,ybmaj,?na&gruk,jiabreza,ts&egad,hkazak-&htron,tsae,???ovonavi,r&adonsark,imidalv,?t&enxe,nek&hsat,mihc,??vo&hsalab,n,?ynzorg,z&akvakidalv,emret,??t&amok?i&juf?masih????v!.&em,g&olb,ro??moc?nc,ten?ude?ved,??ykuyr??v&b?c!.&emon?gro?moc?t&ni?opsgolb,?ude???ed!.&enilnigol,gnigats-oned,hcetaidem,lecrev,o&ned,tpyrctfihs,?ppa-rettalp,s&egap,rekrow,?vr&esi,uc,?weiverpbuhtig,ylf,??ih?l!.&di?fnoc?gro?lim?moc?nsa?ten?ude?vog???m!.&eman?gro?lim?m&oc?uesum??o&fni?r&ea?p???pooc?t&en?ni??ude?vog?zib???o&g?m??rt?s!.&bog?der?gro?moc?ude???t!.&bew-eht-no,naht-&esrow,retteb,?sndnyd,?d?gh?i?won??uqhv--nx??w&a!.moc?hs?l??b!.&gro?oc???c!.&gro?moc?ten?ude??cp??e&iver!.oby,?n?s??g?k!.&bme?dni?gro?moc?ten?ude?vog???m!.&ca?gro?m&oc?uesum??oc?pooc?t&en?ni??ude?vog?zib??b??o&csom?h!s??n?w??p!.&344x,de?en?o&c?g??ro?snduolc,ualeb???r!.&ca?gro?lim?oc?pooc?ten?vog??n??t!.&a46oa0fz--nx?b&82wrzc--nx?ulc??emag?gro?l&im?ru,?moc!.reliamym,?t&en?opsgolb,?ude?v&di?og?ta0cu--nx??zibe?業商?織組?路網???z!.&ca?gro?lim?oc?vog????x&a!.&cm,eb,gg,s&e,u,?tac,ue,yx,?t??c!.&hta,ofni,vog???e&d&ef?nay??ma!nab??rof?s??ilften?jt?m!.&bog?gro?moc?t&en?opsgolb,?ude??g?ma2ibgy--nx??o&b!x??f?rex??rbgn--nx?s!.vog??x&am&jt?kt??x???y&4punu--nx?7rr03--nx?a&d!i&loh?rfkcalb??ot!.emyfilauqerp,??g?lp?p!ila??rot?ssin?wdaorb??b!.&duolcym,fo?hcetaidem,lim?moc!.topsgolb,?vog??ab?gur??c!.&ca?dtl?gro?lim?m&oc!.&ecrofelacs.j,topsgolb,??t??orp?s&egolke?serp??ten?vog?zib??amrahp?nega??d&dadog?uts??e&kcoh?ltneb?n&dys?om?rotta??snikcm??g!.&eb,gro?moc?oc?ten?ude?vog??olonhcet!.oc,?rene??hpargotohp?id?k!.&gro?moc?ten?ude??s??l!.&clp?d&em?i??gro?hcs?moc?ten?ude?vog??f?imaf!nacirema??l&a?il??ppus??m!.&eman?gro?lim?moc?t&en?opsgolb,?ude?vog?zib??edaca!.laiciffo,?ra??n&a&ffit?pmoc??os??o&j?s??p!.&gro?lim?moc?pooc?ten?ude?vog???r&e&corg?grus?llag?viled??lewej?otcerid?tnuoc?uxul??s!.&gro?lim?moc?ten?ude?vog??pil??t&efas?i&c?ledif?n&ifx?ummoc!.&bdnevar,gon,murofym,???r&ahc?uces??srevinu??laer?r&ap!.oby,?eporp??uaeb??u!.&bug?gro?lim?moc!.topsgolb,?ten?ude??b!tseb???van!dlo??xes??z&a!.&eman?gro?lim?moc?o&fni?rp??pp?t&en?ni??ude?vog?zib???b!.&az,gro?jsg,moc?ten?ude?vog???c!.&4e,inum.duolc.&rsu,tlf,?m&laer,urtnecatem.motsuc,?oc,topsgolb,??d!.&cos?gro?lop?m&oc?t??ossa?t&en?ra??ude?vog???ib!.&duolcsd,e&ht-rof,mos-rof,rom-rof,?izoj,nafamm,p&i&-on,fles,?ohbew,tfym,?retteb-rof,snd&nyd,uolc,?xro,?g??k!.&duolcj,gro?lim?moc?t&en?ropeletzak.saapu,?ude?vog???m!.&ca?gro?lim?oc?ten?ude?v&da?og????n!.&asq-irom--nx?ca?gro?htlaeh?i&r&c?o&am?ām???wi!k???keeg?l&im?oohcs??neg?oc!.topsgolb,?t&en?nemailrap?vog???a!niflla???rawhcs?s!.&ca?gro?oc???t!.&c&a?s??e&m?n??ibom?l&etoh?im??o&c?fni?g??ro?vt???u!.&gro?moc?oc?ten??rwon??yx!.&e&nozlacol,tisgolb,?gnitfarc,otpaz,??zub??λε?υε?авксом?брс!.&гро?до?ка?р&бо?п!у?????г&б?ро??дкм?зақ?итед?килотак?леб?мок?н&йално?ом??рку?сур!.&арамас,бпс,гро,зиб,ичос,ксм,м&ок,ырк,?рим,я,??тйас?фр?юе?յահ?לארשי?םוק?اي&روس?سيلم?ناتيروم??بر&ع?غملا??ة&كبش?ي&دوعسلا?روس??یدوعسلا??ت&ا&راما?لاصتا??را&ب?ڀ?ھب???ر&ئازجلا?ازاب?صم?طق??سنوت?عقوم?قارع?ك&تيب?يلوثاك??موك?ن&ا&تس&كاپ?کاپ??دوس?ر&يا?یا??مع?يلعلا??درالا?ميلا?ي&رحبلا?طسلف???ه&ارمه?يدوعسلا??وكمارا?يبظوبا?ۃیدوعسلا?टेन?त&राभ?ोराभ??नठगंस?मॉक?्मतराभ?ত&রাভ?ৰাভ??ালংাব?ਤਰਾਭ?તરાભ?ତରାଭ?ாயித்நஇ?ைக்ஙலஇ?்ரூப்பக்ஙிச?్తరాభ?ತರಾಭ?ംതരാഭ?ාකංල?มอค?ยทไ!.&จิกรุธ?ต็นเ?ร&ก์คงอ?าหท??ลาบฐัร?าษกึศ???ວາລ?ეგ?なんみ?アトス?トンイポ?ドウラク?ムコ?ル&グーグ?ーセ??ン&ゾマア?ョシッァフ??业企?东广?乐娱?亚基诺?你爱我?信中?务政?动移?博微?卦八?厅餐?司公?品食?善慈?团集?国中?國中?址网?坡加新?城商?尚时?山佛?店&商?网?酒大里嘉??府政?康健?息信?戏游?拉里格香?拿大?教主天?机手?构机!织组??标商?歌谷?浦利飞?港香!.&人個?司公?府政?絡網?織組?育教???湾台?灣&台?臺??物购?界世?益公?看点?科盈訊電?站网?籍書?线在?络网?网文中?聘招?販通?逊马亚?通联?里嘉?锡马淡?門澳?门澳?闻新?電家?국한?넷닷?성삼?컴닷??");
+ "a&0&0trk9--nx?27qjf--nx?e9ebgn--nx?nbb0c7abgm--nx??1&2oa08--nx?apg6qpcbgm--nx?hbbgm--nx?rdceqa08--nx??2&8ugbgm--nx?eyh3la2ckx--nx?qbd9--nx??3&2wqq1--nx?60a0y8--nx??4x1d77xrck--nx?6&1f4a3abgm--nx?2yqyn--nx?5b06t--nx?axq--nx?ec7q--nx?lbgw--nx??883xnn--nx?9d2c24--nx?a&a?it??b!.&gro?lim?moc?sr,t&en?opsgolb,?ude?vog??abila?c?ihsot?m?n??c!.&b&a?m?n??c&b?g?q??ep?fn?k&s?y??ln?no?oc,p&i-on,ohsdaerpsym,?sn?t&n?opsgolb,?un?ysrab,?i&ma?r&emarp?fa??sroc??naiva?s??d&ats?n&eit?oh??om?sa?tl??eg?f&c?ob??g!emo?naripi?oy??hskihs?i&dem!.remarf,?hs?k!on??sa!.snduolc,??jnin?k&aso?dov?ede?usto??l!.&c,gro?moc?ofni?r&ep?nb,?t&en?ni??ude?vog??irgnahs?le&nisiuc?rbmuder???m!.&ca?gro?oc?sserp?ten?vog??ahokoy?e00sf7vqn--nx?m??n!.&ac?cc?eman?gro?ibom?loohcs?moc?ni?o&c?fni?rp??r&d?o??s&u?w??vt?xm??av?is?olecrab?tea??p!.&bog?ca?d&em?ls??g&ni?ro??mo&c?n??oba?ten?ude??c?g7hyabgm--nx?ra!.&461e?6pi?iru?nru?rdda-ni?siri???s??q!.&eman?gro?hcs?lim?moc?t&en?opsgolb,?ude?vog???r&az?emac?f4a3abgm--nx?n!d5uhf8le58r4w--nx??u&kas?tan???s!.&bup?dem?gro?hcs?moc?ten?ude?vog??ac!.uban.iu,?iv??t&ad?elhta?led?oyot??u!.&a&cinniv?emirc?i&hzhziropaz?stynniv??s&edo?sedo??tlay?vatlop??bs?cc,d&argovorik?o!roghzu??tl,?e&hzhziropaz?i,nvir?t??f&i?ni,?g&l?ro??hk?i&stvinrehc?ykstyn&lemhk?vypork???k&c?m?s&nagul?t&enod?ul??v&iknarf-onavi?orteporp&end?ind?????l&iponret?opotsa&bes?ves??p??m&k?oc?s?yrk??n&c?d?i?osrehk?v?ylov??o&c,nvor??p&d?p,z??r&c?imotihz?k?ymotyhz??sk?t&en?l?z??ude?v:c?e&alokin?ik??i&alokym?hinrehc?krahk?vl?yk??k?l?o&g!inrehc??krahk??r?,xc,y&ikstinlemhk?mus?s&akrehc?sakrehc?tvonrehc???z&ib,u????v!aj?bb?et?iv??waniko?x&a?iacal??yogan?z&.&bew?c&a?i&n?rga???gro?l&im?oohcs??m&on?t??o&c!.topsgolb,?gn??radnorg?sin?t&en?la??ude?vog?wal??zip!.korgn,???b&00ave5a9iabgm--nx?1&25qhx--nx?68quv--nx?e2kc1--nx??2xtbgm--nx?3&b2kcc--nx?jca1d--nx??4&6&1rfz--nx?qif--nx??96rzc--nx??88uvor--nx?a&0dc4xbgm--nx?c?her?n?ra?t??b!.&erots?gro?moc?o&c?fni??ten?ude?v&og?t??zib??a??c&j?s??d&hesa08--nx?mi??g?l!.&gro?moc?ten?ude?vog??m??s!.&gro?moc?ten?ude?vog???tc-retarebsnegmrev--nx?u&lc!.&elej,snduolc,ysrab,?smas??p!.ysrab,??wp-gnutarebsnegmrev--nx??c&1&1q54--nx?hbgw--nx??2e9c2czf--nx?4&4ub1km--nx?a1e--nx?byj9q--nx?erd5a9b1kcb--nx??8&4xx2g--nx?c9jrb2h--nx??9jr&b&2h--nx?54--nx?9s--nx??c&eg--nx?h3--nx?s2--nx???a!.&gro?lim?moc?rrd,ten?ude?vog??3a09--nx!.&ca1o--nx?gva1c--nx?h&ca1o--nx?za09--nx??ta1d--nx?ua08--nx????b&a?b?ci?f76a0c7ylqbgm--nx?sh??c!.&eugaelysatnaf,gnipparcs,liamwt,nwaps.secnatsni,revres-emag,s&nduolc,otohpym,seccaptf,?xsc,?0atf7b45--nx?a1l--nx??e!.&21k?bog?dem?esab,gro?l&aiciffo,im??moc?nif?o&fni?rp??ten?ude?vog??beuq?n?smoc??fdh?i&l&buperananab?ohtac??n&agro?ilc?osanap??sum?tic??l!.&gro?moc?oc?ten?ude?vog?yo,?l??m!.&mt?ossa??p1akcq--nx??n!.&mon?ossa??i?p??relcel?s!.&gro?moc?ten?ude?vog???t!.&e&m,w,?hc,?s?w??v!.&e0,gro?lim?moc?ten?ude?v&g:.d,,og????wp?yn??d&2urzc--nx?3&1wrpk--nx?c&4b11--nx?9jrcpf--nx???5xq55--nx?697uto--nx?75yrpk--nx?9ctdvkce--nx?a!.mon?d?er?olnwod??b2babgm--nx?c!.vog?g9a2g2b0ae0chclc--nx??e&m!bulc??r!k??sopxe?timil?w??fc?g!.&ude?vog???h&d3tbgm--nx?p?t??i!.&ased?bew?ca?etrof,hcs?lim?o&c!.topsgolb,?g??palf,ro?sepnop?ten?ym?zib??b?ordna?p?rdam??l&iub?og?row??m!.&ed,ot,pj,t&a,opsgolb,???n&a&b?l!.citats:.&setis,ved,?,raas???ob?uf??o&of?rp??r&a&c&tiderc?yalcrab??ugnav??ef506w4b--nx?k!.&oc,ude,?jh3a1habgm--nx??of??s!.&dem?gro?moc?ofni?ten?ude?v&og?t???m!kcrem???t!.topsgolb,excwkcc--nx?l??uolc!.&a&bura-vnej.&1ti,abura.rue.1ti,?tcepsrep,xo:.&ku,nt,?,?b&dnevar,ewilek:.sc,,?citsalej.piv,drayknil,elej,gnitsohdnert.&ed,hc,?letemirp:.ku,,m&edaid,ialcer.&ac,ku,su,??n&evueluk,woru,?r&epolroov,o&pav,tnemele,??tenraxa.1-se,ululetoj,wcs.&gnilebaltrams,koobelacs,latemerab.&1-&rap-rf,sma-ln,?2-rap-rf,?rap-rf.&3s,cnf:.snoitcnuf,,etisbew-3s,mhw,s8k:.sedon,,?s&8k,ecnatsni.&bup,virp,?ma-ln.&3s,etisbew-3s,mhw,s8k:.sedon,,??waw-lp.&3s,etisbew-3s,s8k:.sedon,,??xelpciffart,yawocne.ue,??za5cbgn--nx??e&1&53wlf--nx?7a1hbbgm--nx?ta3kg--nx??2a6a1b6b1i--nx?3ma0e1cvr--nx?418txh--nx?707b0e3--nx?a!.&ca?gro?hcs?lim?oc?t&en?opsgolb,?vog??09--nx??b!.&ca?etisbew321,gnitsohbew,nevueluk.yxorpze,pohsdaerpsym,snoitulostsohretni.duolc,topsgolb,?ortal?ut!uoy???c&0krbd4--nx!.&a2qbd8--nx?b8adbeh--nx?c6ytdgbd4--nx?d8lhbd5--nx???a&lp!.oc,?ps!.&lla4sx,rebu,tsafym,?artxe??sla??i!ffo??n&a&d?iler?nif?rusni!efil?srelevart???eics!.oby,??rofria??d!.&1sndnyd,42pi-nyd,7erauqs,amil4,b&ow-nrefeilgitsng--nx,rb-ni,vz-nelletsebgitsng--nx,?decalpb,e&daregtmueart,luhcsvresi,mohsnd,nihcamyek,tiesbew321,?hcierebsnoissuksid,keegnietsi,lsd-ni,m&oc,rofttalpluhcs,?n&-i-g-o-l,aw-ym,e&lletsebgitsnüg,sgnutiel,?i&emtsi,lreb-n&i,yd,??norblieh-sh.ti.segap,oitatsksid-ygolonys,pv&-n&i,yd,?nyd,?refeilgitsnüg,?orp-ytinummoc,p&h21,iog:ol,,ohsdaerpsym,?r&e&ntrapdeeps.remotsuc,su&-lautriv,lautriv,?t&adpusnd,tub-ni,uor-ym,?vres&-e&bucl,mohym,?bew-emoh:.nyd,,luhcs,??ogiv-&niem,ym,??s&d-&onys,ygolonys,?nd&-&dd,nufiat,sehcsimanyd,tenretni,yard,?isoc.nyd,ps,yard,?oper-&nvs,tig,?sndd:.&nyd,sndnyd,?,?topsgolb,vresi-&niem,tset,?xi2,y&awetag-&llawerif,ym,?srab,tic-amil,?zten&mitbel,sadtretteuf,??art!.oby,?i&sdoow?ug??on--nx??e!.&bil?dem?eif?gro?irp?kiir?moc!.topsgolb,?pia?ude?vog??ei?ffoc?gg?r&f?ged???f&a&c?s??il??g!.&gro?lim?moc?t&en?vp??ude?vog??a&f?gtrom?p!.&3xlh,detalsnart,grebedoc,kselp,sndp,tengam,xlh,y&cvrp,kcor,???rots?yov??elloc?na&hcxe?ro!.hcet,??roeg?ug??i!.&pohsdaerpsym,topsgolb,vog??tilop?v&bba?om???j!.&fo,gro?oc?ten???k!.&c&a?s??e&m?n??ibom?o&c!.topsgolb,?fni?g??ro??i&b?l?n???l&a&dmrif?s!rof???b&a?i&b?dua???c&aro?ric??dnik?g!oog??i&bom?ms??l&asal?erauqa??ppa?uhcs?yts!efil???m!.&4&32i,p&ct,v,??66c,ailisarb,b&dnevar,g-raegelif,?ca?duolcsd,e&d-raegelif,i&-raegelif,lpad:.tsohlacol,,?pcm,?g&ro?s-raegelif,?hctilg,kcatsegde,noitatsksid,o&bmoy,c?t&nigol,poh,??p&i&on,snart.etis,?j-raegelif,ohbew,?r&aegelif,idcm,ofsnd,?s&dym,ndd,ti?umhol,?t&en?s&acdnuos,ohon,??u&a-raegelif,de??v&irp?og??y&golonys,olpedew,srab,??a&g?n!.&reh.togrof,sih.togrof,???em?i&rp?twohs??orhc?w??n!goloc?i&lno!.&egats-oree,oree,ysrab,??w??o!.&derno:.gnigats,,ecivres,knilemoh,?hp?latipac?ts&der?e&gdirb?rif???z!.&66duolc,amil,sh,???ruoblem??om?p!.&bog?gro?lim?mo&c?n??t&en?opsgolb,?ude??irg?yks??r!.&mo&c?n??ossa?topsgolb,?a&c!htlaeh??pmoc?wtfos??bc?eh?if?ots!.&e&rawpohs,saberots,?yflles,??taeht?u&ces?sni?t&inruf?necca??za???s!.&a!bap.us,disnim321,?b!ibnal?rofmok??c!a??d!b?n&arb?ubroflanummok???e?f!noc,?g!ro??h!f??i!trap??k!shf??l?m!oc,t??n!mygskurbrutan??o?p!ohsdaerpsym,p??r!owebdluocti,?s!serp?yspoi,?t!opsgolb,?u?vhf?w?x!uvmok??y?z??a&c?el?hc??i&er?urc??nesemoh?roh?uoh??t&a&d?ts&e!laer??lla???is!.&e&lej,nilnigol,r&etnim,ocevon,?winmo,?k&rowtenoilof,wnf,?laicosnepo,n&eyb,oyc,?spvtsaf,thrs,xulel,ysrab,?bew!.remarf,??ov?ra?t&ioled?ol??utitsni??u&lb?qi&nilc?tuob???v!.&21e?b&ew?ib?og??ce&r?t??erots?gro?lim?m&o&c?n??rif??o&c?fni??rar?stra?t&en?ni??ude?vog??as?e3gerb2h--nx?i&l!.xlh,?rd?ssergorp??ol??w&kct--nx?r??xul?y!.&gro?lim?moc?ten?ude?vog????f&0f3rkcg--nx?198xim--nx?280xim--nx?7vqn--nx?a!.&gro?moc?ten?ude?vog???b!.vog?wa9bgm--nx??c!.topsgolb,a1p--nx!.&a14--nx,b8lea1j--nx,c&avc0aaa08--nx,ma09--nx,?f&a1a09--nx,ea1j--nx,?gva1c--nx,nha1h--nx,pda1j--nx,zila1h--nx,??ns??ea1j--nx?g?iam?l&a1d--nx?og??n!.&bew?cer?erots?m&oc?rif??ofni?re&hto?p??stra?ten???orp?p!.&gro?moc?ude???rus?t!.hcs,w??vd7ckaabgm--nx?w!.&hcs,zib,???g&2&4wq55--nx?8zrf6--nx??3&44sd3--nx?91w6j--nx!.&a5wqmg--nx?d&22svcw--nx?5xq55--nx??gla0do--nx?m1qtxm--nx?vta0cu--nx????455ses--nx?5mzt5--nx?69vqhr--nx?7&8a4d5a4prebgm--nx?rb2c--nx??a!.&gro?mo&c?n??oc?ten??vd??b!.&0?1?2?3?4?5?6?7?8?9?a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t!opsgolb,?u?v?w?x?y!srab,?z???c!b?za9a0cbgm--nx??e!.&eman?gro?ics?lim?moc!.topsgolb,?nue?ten?ude?vog??a??g!.&ayc,gro?lenap:.nomead,,oc?saak,ten???i&a?v??k!.&g&olb,ro??ku,lim?moc?oi,pj,su,ten?ude?v&og?t,???m!.&drp?gro?lim?m&o&c?n??t??oc?ude?vog??pk??n!.&dtl,eman?gro?hcs?i!bom??l&im?oc,?m&oc!.topsgolb,?rif,?neg,ogn,ten?ude?vog??aw?i!b!mulp??car?d&art?dew??h&sif?tolc??k&iv?oo&b?c???ls?n&aelc?iart??p!pohs??re&enigne?tac??t&ad?ekram?hgil?lusnoc?neg?ov?soh!.tfarcnepo,??vi&g?l???o!s??u&rehcisrev?smas?tarebsnegömrev???o&d?lb?og!.&duolc,etalsnart,???r&2n084qlj--nx?ebmoolb?o!.&77ndc.c:sr,,a&remacytirucesym,t&neimip,sivretla,?z,?bew-llams,d&ab-yrev-si,e&sufnocsim,vas-si,?nuof-si,oog-yrev-si,uolc&arfniarodef,mw,??e&a,cin-yrev-si,grof&loot,peh,?l&as-4-ffuts,poeparodef,?m&-morf,agevres,ohruoyslles,?n&ozdop,uma.elet,?r&ehwongniogyldlob,iwym,uces-77ndc.nigiro.lss,?t&adidnac-a-si,is&-ybboh,golb,???fehc-a-si,golbymdaer,k&eeg-a&-si,si,?h,nut,?l&i&amwt,ve-yrev-si,?lawerif&-ym,ym,?sd-ni,?m&acssecca,edom-elbac,?n&af&blm,cfu,egelloc,lfn,s&citlec-a-si,niurb-a-si,tap-a-si,?xos-a-si,?ibptth,o&itatsksid,rviop,?p&j,v-ni,??o&jodsnd,tp&az,oh,??p&i&-on,fles,?o&hbew,tksedeerf,?tf&e&moh,vres,?ym,??r&e&gatop,ppepteews,su-xunil-a-si,?gmtrec,vdmac,?s&a&ila&nyd,snd,?nymsd,?b&alfmw,bevres,?d&ikcet.3s,ylimaf,?eirfotatophcuoc,j,koob-daer,ltbup,nd&-won,deerf,emoh,golb,kcud,mood,nyd:.&emoh,og,?,ps,rvd,tog,uolc,?s&a-skcik,ndd,?tnemhcattaomb,u,?t&ce&jorparodef.&duolc,gts.so.ppa,so.ppa,?riderbew,?e&ews-yrev-si,nretni&ehtfodne,fodne,??hgink-a-si,oi-allizom,s&ixetn&od,seod,?o&h-emag,l-si,?rifyam,??ue:.&a&-q,c,?cm,dc,e&b,d,e,i,m,s,?g&b,n,?hc,i&f,s,?k&d,m,s,u,?l&a,i,n,p,?n&c,i,?o&n,r,ssa,?pj,r&f,g,h,k,t,?s&e,i:rap,,u,?t&a,en,i,l,m,ni,p,?u&a,de,h,l,r,?vl,y&c,m,?z&c,n,??,vresnyd,x&inuemoh,unilemoh,?y&limafxut,srab,???ub&mah?oj???s!.&delacsne,gro?moc?rep?t&en?opsgolb,?ude?vog??gb639j43us5--nx??t?u!.&c&a?s??en?gro?moc?o&c?g??ro?topsgolb,??v!.ta,a1c--nx??wsa08--nx??h&0ee5a3ld2ckx--nx?4wc3o--nx!.&a&2xyc3o--nx?3j0hc3m--nx?ve4b3c0oc21--nx??id1kzuc3h--nx?l8bxi8ifc21--nx?rb0ef1c21--nx???8&8yvfe--nx?a7maabgm--nx??b!.&gro?moc?ten?ude?vog??mg??c!.&7erauqs,amil4,duolc-drayknil,etisbew321,gniksnd,p&h21,ohsdaerpsym,?sndtog,topsgolb,wolf.e&a.1pla,nigneppa,?xi2,ytic-amil,?aoc?et?ir!euz??r&aes?uhc??sob?taw!s???d0sbgp--nx?f&2lpbgm--nx?k??g!.&gro?lim?moc?ude?vog???m!a1j--nx??ocir?p!.&gro?i?lim?moc?ogn?ten?ude?vog???s!.&g&nabhsah,ro??l&im?xv,?m&oc?roftalp.&cb,su,tne,ue,??pib,ten",
+ "?vog?won,yolpedew,?a&c?nom??i&d?f?ri???t!.&ca?enilno,im?ni?o&c?g??pohs,ro?ten??iaf!.oby,?laeh!.arh,?orxer?rae??vo!.lopdren,?zb??i&3tupk--nx?7a0oi--nx?a!.&ffo?gro?moc?ten?uwu,?1p--nx?bud?dnuyh?tnihc??b!.&gro?moc?oc?ro?ude??ahduba?o!m!.&duolcsd,ysrab,???s??c!.&ayb-tropora--nx?ca?d&e?m??esserp?gro?ln,moc?nif,o&c?g?ssa??ro?t&en?ni?roporéa??ude?vuog??cug?t??d&dk?ua??e&bhf--nx?piat??f!.&aw5-nenikkh--nx,dnala?i&ki,spak,?mroftalpduolc.if,nenikkäh,pohsdaerpsym,retnecatad.&omed,saap,?topsgolb,uvisitok321,yd,?onas??g!.&d&om?tl??gro?moc?ude?vog???h&c&atih?ra??s&abodoy?ibustim???juohs?k!.&gro?moc?ofni?ten?ude?vog?zib??b4gc--nx?iw!.remarf,?nisleh?s?uzus??l!.&aac,topsgolb,?drahcir?iamsi??maim?n!.&b&ew?og??ca?gro?lim?mo&c?n??ni?o&c?fni??pp?t&en?ni??ude?zib??airpic?i&hgrobmal?m??re??om?rarref?s!.&egaptig,ppatig,topsgolb,?ed??t&i&c?nifni??rahb??ut?v!.&21k?gro?moc?oc?ten???wik?xa&rp?t??yf??j&6pqgza9iabgm--nx?8da1tabbgl--nx?b!.&acirfa?eto?gro?m&oc?siruot??o&c!e??fni?noce?rga?tser??russa?s&etcetihcra?risiol?tacova??t&en?naruatser?opsgolb,?ude?vinu?yenom???d?f!.&ca?eman?gro?lim?moc?o&fni?rp??ten?vog?zib???nj?s?t!.&bew?c&a?in??eman?gro?lim?moc?o&c?g??t&en?ni?set??ude?vog?zib???yqx94qit--nx??k&8uxp3--nx?924tcf--nx?arfel?c&a&bdeef?lb??ebdnul?ilc?reme??d!.&e&disemmejh321,rots,?ger,mrif,oc,pohsdaerpsym,topsgolb,zib,?t??e&es?samet??h!.&a&4ya0cu--nx?5wqmg--nx??b3qa0do--nx?cni,d&2&2svcw--nx?3rvcl--nx??5xq55--nx?tl,?g&a0nt--nx?la0do--nx?ro??i&050qmg--nx?7a0oi--nx?xa0km--nx??m&1qtxm--nx?oc??npqic--nx?saaces,t&en?opsgolb,?ude?v&di?og?ta0cu--nx??xva0fz--nx?人&个?個?箇??司公?府政?絡&網?网??織&組?组??织&組?组??络&網?网??育&敎?教???n??i&tsob?vdnas??l!.&bew?c&a?os??dtl?gro?hcs?letoh?moc?nssa?ogn?prg?t&en?ni??ude?vog??at?cd?is??m!.&eman?fni?gro?moc?t&en?opsgolb,?ude?vog???n&ab!cfdh?etats?mmoc?t&en?fos??u??i!l!.&noyc,pepym,??p???oob?p!.&b&ew?og??gro?kog?m&af?oc??nog?ofni?pog?sog?ten?ude?vog?zib???row!ten!.&htumiza,nolt,o&c,vra,????s!.topsgolb,?t?u!.&c&a?lp??dtl?e&cilop?m??gro!.&gul:g,,sgul,yr&ettoly&lkeew,tiniffa,?tneelffar,???lenap-tnednepedni,n&noc,oissimmoc-&layor,tnednepedni,??o&c!.&bunsorter.tsuc,en&ilnoysrab,ozgniebllew,?krametyb.&hd,mv,?omida,p&i-on,ohsdaerpsym,?t&fihsreyal.j,opsgolb,?vres-hn,ysrab,??rpoc,?psoh,shn?t&en?nmyp,seuqni-tnednepedni,?vog!.&eci&ffoemoh,vres,?ipa,ngiapmac,??weiver-tnednepedni,y&riuqni-&cilbup,tnednepedni,?srab,????l&04sr4w--nx?a!.&gro?lim?moc?t&en?opsgolb,?ude?vog??bolg?c?ed?g!el??i&c&nanif!.oc,lpl??os??romem?tnedurp??n&if?oitanretni??t&i&gid!.sppaduolc:.nodnol,,?p&ac?soh???ned?ot??utum!nretsewhtron???c!.&bog?lim?oc?topsgolb,vog???dil?e&datic?n&ahc?nahc!rehtaew???t!ria?tam??vart??f&8f&pbgo--nx?tbgm--nx??a?n??g!.&gro?moc?oc?ten?ude?xx,zib,??h&d?op??i!.&21k?ca?fdi?gro?inum?oc!.&egapvar,redrotibat,t&ibatym,opsgolb,???ten?vog??a&f?m&e?g?toh???m?r??l&a&b&esab?t&eksab!.&sua,zn,??oof???c?mt??e&d?hs??ihmailliw?j??m!.&esserp?gro?moc?ten?ude?v&og?uog????n!.&etisbew321,no&med,rtsic,?oc,pohsdaerpsym,retsulc-gnitsoh,topsgolb,vog,yalphk,?o??o&a?btuf?l!.gmo,?o&c!.&ed,rotnemele,??hcs??rit?u??p!.&a&cin&diws?gel??d&g,ortso?urawon??i&dem?mraw?nydg,?k&elo&guld?rtso??slopolam?tsu?ytsyrut??l&ip?o&kzs?w&-awolats?oksnok????n&erapohs,img?zcel,?rog&-ai&bab?nelej??j?z??syn?tsaim?w&a&l&eib?i?o??zsraw??o&namil?tainop,??z&eiwolaib?mol???c&e&iw&alselob?o&nsos?rtso???le&im?zrogz???orw,p??d&em,ia?ragrats?uolc&inu,sds,??e&c&i&lrog?w&ilg,o&hc&arats?orp??klop?tak????yzreibok??i&csjuoniws?ksromop?saldop??l&ahdop?opo??napokaz,t&atselaer?iselpmis,?z&romop?swozam???g&alble?ezrbo&lok?nrat??ro??hcyzrblaw?i&csomohcurein?grat?klawus??k&e&rut?walcolw??in&byr?diws,sark,?le?o&nas?tsylaib??rob&el?lam??s&als?jazel?nadg,puls?rowezrp???l&colw?e&r?vart??i&am?m???m&o&c?dar?n?tyb??s&g?iruot??t!a???n&a&gaz?nzop,?i&bul?cezczs?lbul,molow?nok?zd&eb?obeiws???uleiw?y&tzslo?z&rtek?seic????o&c,fni?k&celo?zdolk??lkan?n&leim?pek?t&uk?yzczs??z&copo?eing?rowaj???rga?tua?w&ejarg?ogarm???p&e&eb,lks!emoh,??klwwortso?ohs!-ecremmoce,daerpsym,??romophcaz?sos?t&aiwop?en?opos,ra,sezc??ude?v&irp?og!.&a&io?p?s!w???bni&p?w??ci?dtiw?e&ko?ss&p?w???fiw?g&imu?u??hiiw?m&igu?rio?u!o???nds!ipz??o&ks?p!pu??s?wtsorats??p&a?sp!mk?pk?wk??u&m?p??wk?z??r&hcso?ksw?p?s??s&i?oiw?u?zu??talusnok?w&gzr?i&p?rg?w??m?o&o?pu??u!imzw???z&kw?ouw?????w&a&l&corw?sizdow??w??o&golg?k&ark,ul?zsurp??r&az?gew??t&rabul,sugua??z&coks?sezr????xes?y&buzsak?d&azczseib?ikseb??hcyt?n&jes?lod-zreimizak??pal?r&ogt?uzam??walup?zutrak??z&am-awar?c&aprak?iwol?zsogdyb??dalezc?ib?s&i&lak?p??uklo????l??r&as?f?s??s!.&gro?moc?ten?ude?vog???t!.vog??ubnatsi?x3b689qq6--nx?yc5rb54--nx??m&00tsb3--nx?1qtxm--nx?981rvj--nx?a!.&aayn,enummoc?gro?moc?o&c?idar,ken,?t&en?opsgolb,??c!bew??dretsma?e&rts?t!.&citsalej,esruocsid,???fma?xq--nx??b!.&gro?moc?ten?ude?vog??i??c!.&moc?oc?ten?vog???d!.&gro?moc?ten?ude?vog???f!.&gro?moc?oidar,ten?ude??i??g!vu96d8syzf--nx??h?i!.&ca?gro?moc?o&c!.&clp?dtl???r,?t&en?t??vt??k?rbg4--nx??k!.&drp?e&rianiretev?sserp??gro?lim?m&o&c?n??t??nicedem?ossa?pooc?s&eriaton?neicamrahp?sa??ude?v&og?uog????l&if?ohkcots??o!.&dem?gro?m&oc?uesum??o&c?rp??ten?ude?vog??b?c!.&0x,2aq,3pmevres,5sndd,a&c&-morf,ir&bafno,fa,??g&-morf,oy-sehcaet,?i-morf,m&-morf,all&-a-si,amai,??p&-morf,c-a-si,?r&emacytirucesym,odih,?s,tadtsudgniht,v-morf,w-morf,z,?b&ew&-sndnyd,arukas,draiw.segap,ottad,?ildts.ipa,?c&amytirucesemoh,d-morf,esyrcs,itsalej.omed,n&-morf,vym,?p&kroweht,ytirucesemoh,?q,rievres,s-morf,?d&aerotffuts,e&calpb,ifitrec-&si,ton-si,?llortnocduolc,rewopenignepw:.sj,,tsohecapsppa,?i&-morf,rgevissam.saap,?m-morf,n&-morf,abeht-htiw-si,?s-morf,uolc&-noitatsyalp,hr,iafaw.&d&ej,yr,?nol,?meaeboda,nevia,panqym:-&ahpla,ved,?,smetsystuo,tekcilc,ved&j,pw,??vreser,wetomer,?e&butuoyhtiw,ciffo-sndnyd,d:-morf,o&celgoog,n&il.srebmem,neve.&1-&su,ue,?2-&su,ue,?3-&su,ue,?4-&su,ue,????,erf&-sndnyd,sndd,?filflahevres,g&de-yltsaf,nahcxeevres,?i&hcet-a-si,p-sekil,?k&auqevres,irtsretnuocevres,?l&bitpa-no,googhtiw,?m&agevres,ina-otni-si,oh-&sndnyd,ta-sndnyd,??n&-morf,ilno&-evreser,ysrab,?og-si,?r&alfduolcyrt,ehwynanohtyp:.ue,,ihcec,?srun-a-si,t&i&nuarepo,s&-ybboh,aloy,elpmis,tipohs,xiw,??omer-sndnyd,upmocsma,ysgolb,?v&als-elcibuc-a-si,i&lsndd,tavresnoc-a-si,??z&amkcar,eelg,iig,??fehc-a-si,g&ni&gats-&raeghtua,swennwot,?ksndd,robsikrow,tsoh-bt.etis,?o&fgp,lb&-sndnyd,sihtsetirw,???h&n-morf,o-morf,?i&fiwehtno,h-morf,kiw-sndnyd,m-morf,p&aerocne,detsoh,?r-morf,w-morf,z&ihcppa,nilppa,??jn-morf,k&a&-morf,erfocsic,?cils-si,eeg&-a&-si,si,?sndd,?h,latsnaebcitsale:.&1-&htuos-pa,lartnec-&ac,ue,?ts&ae&-&as,su,?ht&ron-pa,uos-pa,??ew-&su,ue,vog-su,???2-ts&ae&-su,ht&ron-pa,uos-pa,??ew-&su,ue,??3-ts&aehtron-pa,ew-ue,??,o-morf,r&adhtiwtliub,ow&-&sndnyd,ta-sndnyd,?ten-orehkcats,??sedal,u,?l&a&-morf,colottad,rebil-a-si,?f-morf,i&-morf,am&-sndnyd,detsohpw,??l&ecelffaw,uf-ytnuob:.a&hpla,teb,?,?ppmswa,ru-&elpmis,taen,?ssukoreh,xegap,?m&n-morf,pml.ppa,rofe&pyt.orp,rerac-htlaeh,?sacrasevres,uirarret-yltsaf,?n&a&cilbuper-a-si,f&-sllub-a-si,racsan-a-si,?i&cisum-a-si,ratrebil-a-si,?tarukas,?c,dc&hsums,umpw,xirtrepmi,?eerg-a-si,i&-morf,jod,?m-morf,o&ehtnaptog,isam-al-a-tse,r&italik,tap-el-tse,?s&iam-al-a-tse,replausunu,??pj,t-morf,?o&bordym,c,hce-namtsop,jodsnd,m&-morf,ed-baltlow,?n:iloxip,,ttadym,?p&2pevres,aelutym,i&-sndnyd,fles,ogol,ruoy&esol,hctid,?ym&eerf,teg,??ohsdaerpsym,pa&-rettalp,anis:piv,,esaberif,k1,lortnocduolc,oifilauq,r&aegyks,oetem:.ue,,?t&ilmaerts,norfegap,?ukoreh,?t&fevres,thevres,??r&081,a:-morf,tskcor-a-si,,b,e&d&iv&erp-yb-detsoh.saap,orpnwo,?ner&.ppa,no,??e&bevres,nigne-na-si,?ggolb-a-si,h&caet-a-si,pargotohp-a-si,?krow-drah-a-si,n&gised-a-si,ia&rtlanosrep-a-si,tretne-na-si,??p&acsdnal-a-si,eekkoob-a-si,?retac-a-si,subq,tn&ecysrab,iap-a-si,uh-a-si,?vres&-&ki.&cpj-rev-duolcj,duolcj,?s&ndnyd,pvtsaf,??inim,nmad,sak,?y&alp-a-si,wal-a-si,?zilibomdeepsegap,?g,ituob,k,mgrp.nex,o&-morf,sivdalaicnanif-a-si,t&areleccalabolgswa,c&a-na-si,od-a-si,?susaym,??p-morf,u&as-o-nyd,e&tsoh.&duolc-gar,hc-duolc-gar,?ugolb-nom-tse,?omuhevres,??s&a&apod,ila&nyd,snd,?nymsd,vnacremarf,?bbevres,ci&p&-sndnyd,evres,?tcatytiruces,?dylimaf,e&cived-anelab,itilitu3,lahw-eht-sevas,mag-otni-si,t&i&iis,sro,?yskciuq,??fpi-&eralfduolc,fc,?i&ht2tniop,pa&elgoog,tneltneg,??jfac,k&-morf,aerf-ten,colb&egrof,pohsym,??m&-morf,cxolb,?n&d&-pmet,dyard,golb,htiwssem,mood,tog,?kselp,nyd,ootrac-otni-si,?o&-xobeerf,xobeerf,?ppa&-avnac,raeghtua,t&ikria,neg,??r&ac-otni-si,e&ntrap-paelut,tsohmaerd,??s&e&l-rof-slles,rtca-na-si,?ibodym,?tsaeb-cihtym.&a&llicno,zno,?ilay,lacarac,re&gitnef,motsuc,?sv,toleco,x:n&ihps,yl,?,?u,wanozama.&1-&ht&ron-ue.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??uos-&em.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??fa.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??pa&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,??ue.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,????la&nretxe-3s,rtnec-&ac&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,??ue&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,????ts&ae&-&as&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,??pa.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??su:-etisbew-3s,.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,yawetag-scitylana,?,?ht&ron-pa&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,yawetag-scitylana,??uos-pa&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,????ew-&su&-&3s,etisbew-3s,?.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,???ue&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,yawetag-scitylana,??vog-su-&3s,spif-3s,????2-ts&ae&-su&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,yawetag-scitylana,??ht&ron-pa&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,??uos-pa&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??kcatslaud.3s,????ew-&su&-&3s,etisbew-3s,?.&9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??yawetag-scitylana,??ue&-3",
+ "s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,????3&-ts&aehtron-pa.9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??ew-ue&-3s,.&3s,9duolc&-swa.stessa-weivbew,.s&fv,tessa-weivbew,??etisbew-3s,kcatslaud.3s,???s,??yasdrocsid,?t&arcomed-a-si,c&-morf,etedatad.&ecnatsni,omed,??eel&-si,rebu-si,?hgilfhtiwletoh,i:batym,,m-morf,n&atnuocca-na-si,e&duts-a-si,r-ot-ecaps,tnocresu&buhtig,e&capsppa,donil.pi,lbavresbo.citats,?pl,???ops&edoc,golb,ppa,?s&i&hcrana-&a-si,na-si,?laicos-a-si,pareht-a-si,tra-na-si,xetn&od,seod,??oh&piym,sfn,??u&-morf,nyekcoh-asi,?v-morf,?u&-rof-slles,4,a-sppatikria,e,h,oynahtretramssi,r:ug-a-si,,?v&n-morf,rdlf,w-morf,?w&o&lpwons-yrt,zok,?ww100,?x&bsbf.sppa,em,i&nuemoh,rtrepmi,?obaniateb,t-morf,unilemoh,?y&a&bnx:.&2u,lacol-2u,?,l&erottad,pezam,?wetag-llawerif,?dnacsekil,fipohsym,k&-morf,niksisnd,?rot&ceridevitcaym,sitk,?u:goo,,w-morf,x&alagkeeg,orp&hsilbup,mapson.duolc,???zesdrocsid,?inu??m?or?tsla??p!.&eman,nwo,??raf!.jrots,etats??s?t!.&gro?lim?mo&c?n??oc?ten?ude?vog???u&esum?rof??z!.&ca?gro?hcs?lim?moc?o&c?fni??ten?ude?vog?zib????n&315rmi--nx?a&brud?cilbuper?f?grompj?hkaga?idraug?m?ol?ssin?u&hix?qna??varac?yalo??b!.&gro?moc?oc,ten?ude?vog??c??c!.&ah?bh?c&a?s??d&5xq55--nx?g?s?uolctnatsni,?eh?g&la0do--nx?ro??h&a?q?s??i&7a0oi--nx?h??j&b?f?t?x?z??kh?l&h?im?j??m&n?oc!.swanozama.&1-htron-nc.3s,be.1-&htron-nc,tsewhtron-nc,????n&h?l?s?y??om?qc?s&g?j?ppa-avnac,?t&cennockciuq.tcerid,en??ude?vog?wt?x&g?j?n?s??z&g?x??司公?絡網?络网??b??d&g!.ypnc,?ka??e&drag?erg?fuak?gawsklov?hctik?i&libommi?w??m?po?r!ednaalv??sier?ves??g!.&ca?gro?moc?ten?ude?vog??is&ed!.ssb,?irev???h!.&bog?cc,gro?lim?moc?ten?ude???i!.&ac?bew,c&a?in??dni?e&m?sabapus,?g&5?6?p?ro??i&a?hled??ku?l&evart?im??m&a?oc?rif??n&c?eg??o&c?fni?i?rp??p&ooc?u??r&ahib?d?e??s&c?er?nduolc,senisub?u??t&arajug?en!retni??ni?opsgolb,sop??ude?v&og?t??ysrab,zib??elknivlac?griv?ks?lreb?p?v?w?x??k!.&gro?ten?ude?vog???l&eok?ocnil??m!.&cyn,gro?ude?vog???o&dnol?i&hsaf?n&o?utiderc??siv!orue??t&a&cude!.oc,?dnuof?tsyalp??c&etorp?u&a?rtsnoc?????kin?las?mrom?nac?p&q?uoc??s&iam?pe?scire??t&ron?sob??zama??p!.&gro?oc?ten?ude?vog??k??r&e&c?yab??op!.eidni,??s!.&gro?moc?osrep?t&opsgolb,ra??ude?v&inu?uog????t!.&d&ni?uolcegnaro,?gro?ltni?m&oc!nim??siruot??nif?o&fni?srep??sne?t&an?en??vog??m??u&f?r!.&bdnevar,lper,retropno,s&h,revres,?tnempoleved,??stad?xamay?y??v!.&a&lnos?ohhnah&k?t???c&a?ouhphnib?uhphniv??di?e&man?rtneb?uhneihtauht??g&n&a&boac?ig&ah?cab?n&a?ei&k?t???uah??nad?rtcos?uqneyut??o&dmal?hpiah?lhniv?nkad?ud&hnib?iah????ro??h&ni&b&aoh?gnauq?hnin?iaht??d&hnib?man??mihcohohphnaht?n&cab?gnauq?yat??tah?vart??tlaeh??i&a!bney?coal?gngnauq?laig?ngnod??onah?rtgnauq??kalkad?m&an&ah?gnauq??oc?utnok??n&a&ehgn?gnol?kcab?uhthni&b?n???e&ibneid?y&gnuh?u&gniaht?hp????osgnal??o&fni?ht&nac?uhp??i?rp??pahtgnod?t&en?ni?opsgolb,?u&a&hcial?mac?tgnuv-airab??de?eilcab??vog?zib???wo&rc?t!epac????o&76i4orfy--nx?a!.&bp?de?go?oc?ti?vg??boat??b!.&a&ci&sum?tilop??i&c&arcomed?neic??golo&ce?ncet??m&edaca?onoce??rt&ap?sudni??vilob??n&egidni?icidem??serpme?tsiver?vitarepooc??b&ew?og??dulas?e&rbmon?tr&a?op&ed?snart????g&olb?ro??ikiw?l&a&noi&canirulp?seforp??rutan??im??moc?o&fni?lbeup?rga?tneimivom??saiciton?t&askt?en?ni??ude?vt??h?iew?olg??c!.&bew?cer?dr&c,rac,?esabapus,gro?ipym,l&im?per:.di,,?m&o&c!.topsgolb,?n??rif??ofni?s&egap&dael,l,?tra??t&4n,en?ilperdellawerif:.di,,ni??ude?vog??a?e?in?mara?s&edarb?ic???d!.&b&ew?og??dls?gro?lim?moc?t&en?ra??ude?vog??agoba?if?zd7acbgm--nx??e&c?d&iv?or???f!ni!.&e&g&delwonk-fo-l&errab,lerrab,?ellocevoli,?ht-skorg,rom-rof-ereh,tadpusn:d,,?llatiswonk,macrvd,ofni-v,p&i&-on,fles,?ohbew,?ruo-rof,s&iht-skorg,nd&-cimanyd,nyd,uolc,??tsrifyam,ysrab,zmurof,???g&el?n!am?ib???hwsohw?i!.&35nyd,8302,a&minifed,tad-b,?b&altig,uhtig,?czh,d&in,raobelgaeb,u&olc&iaznab.ppa,ropav,?rd,??e&c&apsinu.1rf-duolc,ivedniser,?donppad.sndnyd,egipa,lej,nilnigol,sufxob,t&i&beulb,snoehtnap,?newtu,ybeeb.saap,??gni&gatsniser.secived,tsohytsoh,?ilpu,k&coregrof.di,orgn:.&as,ni,p&a,j,?su,u&a,e,??,ramytefasresworb,?moc?n&aicisum,mtsp:.kcom,,yded,?ot&oq,pyrctfihs,?p&opilol,pa&-arusah,e&nalpkcab,tybeeb.1dkes,???r&e&tsneum-hf,vres&cisab,lautriv,??ial.sppa,?s&codehtdaer,gnihtbew,nemeis-om,pparevelc,t&acdnas,ekcit,??t&e&kcubtib,notorp,?i&belet,detfihs,gude,kecaps,?raedon.egats,s&ohg,udgniht.&cersid.&dvreser,tsuc,?dorp.tsuc,gnitset.&dvreser,tsuc,?ved.&dvreser,tsuc,????vgib.0ku,whs,x&bslprbv.g,cq,rotide,?y&olpedew,srab,??b?d&ar?u&a?ts???j?r?syhp??j!.&eman?gro?hcs?lim?moc?ten?ude?vog???ll&ag?o??m!.&gro?moc?ten?ude?vog??g?il?mi?orp??n!.&a&0&b-ekhgnark--nx?c-iehsrgev--nx?g-lksedlig--nx?k-negnanvk--nx??1&p-nedragy--nx?q-&asierrs--nx?grebsnt--nx?lado-rs--nx?n&egnidl--nx?orf-rs--nx??regnayh--nx?ssofenh--nx??r-datsgrt--nx?s-ladrjts--nx?v-y&senner--nx?vrejks--nx???3g-datsobegh--nx?4&5-&dnaleprj--nx?goksnerl--nx?tednalyh--nx??6-neladnjm--nx?s-&antouvachb--nx?impouvtalm--nx??y-&agrjnevvad--nx?ikhvlaraeb--nx???7k-antouvacchb--nx?8&k-rekie-erv--nx?l-ladrua-rs--nx?m-darehsdrk--nx??a!.sg??bct-eimeuvejsemn--nx?d&do?iisevvad?lov?narts?uas??f&1-&l--nx?s--nx??2-h--nx??g&10aq0-ineve--nx?av?ev?lot?r&ajn&evvad?u??ájn&evvad?u????h?iz-lf--nx?j&ddadab?sel??k&el?hoj&sarak?šárák??iiv&ag&na&el?g??ŋ&ael?ág???ran???l&f?lahrevo?o&ms?s??sennev?t-&ilm--nx?tom--nx??u&-edr--nx?s??øms??muar?n&0-tsr--nx?2-dob--nx?5-&asir--nx?tals--nx??a&r!-i-om?f?t??t??douvsatvid?kiv?m&os?øs??n&od?ød??ra?sen?t&aouvatheig?ouv&a&c&ch&ab?áb??h&ab?áb???n??i&ag?ág??sa&mo?ttvid??án???z-rey--nx?ær&f?t???o&p-&ladr--nx?sens--nx??q-nagv--nx?r-asns--nx?s-kjks--nx?v-murb--nx?w-&anr&f--nx?t--nx??ublk--nx???ppol?q&0-t&baol--nx?soum--nx?veib--nx??x-&ipphl--nx?r&embh--nx?imph--nx???y-tinks--nx??r&f-atsr--nx?g-&an&ms--nx?nd--nx??e&drf--nx?ngs--nx??murs--nx?netl--nx?olmb--nx?sorr--nx??h-&a&lms--nx?yrf--nx??emjt--nx??i&-&lboh--nx?rsir--nx?y&d&ar--nx?na--nx??ksa--nx?lem--nx?r&ul--nx?yd--nx????stu??j-&drav--nx?rolf--nx?sdav--nx??kua?l-&drojf--nx?lares--nx??m-tlohr--nx?n-esans--nx?olf?p-sdnil--nx?s-ladrl--nx?tih?v-rvsyt--nx??s&a&ns?ons??i&ar?er&dron?r&os?øs???ár??la&g?h??mor!t??sir?uf?åns??t&koulo&nka?ŋká??la?p-raddjb--nx?r-agrjnu--nx?s&aefr&ammah?ámmáh??orf?r&o?ø???u-vreiks--nx??u&h-dnusel--nx?i-&drojfk--nx?vleslm--nx??j-ekerom--nx?k-rekrem--nx?u-&dnalr--nx?goksr--nx?sensk--nx??v-nekyr--nx?w-&k&abrd--nx?ivjg--nx??oryso--nx??y-y&dnas--nx?mrak--nx?n&art--nx?nif--nx??reva--nx??z-smort--nx??v!.sg?ledatskork?reiks??wh-antouvn--nx?x&9-dlofts--nx.aoq-relv--nx?d-nmaherk--nx?f-dnalnks--nx?h-neltloh--nx?i-drgeppo--nx?j-gve&gnal--nx?lreb--nx??m-negnilr--nx?n-drojfvk--nx??y&7-ujdaehal--nx?8-antouvig--nx?b-&dlofrs--nx?goksmr--nx?kivryr--nx?retslj--nx??e-nejsom--nx?f-y&krajb--nx?re&dni--nx?tso--nx??stivk--nx??g-regark--nx?orf?ørf??z9-drojfstb--nx??b&25-akiivagael--nx?53ay7-olousech--nx?a&iy-gv--nx?le-tl&b--nx?s--nx??n0-ydr--nx??c&0-dnal-erdns--nx?z-netot-erts--nx??g&g-regnarav-rs--nx?o-nejssendnas--nx??ju-erdils-ertsy--nx?nj-dnalh-goksrua--nx?q&q-ladsmor-go-erm--nx.&ari-yreh--nx?ednas??s-neslahsladrjts--nx???ca&4s-atsaefrmmh--nx?8m-dnusynnrb--nx?il-tl--nx?le-slg--nx?n5-rdib--nx?op-drgl--nx?uw-ynnrb--nx??d&a&qx-tggrv--nx?reh!nnivk?sd&ork?ørk??uas??ts&e&bi?kkar?llyh?nnan??g&ort?ørt??k&alf?irderf??levev?mirg?obeg&ah?æh??r&ah?ejg????barm-jdddb--nx?ie!rah?s&etivk?ladman???lof&r&os?øs??ts&ev.ednas?o.relav?ø.relåv???n&a&l&-erd&n&os?øs??ron??adroh.so?dron.&a&g5-b--nx?ri-yreh--nx??ob?y&oreh?øreh??øb??e&m!lejh??pr&oj?øj??vi??gyb?n&aks?åks??o&h-goksrua?rf??r&o?ua?ø??tros?øh-goksrua??rts!e&devt?lab?mloh???s&ellil?naitsirk?rof???u&l!os??s!d&im?lejt??e&guah?l&a?å???kkoh?lavk?naitsirk?r&af?eg&e?ie???tef?y&onnorb?ønnørb?????r&a&blavs!.sg??g&eppo?la???o&j&f&a!dniv?k?vk??die?e&dnas?kkelf??llins?r&iel?ots??s&lab?t&ab?åb??yt??å!k??ævk??les??ts??åg&eppo?lå???ureksub.sen??e&ayb-yrettn--nx?d&ar?isemmejh321,lom?r&of?øf??år??g&gyr?nats??i&meuv&ejsem&aan?åån??sekaal??rjea??j&d&ef?oks??les??k&er&aom?åom??hgna&ark?årk??iregnir?kot!s??s&ig?uaf???l&bmab?kyb?l&av?ehtats??oh??m&it?ojt?øjt??n&arg?g&os?øs??meh?reil?te?ummok?yrb??r&dils-erts&ev?y&o?ø???ua?vod??sa&ans?åns??t&robraa?spaav??urg??f&62ats-ugsrop--nx?a&10-ujvrekkhr--nx?7k-tajjrv-attm--nx??o!.sg?h??s!.sg??v!.sg???g&5aly-yr&n--nx?v--nx??a&llor?ve&gnal?lreb???n&av!snellu??org??oks&die?m&or?ør??ner&ol?øl??r&o?ø???r&eb!adnar?edyps?s&die?elf?gnok?n&ot?øt????obspras??uahatsla?åve&gnal?lreb???h&0alu-ysm--nx?7&4ay8-akiivagg--nx?5ay7-atkoulok--nx??a!.sg???i&e&hsr&agev?ågev??rf??k&h&avlaraeb?ávlaraeb??s??lm&a?å??mpouvtal&am?ám??pph&al?ál??rrounaddleid?ssaneve?ššáneve??j&0aoq-ysgv--nx?94bawh-akhojrk--nx??k&a&b&ord?ørd??jks?lleis??iv!aklejps?l&am?evs?u??mag?nel?ojg?r&a&l?n??epok?iel?y&or?ør???s&ah?kel?om??øjg??kabene?ojsarak?ram&deh.&aoq-relv--nx?rel&av?åv??so??e&let.&ag5-b--nx?ob?øb??ra???åjks??l&a!d&anrus?d&numurb?ron??e&gnard?nte?s&meh?sin??ttin??g&is?nyl??kro?l&em?l&ejfttah?of??u&ag-ertdim?s???n&am?era?gos?i&b?nroh?r??kos?nus?oj??o-&dron?r&os?øs???ppo?r&a!l?nram??e&gne?l?v??is?o&jts?ts??u&a-&dron?r&os?øs???h??å?æl?øjts??s&e&jg?nivk?ryf??kav?mor-go-er&om.&ednas?yoreh??øm.&ednas?yøreh???uag??t&las?rajh?suan??v&l&a?e-rots??u-go-eron??yt??ksedlig?res&a?å???bib&eklof?seklyf??es!dah??h!.sg??i&m?syrt??l&ejf?ov&etsua?gnit?ksa?sdie???n!.sg??o!.sg?boh?g?h??r!.sg??å!ksedlig??øboh??m&a&rah?vk??f!.sg??h!.sg??i&e&h&dnort?rtsua?ssej??rkrejb??ksa??ol?t!.sg??u&dom?esum?r&ab?drejg?evle?os?uh?æb?øs??ttals???n&a&g&av?okssman?åv??jlis?or?r&g?rev???e&d&do&sen?ton??lah?r&agy&o?ø??ojfsam???g&iets?n&a&l&as?lab??n&avk?ævk??t&arg?ddosen??v&al?essov???i&d&ol?øl??l&ar?ær???yl??reb??iks?k&srot?y&or?ør???l&a&d&gnos?n&er?ojm?øjm??om??tloh??ug?åtloh??mmard?ojs&om?sendnas??ppolg?s&lahsladr&ojts?øjts??o??t&o&l?t-erts&ev?o?ø???roh?øl??vly&kkys?nav??yam-naj!.sg??øjs&om?sendnas???g&orf?ujb??i&dnaort?vnarg??kob?ladendua?maherk&a?å??n&it?urgsrop??orf-&dron?r&os?øs???r&aieb?evats??sfev?uaks?yrts??o&6axi-ygvtsev--nx?c,d&ob?rav??ievs?kssouf?l&m&ob?øb??ous&adna?ech&ac?áč???so!.sg???msdeks?niekotuak?r&egark?olf?y&oso?øso???s&dav?mort???p&ed?ohsdaerpsym,p&akdron?elk???r&a&d&dj&ab?áb??iab??jtif?luag?mah?vsyt??",
+ "e&gn&a&k&iel?ro??merb?n&at?mas??rav-r&os?øs??srop?talf?v&ats?el??y&oh?øh???ivsgnok??il?jkniets?k&a&nvej?rem?s&gnir?nellu???ie-er&den?v&o?ø???ram?sa?årem??la&jf?vh??m&b&ah?áh??mahellil??nnul?ts&l&oj?øj??ul??y&o?ø???imp&ah?áh??m!.sg??osir?t!.sg??ádiáb?ævsyt?øsir??s&adnil?en&dnas?e&dga?k&ri&b?k??som??ve??me&h?jg??nroh-go-ejve?s&a?ednil?k&o?ø??of?yt?å??tsev??gv?hf?igaval?o&r&or?ør??sman??so&fen&oh?øh??m?v??uh&lem?sreka.sen??å!dnil???t&a&baol?g&aov?grav??jjr&av-attam?áv-attám??l&a&b?s??ás??soum?ts?v&eib?our???e&dnaly&oh?øh??f?s&nyt?rokomsdeks?sen??vtpiks??in&aks?áks??loh&ar?år??n!.sg??o&m&a?å??psgolb,?s!.sg?efremmah?or?ør??terdi?á&baol?ggráv?lá&b?s??soum?veib???u&b!.sg?alk?e&dna?gnir?nner??les?ælk??dra&b?eb??g&nasrop?vi?ŋásrop??j&daehal&a?á??jedub?v&arekkhar?árekkhár???ksiouf?n&diaegadvoug?taed???v&irp?lesl&am?åm???y&b&essen?nart?sebel?tsev??o&d&ar?na!s??or??gavtsev?k&rajb?sa??lem?mrak?n&art?n&if?orb???r&a&mah?n?v??e&dni?t&so?ton??va??ul?yd??s&am?enner?gav?lrak?tivk??vrejks??ø&d&ar?na!s??ør??gåvtsev?k&rajb?sa??lem?mrak?n&art?n&if?ørb???r&e&dni?t&so?tøn??va??ul?yd?æ&n?v???s&enner?gåv?tivk?åm??vrejks???á&slág?tlá?vreiks??å&gåv?h?jddådåb?lf??ø&d&ob?rav??r&egark?olf??s&dav?mort????aki?i&sac?tal??u??o&b?f?g?hay?o?ttat??r!.&cer?erots?gro?m&o&c?n??rif?t??o&c,fni??pohs,stra?t&n?opsgolb,?www?ysrab,?e&a!.&a&ac?cgd?idem??bulc!orea??ci&ffartria?taborea??e&cn&a&l&lievrus-ria?ubma??netniam?rusni??erefnoc??gnahcxe?mordorea?ni&gne?lria?zagam??rawtfos??gni&d&art?ilg!arap?gnah???l&dnahdnuorg?ledom??noollab?retac?sael?t&lusnoc?uhcarap??vidyks??hcraeser?l&anruoj?euf?icnuoc?ortnoc!-ciffart-ria???n&gised?oi&nu?t&a&cifitrec?ercer?gi&tsevni-tnedicca?van??i&cossa!-regnessap??valivic??redef??cudorp?neverp-tnedicca????ograc?p&ihsnoipmahc?uorg!gnikrow???r&e&dart?enigne?korb?niart?trahc??o&htua?tacude???s&citsigol?e&civres?r??krow?serp!xe??tnega??t&farcr&ia?otor??hgil&f?orcim??liubemoh?n&atlusnoc?e&duts?m&esuma?n&iatretne?revog??piuqe????olip?ropria?si&lanruoj?tneics???w&erc?ohs??y&cnegreme?dobper?tefas????rref?z??p!.&a&aa?ca?pc??dem?ecartsnd.icb,gne?r&ab?uj??snduolc,t&acova?cca?hcer??wal?ysrab,???s!.&em?gro?hcs,moc?ten?ude?vog???t!.&0x,116,ayo,gro?lim?moc?nayn,sulpnpv,t&cennockciuq.tcerid,en??ude?v&dr,og???o&hp?m?v?yk??tol?ua??v&iv?lov??xas?ykot??p&a&ehc?g?m?s??eej?g!.&gro?ibom?moc?ossa?ppa,ten?ude???i&r!.nalc,?v?z??j!.&0o0o,a&3&5xq6f--nx?xqi0ostn--nx??5wtb6--nx?85uwuu--nx?9xtlk--nx?ad,b&ats,ihc!.&a&bihciakoy?don?ma&him?ye&ragan?tat???r&a&bom?gan?hihci??u&agedos?kas?ustak???s&os?ufomihs??t&amihcay?iran??w&a&g&im&anah?o??omak??kihci?zustum??ihsak??y&agamak?imonihci???e&akas?nagot??i&azni?esohc?h&asa?s&abanuf?ohc???ka&to?zok??musi?orihs?r&akihabihsokoy?o&dim?tak??ukujuk??usihs??nano&hc?yk??o&d&iakustoy?ustam??hsonhot?k&a&rihs?t??iba??nihsaran?sobimanim?tas&arihsimao?imot??uhc?yihcay??u&kujno?s&ayaru?t&imik?tuf???zarasik?????c&cah,ed,?g&as!.&a&gas?m&a&tamah?yik??ihsak??rat?t&a&gatik?hatik??ira!ihsin????e&kaira?nimimak??i&akneg?g&aruyk?o??h&c&amo?uo??siorihs??kaznak?modukuf?ra&gonihsoy?mi???nezih?u&k&at?ohuok??s&ot?tarak?????ihs!.&a&kok?m&a&hagan?yirom??ihsakat??rabiam?wagoton??e&miharot?nokih??houyr?i&azaihsin?esok?kustakat?moihsagih??na&mihcahimo?nok??o&hsia?mag?t&asoyot?ok?tir???us&ay?t&asuk?o??????k&aso!.&a&d&awihsik?eki??k&a&noyot?s&akaayahihc?oihsagih???oadat?uziak??m&ayas!akaso??odak??r&a&bustam?wihsak??ediijuf??t&akarih?i&k?us???wag&ayen?odoyihsagih???e&son?tawanojihs??honim?i&akas?h&cugirom?s&ayabadnot?i&a&kat?t??n??oyimusihsagih???k&a&rabi?sim??ustakat??muzi?r&ijat?otamuk???nan&ak?n&ah?es???o&ay?n&a&ganihcawak?simuzi?tak??eba?ikibah?oyot??t&anim?iad?omamihs??uhc??ust&oimuzi?tes????ou&kuf!.&a&d&amay?eos??g&no?ok?usak??hiku?k&awayim?uzii??ma&kan?y&asih?im???rawak?t&a&gon?ka&h?num?t???umo??wa&g&a&kan?nay?t??ias??ko!rih???y&ihsa?usak???e&m&ay?uruk??taruk?us??i&a&nohs?raihcat??goruk?h&cukuf?s&a&gih?hukuy??in???k&a&gako?muzim??iust?o?ustani??m&anim?otihsoynihs?u??r&ogo?ugasas??usu??ne&siek?zu&b?kihc???o&gukihc?h&ak?ot?ukihc??j&ono?ukihc??kayim?nihsukihc?to?uhc??u&fiazad?gnihs?stoyot????zihs!.&a&bmetog?d&amihs?eijuf?ihsoy?omihs??kouzihs?mihsim?ra&biah?honikam??tawi?wa&g&ekak?ukik??kijuf??yimonijuf??i&a&ra?sok??hcamirom?juf?kaz&eamo?ustam??ma&nnak?ta??nukonuzi?orukuf??nohenawak?o&nosus?ti??u&stamamah?z&a&mun?wak??i!ay?i&hs&agih?in??manim??mihs????????m&a&tias!.&a&d&ihsoy?ot?usah??k&a&dih?sa??o&arihs?s???m&a&tias?y&as?o&rom?tah??ustamihsagih???i&hsagurust?jawak??uri??ni?wa&g&e&ko?man??ikot?o??k&ara?i&hsoy?mak???ru?zorokot??y&a&g&amuk?ihsok?otah??kuf??imo??ziin??e&bakusak?ogawak?sogo?ttas?zokoy??i&baraw?h&cugawak?s&oyim?ubustam???iroy?k&ato?ihs?u&k?stawi???m&akoyr?i&hsoy?juf??uziimak???naznar?o&dakas?ihsay?jnoh?n&a&go?nim??imijuf?nah?oy??r&ihsayim?otagan??t&asim!ak??igus?omatik??zak??u&bihcihc!ihsagih??sonuok?ynah????y&ak&aw!.&a&d&ira?notimak??kadih?ma&h&arihs?im??y&a&kaw?tik??oduk???ru&ustakihcan?y??sauy?wa&g&a&dira?zok??orih??konik??yok?zok??e&banat?dawi??i&garustak?jiat?mani??naniak?o&bog?nimik?t&asim?omihs&ah?uk????ugnihs???o!.&a&jos?koasak?m&ay&ako?ust??ihsayah??r&abi?ukawaihsin??wi&aka?nam???e&gakay?kaw??i&gan?h&cu&kasa?otes??sahakat??k&asim?ihsaruk??miin??n&anemuk?ezib??o&hsotas?jnihs?n&amat?imagak??ohs?uhcibik?????ot!.&a&damay?got?koakat?may&etat?ot??nahoj?riat?waki&inakan?reman???eb&ayo?oruk??i&h&asa?ciimak?sahanuf??kuzanu?m&an&i?ot??ih???nezuyn?otnan?u&hcuf?stimukuf?z&imi?ou???????ihs&o&gak!.&a&m&ayuok?ihsogak??si?yonak??e&banawak?n&at&akan?imanim??uka??tomoonihsin??i&adnesamustas?k&azarukam?oih??m&ama?uzi??usuy??nesi?o&knik?os?tomustam??uzimurat???rih!.&a&ka&n?s??m&ayukuf?i&hsorihihsagih?j&ate?imakikaso????r&a&bohs?h&ekat?im???es??tiak?wiad??e&kato?ruk??i&h&ci&akustah?mono?nihs??s&inares?oyim???manimasa?uk??negokikesnij?o&gnoh?namuk??uhcuf????uk&ot!.&a&bihci?mi&hsu&kot?stamok??m??wagakan??egihsustam?i&gum?h&coganas?soyim??kijaw?m&anim?uzia??ukihsihs??nan&a?iak??o&nati?turan????uf!.&a&batuf?m&a&to?y&enak?irok???ihs&im?ukuf??os?uko??r&aboihsatik?uganat??ta&katik?mawak?rih??w&a&g&akus?emas?uy??k&a&mat?rihs?sa??ihsi??nah??ohs???e&gnabuzia?iman?ta&d?tii???i&adnab?enet?hs&agih?iimagak??k&a&wi?zimuzi??ubay??minuk?r&ook?ustamay???nihsiat?o&g&etomo?ihsin?nan?omihs??no!duruf?rih??rihsawani?ta&may?simuzia???u&rahim?stamakawuzia?zia&ihsin?nay???????nug!.&a&bawak?doyihc?k&anna?oi&hsoy?juf?mot???m&ayakat?ustagaihsagih??n&ihsatak?nak??r&ahonagan?nak?o?u&kati?mamat???t&amun?inomihs?o??w&akubihs?iem?ohs???i&hsa&beam?yabetat??kas&akat?esi??m&akanim?uzio??ogamust?rodim??o&jonakan?n&eu?oyikust??tnihs??u&komnan?stasuk?yrik????rep,?n&ibmab,nog,ob,?ppacihc,ra&n!.&a&bihsak?d&akatotamay?u!o???guraki?m&ay&atik&imak?omihs??irokotamay??oki??ra&hihsak?n??wa&geson?knet???e&kayim?ozamay?sog?ustim??i&a&rukas?wak??garustak?h&ciomihs?sinawak??jo?ka&mnak?toruk??makawak?nos?r&net?otakat?ugeh???o&d&na?oyo??gnas?jnihs?nihsoy!ihsagih??tomarawat?yrok????rikik,?t&ag&amay!.&a&dihsio?k&atarihs?ourust??may&a&kan?rum??enak?onimak??rukho?ta&ga&may?nuf??hakat?kas??wa&g&ekas?orumam??ki&hsin?m??z&anabo?enoy?ot???zuy??e&agas?bonamay?dii?nihsagih?o??i&a&gan?nohs??h&asa?sinawak??nugo??o&dnet?jnihs?ynan??ukohak???iin!.&a&ga?k&ium?oagan??munou!imanim??t&a&bihs?giin??ioy??w&a&gioti?kikes?zuy??irak??yijo??e&kustim?mabust??i&aniat?hcamakot?kaz&awihsak?omuzi??m&a&gat?karum??o???n&anust?esog??o&das?ihcot?jnas?k&ihay?oym??mak?naga?ries??u&ories?steoj?????i&k&a!.&a&go?k&asok?oimak??t&ago!rihcah??ika!atik???w&aki?oyk???e&mojog?natim?suranihsagih?t&ado?okoy???i&hsoyirom?magatak?naokimak??nesiad?o&hakin?jnoh!iruy??nuzak?rihson?tasi&juf?m??yjnoh??u&kobmes?oppah????in,?o!.&a&dakatognub?m&asah?ihsemih??su?t&ekat?i&h?o????e&onokok?ustimak??i&jih?k&asinuk?ias?usu??mukust??onoognub?u&fuy?juk?ppeb?suk?????nayn,?wa&ga&k!.&a&mihsoan?rihotok?waga&kihsagih?ya???emaguram?i&j&nonak?ustnez??kunas?monihcu??o&hsonot?nnam?yotim??u&st&amakat?odat??zatu????nak!.&a&dustam?kus&okoy?tarih??maz?nibe?r&a&gihsaimanim?h&esi?imagas??wa&do?guy???u&im?kamak???tikamay?wa&k&ia?oyik?umas??sijuf??yimonin??e&nokah?saya??i&akan?esiak?gusta?hsuz?kasagihc?o?ukust??o&nadah?sio?tamay?????kihsi!.&a&danihcu?gak?kihs?mijaw?t&abust?ikawak??wazanak??i&gurust?hcionon?mon?ukah??nasukah?o&anan?ton!akan???u&kohak?stamok?z&imana?us?????niko!.&a&han?m&arat?ijemuk?uru??n&e&dak?zi??no??ra&hihsin?rih??wa&kihsi?niko??yehi?zonig??e&osaru?seay??i&hsagih?jomihs?k&a&gihsi?not??ihsakot??m&a&ginuk?kihsug?maz??igo?otekat??nuga!noy???n&a&moti?timoy?wonig??i&jikan?k???o&gan?jnan?tiad&atik?imanim???u&botom?kusug&akan!atik??imot??rab&anoy?eah??????yp,zomim,?bus,c&204ugv--nx?462a0t7--nx?678z7vq5d--nx?94ptr5--nx?a?mpopilol,?d&-2,17sql1--nx?3thr--nx?5&20xbz--nx?40sj5--nx??7&87tlk--nx?ptlk--nx??861ti4--nx?a?e!tfarcdnah,?n&eirf&lrig,yob,?om,?ooftac,?e&16thr--nx?5&1a4m2--nx?9ny7k--nx??damydaer,eweep,garotsarukas.&10ksi.3s,20ksi.3s,?i&bmoz,m!.&a&bot?k&asustam?uzus??m&a&him?y&emak?im???ihs??nawuk?wi&em?k???e&bani?ogawak?si!imanim???i&arataw?gusim?h&asa?ciakkoy??k&a&mat?sosik?t??iat??raban??o&dat?hik?n&amuk?ihseru?o&du?mok????ust????kilbew,lasrepus,mihe!.&a&m&a&h&ataway?iin??yustam??ij&awu?imak???taki!man???ebot?i&anoh?kasam?rabami??n&ania?egokamuk?oot??o&jias?kihcu?nustam?uhcukokihs?yi!es???u&kohik?zo????n!.&arukas,lapo,n&erukom,riheg,?omomus,stnim,teniesa.resu,xob-liam,yrovi,zapot,?amihs!.&a&d&amah?ho?usam??kustay?m&a?ihsoni&hsin?ko???wakih??e&namihs?ustam??i&g&aka?usay??konikak?mikih??nannu?o&mu&kay?zi!ihsagih?uko???nawust?tasim??u&stog?yamat????nep,?rotsnoihsaf,srev,t&awi!.&a&bahay?d&amay?on??koirom?t&a&honat?katnezukir??imus??w&as&ijuf?uzim??ihs???e&hon&i&hci?n??uk??tawi??i&a&duf?murak?wak??h&custo?si&amak?ukuzihs???j&oboj?uk??k&a&m&anah?uzuk??sagenak??esonihci??m&akatik?uzia&rih?wi????o&kayim?no&rih?t??tanufo??uhso???isarap,saman,tococ,?ulbybab,?g&3zsiu--nx?71qstn--nx?l?olblooc,?h&03pv23--nx?13ynr--nx?22tsiu--nx?61qqle--nx?o-hu,sulb,?i&54urkm--nx?azosbew,ced,g&ayim!.&a&dukak?m&a&goihs?kihs??ihsustam!ihsagih??unawi??r&awago?iho??ta&bihs?rum??w&a&gano?kuruf??iat??y&imot?ukaw???e&mot?nimes??i&hsiorihs?ka&monihsi?s&awak?o???mak?r&ataw?o&muram?tan????o&az?jagat?t&asim?",
+ "omamay???u&fir?k&irnasimanim?uhsakihcihs?????ihcot!.&a&g&a&h?kihsa??ust??kom?m&ay&o?usarak??unak??r&a&boihsusan?watho??iho?ukas??t&akihsin?iay??wa&konimak?zenakat??y&imonustu?oihs???e&iiju?kustomihs?nufawi??i&akihci?g&etom?ihcot?on???o&k&ihsam?kin??nas?sioruk?tab??u&bim?san?????h&c&ia!.&a&dnah?m&a!h&akat?im??yuni??ihs&ibot?ust???r&a&hat?tihs??ik?u&ihsagih?kawi???t&ihc?o&k?yot???wa&koyot?zani??yi&monihci?rak???e&inak?k&aoyot?usa??manokot?noyot??i&a&gusak?kot?sia??eot?h&asairawo?cugo?s&ahoyot?oyim???k&a&mok?zako??ihssi??motay?rogamag??n&an&ikeh?ok??ihssin??o&got?ihsin?jna?rihsnihs?suf?tes??u&bo?raho?s&oyik?takihs??yrihc?zah????ok!.&a&dusay?kadih?mayotom?r&ah&im?usuy??umakan??sot!ihsin??wa&g&atik?odoyin??k&as?o????i&esieg?hco!k??jamu?k&a!sus??usto??ma&gak?k??rahan??o&mukus?n&i?ust!ihsagih???torum?yot!o???u&koknan?zimihsasot????ugamay!.&a&m&ayukot?ihso??toyot??e&bu?subat??i&gah?kesonomihs?nukawi?rakih??nanuhs?otagan?u&ba?foh?otim?stamaduk?uy?????s&anamay!.&a&dihsoyijuf?mayabat?r&ahoneu?ustakihsin??w&a&k&ayah?ijuf??suran??ohs???egusok?i&ak?h&cimakan?s&anamay?od???k&asarin?u&feuf?sto????o&k&akanamay?ihcugawakijuf??nihso?t&asimawakihci?ukoh??uhc??spla-imanim?u&b&nan?onim??fok?hsok?rust????ubon,??ix,ka&rabi!.&a&bukust?gok?kan!ihcatih??m&a&sak?timo?wi??ihsak?ustomihs??ni?r&a&hihcu?way??u&agimusak?ihcust???t&ag&amay?eman??oihcatih??w&ag&arukas?o??os??yi&moihcatih?rom???e&bomot?dirot?not?tadomihs??i&a&k&as?ot??rao??esukihc?gahakat?h&asa?catih??k&a&rabi?saguyr??ihsani?uy??ma?rukustamat??o&dnab?giad?him?kati?rihsijuf?soj?t&asorihs?im??yihcay??u&fius?kihsu?simak????sagan!.&a&m&abo?ihsust??natawak?r&abamihs?u&mo?ustam???wijihc?yahasi??i&akias?hies?k&asagan?i??masah??neznu?o&besas?darih?t&eso?og!imaknihs????ust&igot?onihcuk?uf????zayim!.&a&biihs?guyh?k&oebon?ustorom??mihsuk?r&emihsin?uatik??ta&katik?mim??wag&atik?odak??ya??e&banakat?sakog??i&hsayabok?kaza&kat?yim??m&animawak?ot&inuk?nihs????nanihcin?o&j&ik?onokayim??n&ibe?ust??tias??urahakat????ro&cep,moa!.&a&dawot?turust?wasim??e&hon&ihc&ah?ihs??nas?og?ukor??sario??i&anarih?ganayati?hsioruk?jehon?kasorih?makihsah?nawo?r&amodakan?omoa???o&gnihs?kkat??u&ragust?stum????ttot!.&a&r&ahawak?uotok??sa&kaw?sim???egok?irottot?nanihcin?o&ganoy?nih?tanimiakas??u&bnan?z&ay?ihc??????ukuf!.&a&deki?gurust?ma&bo?h&akat?im??yustak??sakaw??eabas?i&akas?ho?jiehie?ukuf??nezihce!imanim??ono????k&26rtl8--nx?4&3qtr5--nx?ytjd--nx??522tin--nx?797ti4--nx?ci&gid,ht,sevol,?ee,limybab,n&at,upatilol,??l&33ussp--nx?e&ccabew.&resu,sr,?llarap,?lik,oof,rigetuc,?m&11tqqq--nx?41s3c--nx?ef,sioge,?n&30sql1--nx?65zqhe--nx?a&ebyllej,i&lognom,viv,??iam,n7p7qrt0--nx?o&o&las,mflah,?ruk,staw,??o&131rot--nx?7qrbk--nx?aic,c?d&iakkoh!.&a&deki?gakihset?hcebihs?k&adih?u&fib?narihs???m&ayiruk?hot?ihs&orihatik?ukuf??oras?usta??r&ib&a!ka??o?uruf??ozo?u&gakihsagih?oyot???sakim?ta&gikust?mun??w&a&ga&k&an?uf??nus!imak???k&aru?i&h&asa?sagih??kat?mak??omihs?um??zimawi??ine?oyk??yot??e&a&mustam?nan??b&a&kihs?yak??o&noroh?to???ian?k&ihsam?ufoto??nakami?ppoko!ihsin??sotihc?tad!okah??uonikat??i&a&bib?mokamot?n&a&k&kaw?oroh??wi??eomak?ihsatu?okik?usta&moruk?sakan????eib?h&c&ioy?u&bmek?irihs???s&ase?ekka?oknar?uesom???jufirihsir?k&amamihs?i&at?n???m&atik?otoyot??oa&kihs?rihs??r&a&hs?kihsi?mot??ihs&aba?ir??otarib???n&a&hctuk?rorum?se?tokahs??uber??o&kayot?m&ire?ukay??naruf!ima&k?nim???orih?r&ih&ibo?suk??o&bah?h&i&b?hsimak??sa??pnan?yan??umen??t&asoyik?eko?ukoh???u&bassa?kotnihs?m&assaw?uo??pp&akiin?en&ioto?nuk??ip??rato?s&akat?t&eb&e?i&a?hs!a??robon??m&e?o&m?takan???no&h?tamah??o&mik?s?t??u&kir?ppihc?st???onihsnihs?ufuras??uaru??yru!koh??zimihs!ok?????nu,?g!iti,oyh!.&a&bmat?dnas?gusak?k&at?o&oyot?y??uzarakat??m&ayasas?irah??wa&g&ani?okak??k&i&hci?mak??oy???yi&hsa?monihsin???i&asak?hs&aka?i&at?nawak???j&awa!imanim??emih??k&a&goa?s&agama?ukuf??wihsin??i&hsog?m???mati?oia?rogimak??n&annas?esnonihs??o&gasa!kat??ka?n&ikat?o?ustat??rihsay?sihs?tomus?yas??u&bay?gnihs?????hih,konip,l&bs,ik,?mol,nagan!.&a&bukah?d&a&w?yim??e&ki?u??ii??k&a&s&ay?uki??zus??ihsoo?ousay??m&ay&akat?ii??i&hsukufosik?jii??ukihc??n&i!hsetat??uzii??r&ah?ugot??saim?t&agamay?oyim??w&a&g&a&kan?n??o??kustam?ziurak??onim!imanim??u&koo?s!omihs????ya&ko?rih???e&akas?nagamok?subo??i&gakat?h&asa?c&a!mo!nanihs???uonamay??sukagot??k&a&kas?mimanim?to??ia&atik?imanim??oa?uzihcom??m&akawak?ijuf?o!t???r&ato?ijoihs?omakat???n&ana?esnoawazon??o&hukas?n&a&gan?kan??i&hc?muza??ustat??romok?si&gan?k??tomustam??u&k&as?ohukihc??stamega????o&b,m,pac,?to&mamuk!.&a&gamay?rahihsin?sukama!imak??tamanim??enufim?i&hcukik?k&ihsam?u??nugo!imanim??romakat??o&ara?rihsustay?sa?t&amay?om&amuk?us??u!koyg???yohc??u&sagan?zo????yk!.&a&bmatoyk?k&ies?oemak?uzaw??mayi&h&cukuf?sagih??muk??nihsamay?rawatiju?t&away?ik???e&ba&nat!oyk??ya??di?ni??i&ju?kazamayo?manim??natnan?o&gnatoyk?kum?mak?rihsamayimanim?y&gakan?ka&koagan?s??oj???u&ruziam?z&ayim?ik??????wtc1--nx?ykot!.&a&d&i&hcam?mus??oyihc??k&atim?ihsustak??m&a&t!uko??yarumihsa&gih?sum???i&hs&agoa?ika?o!t??uzuok??ren???r&a&honih?wasago??iadok?umah??ssuf?t&ik?o??wa&g&anihs?ode??k&ara?ihcat???y&agates?ubihs???e&amok?donih?m&o?urukihsagih??soyik??i&enagok?gani?h&ca&da?tinuk??sabati??j&nubukok?oihcah??manigus??o&huzim?jihcah?n&akan?ih!sasum??urika??rugem?t&a&mayihsagih?nim??iat?ok??uhc?yknub??u&fohc?hcuf?kujnihs?????p&a&ehc,rc,?o&hs&eht,iiawak,yub,?lf,p&evol,ydnac,?rd&kcab,niar,???r&2xro6--nx?atselttil,e&d&nu,wohc,?h,ilf,pp&ep,irts,u,?t&aerg,tib,??g!r,?ks,o!on,?ufekaf,?s&9nvfe--nx?dom,p&ihc,oo,?remagten,sikhcnerf,u&bloohcs,ruci,srev,?xvp4--nx??t&a&cyssup,obgip,?e&rces,vlev,?hginyad,netnocresu,opsgolb,sidas,u&b,ollihc,??u&4rvp8--nx?fig!.&a&d&eki?ih??kimot?m&ayakat?ihsah??ne?raha&gi&kes?makak??sak??taga&may?tik??wa&g&ibi?ustakan??karihs!ihsagih????e&katim?uawak??i&gohakas?hc&apna?uonaw??k&ago?es?ot??m&anuzim?ijat??nak?urat??nanig?o&dog?jug?makonim?nim?roy?sihcih??u&fig?s&otom?t&amasak?oay??????hc,pup,stoknot,ynup,?wonsetihw,x&5ytlk--nx?irtam,?y&adynnus,dr,knarc,l&oh,rig,?moolg,ob,pp&ih,olf,?rgn&a,uh,?u6d27srjd--nx?vaeh,?z&72thr--nx?e&ej,lur,??井福?京東?分大?取鳥?口山?城&宮?茨??媛愛?山&富?岡?歌和??岡&福?静??島&児鹿?広?徳?福??崎&宮?長??川&奈神?石?香??庫兵?形山?手岩?木栃?本熊?根島?梨山?森青?潟新?玉埼?田秋?知&愛?高??縄沖?良奈?葉千?賀&佐?滋??道海北?都京?重三?野長?阜岐?阪大?馬群???k!.&art?gro?moc?per?ude?vog???l&eh?l??m!.uj,ac?j??nd?o&g?h&pih?s!.&esab,xilpoh,ysrab,???lnud?oc?t!.&lldtn,snd-won,???pa!.&0mroftalp,a&rusah,ted,?bew:erif,,e&erf-korgn,gatskrelc,kalfwons:.kniletavirp,,niln&igol,okoob,?tupmocegde,virdhsalfno,?ilressem,k&orgn,relc,?le&crev,napysae,?maerdepyt,n&aecolatigidno,ur:.a,,?poon,r&cne,emarf,?t&i&belet,lmaerts,?xenw,?yfilten,??ra&a?hs??u&ekam?llag?org!.esruocsid,cts?kouk?nayalo???vsr?xece4ibgm--nx??q&a!3a9y--nx??g?i!.&gro?lim?moc?ten?ude?vog???m?se??r&a!.&a&cisum?sanes??bog?gro?l&autum?im??moc!.topsgolb,?pooc?rut?t&e&b?n??ni??ude?vog??4d5a4prebgm--nx?b?c?eydoog?los?t&at?s!uen???ugaj??b!.&21g?a&b&a&coros?iuc??itiruc??cnogoas?dicerapa?gniram?i&naiog?ramatnas??n&erom?irdnol??op?p&acam?irolf?ma&j?s???rief?tsivaob??b!aj?ib?mi?sb??c&ba?e&r?t??js?sp?t!e???d&em?mb?n&f?i??rt??e&dnarganipmac?ficer?ht?llivnioj?rdnaotnas??f&dj?ed?gg?n&e?i???g&e&l!.&a&b,m,p,?bp,c&a,s,?e&c,p,s,?fd,gm,ip,jr,la,ma,nr,o&g,r,t,?p&a,s,?r&p,r,?s&e,m,r,?tm,??s??l&s?z??n&c?e?o??ol!b?f?v??pp?ro??hvp?i&du?kiw?nana?oretin?r&c?eurab??sp?te?xat??l&at&an?rof??el?im?sq??m&a?da?e&gatnoc?leb??f?ic?oc!.&duolclautriv.elacs.sresu,etiselpmis,topsgolb,???nce?o&ariebir?c&e?narboir?saso??d&o?ranreboas??e&g?t??i&b?dar?ecam?r??rp?t&a?erpoir???p&er?m!e?t??ooc?pa?se??qra?r&af?ga?o&davlas?j??tn?ut??s&a&ixac?mlap?nipmac??ed?u&anam?j?m???t&am?e&d?n?v??nc?o&f?n??ra?sf??u&caug9?de?ja?rg??v&da?ed?og!.&a&b?m?p??bp?c&a?s??e&c?p?s??fd?gm?ip?jr?la?ma?nr?o&g?r?t??p&a?s??r&p?r??s&e?m?r??tm???rs?t??xiv?z&hb?ls?o&c?f?????c!.&as?ca?de?if?o&c?g??ro???e&bew?ccos?dnik?e&b?n&igne?oip??rac??gni&arg?rheob??h&cor?sok?t&aew?orb???itnorf?k&col?o&p?rb???l&aed?ffeahcs??mal?nes?pinuj?t&a&eht?rebsnegömrev??law?nec?s&acnal?nom?ubkcolb??upmoc??v&o&csid?rdnal??resbo??wulksretlow?ywal?zifp??f!.&aterg?bew&-no,etis321,?drp?e&c&itsuj-reissiuh?narf-ne-setsitned-sneigrurihc,?lipuog,rianiretev??hny,i&cc?rgabmahc??m&o&c?n??t??n&eicamrahp?icedem??ossa?pohsdaerpsym,s&e&lbatpmoc-strepxe?riaton?tsitned-sneigrurihc?uova??o&-x&bf,obeerf,?x&bf,obeerf,???t&acova?o&or-ne,psgolb,?r&epxe-ertemoeg?op!orea????vuog?xobided,?avc7ylqbgm--nx?s??g!.&etiselpmis,gro?moc?t&en?opsgolb,?ude?vog???h!.&e&erf,man??mo&c?rf??topsgolb,zi??ur??i!.&a&61f4a3abgm--nx?rf4a3abgm--nx??ca?di?gro?hcs?oc?ten?vog?نار&يا?یا???a&h?per??ew?lf??k!.&c&a?s??e&n?p?r??gk?iggnoeyg?kub&gn&oeyg?uhc??noej??l&im?uoes??man&gn&oeyg?uhc??noej??n&as&lu?ub??o&e&hcni?jead??wgnag???o&c?g??ro?s&e?h?m??topsgolb,u&gead?j&ej?gnawg????cilf??l!.&gro?moc?ten?ude?vog???m!.&topsgolb,vog???n!.&gro?moc?ofni?ten?ude?vog?zib???o&htua?odtnorf?t&c&a?od??laer???p!.&alsi?ca?eman?forp?gro?moc?o&fni?rp??t&en?se??ude?vog?zib???s?t!.&21k?bew?cn!.vog??eman?gro?kst?l&e&b?t??im?op??moc!.topsgolb,?neg?ofni?pek?rd?sbb?ten?ude?v&a?og?t??zib??f?m??ubad?vd??s&8sqif--nx?9zqif--nx?a!.vog?birappnb?gev?lliv?mtsirhc?s??b!.&ew,gro?moc?ten?ude?vog??c?oj?s?u??c&i&hparg?p?t&sigolyrrek?ylana???od??d&a?d?ik?l?n&iwriaf?omaid??oogemoh?rac??e!.&b&ewim321,og??gro?mo&c!.topsgolb,?n??pohsdaerpsym,ude??civres!.enilnigol,?d&d2bgm--nx?oc??h&ctaw?guh??i&lppus?rtsudni?treporp!yrrek???jaiv?l&aw?cycrotom?gnis?pats??m&ag?oh?reh??nut?ohs?picer?r&it?ut&cip!.7331,?nev???s&i&rpretne?urc??ruoc??taicossa?vig??g!nidloh??h5c822qif--nx?i!.&ekacpuc,gro?moc?t&en?ni?opsgolb,?ude?vog??a09--nx?nnet?rap?targ??k&c&or!.&ecapsbew,snddym,ytic-amil,??us??hxda08--nx?row??l!.&c&a?s??ed,gro?o&c?fni??ten?ude?vog?zib??a&ed?tner??e&ssurb?toh!yrrek???lahsram?m?oot??m!.&bal,etisinim,gro?moc?ten?ude?vog??b?etsys!.tniopthgink,?ialc??n&a&f?gorf?ol??i&a&grab?mod??giro??o&it&acav?cudorp?ulos??puoc???o&dnoc?geuj?ppaz?t&ohp!.remarf,?ua???p!.&ces?gro?moc?olp?ten?ude?vog??i&hsralohcs?lihp?t??u??r!.&au,ca?gro?ni?oc?topsgolb,ude?vog?xo,yldnerb.pohs,?a&c?p?tiug??c?e&dliub!.etisduolc,?erac?gor?levart?mraf?n&niw?trap??wolf??ot&cartnoc?omatat??pj?uot??s!.&em?gro?hcs?moc?ten?ude?vog?zib??alg?e&n&isub",
+ "!.oc,?tif??rp!xe!nacirema???xnal??iws??t&a&e&b?ytic??ob??ek&cit?ram??fig?h&cay?gilf??n&atnuocca?e&mt&rapa?sevni??ve!.&nibook,oc,????rap??u!.&a&c!.&21k?bil?cc???g!.&21k?bil?cc???i!.&21k?bil?cc???l!.&21k?bil?cc???m!.&21k!.&hcorap?rthc?tvp???bil?cc???p!.&21k?bil?cc???si?v!.&21k?bil?cc???w!.&21k?bil?cc????c&d!.&21k?bil?cc???n!.&21k?bil?cc???s!.&21k?bil?cc????d&e&f?lacsne.xhp,?i!.&21k?bil?cc???m!.&21k?bil?cc???n!.&bil?cc???s!.&bil?cc???u&olcrim,rd,??e&d!.&21k?bil,cc???las-4-&dnal,ffuts,?m!.&21k?bil?cc???n!.&21k?bil?cc????h&n!.&21k?bil?cc???o!.&21k?bil?cc????i&h!.&bil?cc???m!.&21k?bil?c&c?et??goc?n&eg?otae??robra-nna?sum?tsd?wanethsaw???nd?r!.&bil?cc???v!.&21k?bil?cc???w!.&21k?bil?cc????jn!.&21k?bil?cc???k&a!.&21k?bil?cc???o!.&21k?bil?cc????l&a!.&21k?bil?cc???f!.&21k?bil?cc???i!.&21k?bil?cc????mn!.&21k?bil?cc???n&afflog,i!.&21k?bil?cc???m!.&21k?bil?cc???sn?t!.&21k?bil?cc????o&c!.&21k?bil?cc???m!.&21k?bil?cc???ttniop,?p&ion,rettalp,?r&a!.&21k?bil?cc???o!.&21k?bil?cc???p!.&21k?bil?cc????s&a!.&21k?bil?cc???dik?k!.&21k?bil?cc???m!.&21k?bil?cc???nd&deerf,uolc,??t&c!.&21k?bil?cc???m!.&21k?bil?cc???u!.&21k?bil?cc???v!.&21k?bil?cc????ug!.&21k?bil?cc???v&n!.&21k?bil?cc???w!.cc???x&ohparg,t!.&21k?bil?cc????y&b-si,k!.&21k?bil?cc???n!.&21k?bil?cc???w!.&21k?bil?cc????za!.&21k?bil?cc????ah!uab??bria?col?e!.ytrap.resu,?ineserf?lp?xe&l?n???vt?w!.&66duolc,gro?moc?s&ndnyd,tepym,?ten?ude?vog??a?e&iver?n!.elbaeciton,??odniw??y&alcrab?ot???t&0srzc--nx?a!.&amil4,ca!.hts??etiesbew321,gni&liamerutuf,tsoherutuf,?o&c!.topsgolb,?fni,?p&h21,ohsdaerpsym,?r&euefknuf.neiw,o??v&g?irp,?xi2,ytic-amil,zib,?c?e!s??hc?l!asite??mami?rcomed??b!.&gro?moc?ten?ude?vog??b?gl??c&atnoc?e&les?rid!txen????dimhcs?e!.&eman?gro?moc?ofni?ten?ude?vog?zib??b?em?grat?id?k&circ?ram??n!.&0rab,1rab,2rab,5inu,6vnyd,7&7ndc.r,erauqs,?a&l&-morf,moob,?minifed,remacytirucesym,tadsyawla,z,?b&boi,g,lyltsaf:.pam,,?c&i&nagro-gnitae,tats-oieboda,?paidemym,?d&e&calpb,ziamaka,?hiamaka,irgevissam.saap.&1-&gs,nol,rf,yn,?2-&nol,yn,??nab-eht-ni,uolc&meaeboda,nievas.c&di-etsedron,itsalej,?xednay:.e&garots,tisbew,?,??e&c&narusnihtlaehezitavirp,rofelacs.j,?gd&eiamaka,irbtib,?ht-no-eciffo,l&acs&liat.ateb,noom,?ibom-eruza,?m&ecnuob,itnuroieboda,ohtanyd,tcerider,?n&ilno-evreser,ozdop,?rehurht,s:abapus,,ti&s-repparcs,usegde,?zam&aym,kcar,??f&aeletis,crs.&cos,resu,?ehc-a-si,?g&ni&gats-&d&eziamaka,hiamaka,?e&gdeiamaka,tiusegde,?iamaka,nigiroiamaka,yekegde,?reesnes,sirkcilc,tsohnnylf,?olbevres,?iamaka,k&catsvano,eeg-a&-si,si,?u,?l&acolottad,iamwt,meteh,s&d-ni,s-77ndc,??m&ac&asac,ih,?urofniem,?n&a&f&agp,lhn,?i&bed,llerk,??dcduabkcalb,i:giroiamaka,,pv-ni,?o&c-morf,duppa,jodsnd,rp-ytinummoc,ttadym,?p&i&-&etsef,on,?emoh,fles,nwo,?j,mac-dnab-ta,o&-oidar-mah,h&bew,sdaerpsym,??pa&duolc,egde,?tfe&moh,vres,?usnd,?r&e&tsulcyduolc,vres-xnk,?vdslennahc:.u,,?s&a&ila&nyd,snd,?nymsd,?bbevres,dylimaf,e&gde-ndc,rauqs,suohsyub,t&isbeweruza,ys,??k&catstsaf,ekokohcs,?n&d&-won,aka,d,golb,npv,?oitcnufduolc,?ppacitatseruza:.&1,2:suts&ae,ew,?,3,aisatsae,eporuetsew,sulartnec,?,s&a-skcik,ecca&-citats,duolc,??t,?t&adies,ce&ffeym,jorprot:.segap,,lespohs,?e&nretnifodne,smem,?farcenimevres,i-&ekorb,s&eod,lles,teg,??n&essidym,orfduolc,?r0p3l3t,s&ixetnod,oh&-spv:.citsalej.&cir,lta,sjn,?,gnik,???u&h,nyd,r:eakust.citsalej,,?ved-naissalta.dorp.ndc,x&inuemoh,spym,tsale.&1ots-slj,2ots-slj,3ots-slj,?unilemoh,?y&awetag-llawerif,ekegde,ffijduolc:.&ed-1arf,su-1tsew,?,ltsaf.&dorp.&a,labolg,?lss.&a,b,labolg,?pam,slteerf,?n&-morf,ofipi,?srab,?z&a-morf,tirfym,???p?tcip?v??f&ig?osorcim??g!.&bog?dni?ed,g&olb,ro??lim?moc?ot,ten?ude???h!.&dem?gro?l&er?op??m&oc?rif??o&fni?rp?s&rep?sa???po&hs?oc??t&en?luda?ra??ude?vuog???i!.&a&2n-loritds--nx?7e-etsoaellav--nx?8&c-aneseclrof--nx?i-lrofanesec--nx??at?b?c!cul??dv?i&blo&-oipmet?oipmet??cserb?drabmol?g&gof?urep??l&gup?i&cis?me&-oigger?oigger???uig&-&aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf???aizenev&-iluirf?iluirf??ev&-iluirf?iluirf??v&-iluirf?iluirf????n&a&brev?cul?pmac?tac??idras?obrac&-saiselgi?saiselgi??resi??otsip?r&b&alac!-oigger?oigger??mu??dna&-&attelrab-inart?inart-attelrab??attelrabinart?inartattelrab?ssela??epmi?ugil??tnelav&-obiv?obiv??vap?z&e&nev?ps&-al?al???irog???l&iuqa!l??leib??m&or?rap??n!acsot?e&dom?is?sec&-&ilrof?ìlrof??ilrof?ìlrof???g&amor&-ailime?ailime??edras?olob??i&ssem?tal??ne!var??o&cna?merc?rev?vas???oneg?p?r!a&csep?rr&ac&-assam?assam??ef??von??etam?tsailgo!-lled?lled???s!ip?sam&-ararrac?ararrac??u&caris?gar???t!a&cilisab?recam??resac?soa!-&d&-&ellav?lav??ellav?lav??ellav??d&-&ellav?lav??ellav?lav??ellav??te&lrab&-&airdna-inart?inart-airdna??airdnainart?inartairdna??ssinatlac???udap?v!o&dap?neg?tnam???zn&airb&-a&lled-e-aznom?znom??a&lledeaznom?znom??eaznom??e&c&aip?iv??soc?top??om???b&-&23,46,61,?3c-lorit-ds-onitnert--nx?be-etsoa&-ellav--nx?dellav--nx??c!f-anesec-lrof--nx?m-lrof-anesec--nx??he-etsoa-d-ellav--nx?m!u??o2-loritds-nezob--nx?sn-loritds&-nasl&ab--nx?ub--nx??nitnert--nx??v!6-lorit-dsnitnert--nx?7-loritds&-nitnert--nx?onitnert--nx???z&r-lorit-ds&-nitnert--nx?onitnert--nx??s-loritds-onitnert--nx???c&f?is?l?m?p?r?v??d&p?u!olcnys,??e&c!cel?inev?nerolf??f?g!apemoh321,ida&-&a&-onitnert?onitnert??otla!-onitnert?onitnert???a&-onitnert?onitnert??otla!-on&azlob?itnert??onitnert????hcram?l?m!or??n&idu?o&n&edrop?isorf??torc???p?r?s&erav?ilom??t!nomeip?s&eirt?oa!-&d-e&ellav?éllav??e&ellav?éllav???de&ellav?éllav??e&ellav?éllav?????v?znerif??g&a?b?f?il?o?p?r?up?vf??hc?i&b?c?dol?f?l!lecrev?opan?rof&-anesec?anesec???m?n&a&part?rt&-attelrab-airdna?attelrabairdna???imir?ret??p?r!a&b?ilgac?ssas???s!idnirb??t&ei&hc?r??sa??v??l&a!c??b?c?o&m?rit&-&d&eus&-&nitnert?onitnert??nitnert?onitnert??us&-&nitnert?onitnert??nitnert?onitnert??üs&-&nitnert?onitnert??nitnert?onitnert???s&-onitnert?onitnert???d&eus!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??us&-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert??üs!-&n&asl&ab?ub??ezob?itnert??onitnert??nitnert?onitnert???s&-onitnert?onitnert?????m&ac?f?i!t.nepo.citsalej.duolc,?ol?r??n&a!lim?sl&ab?ub???b?c?e!en.cj,v?zob??irut?m!p??p?r?t??o&a!v??b!retiv??c!cel??enuc?g!ivor??i&dem&-onadipmac?onadipmac??pmet&-aiblo?aiblo??rdnos?zal??l?m!a&greb?ret??oc?re&f?lap???n!a&dipmac&-oidem?oidem??lim?tsiro?zlob??ecip&-ilocsa?ilocsa??i&bru&-orasep?orasep??lleva?rot?tnert??r&elas?ovil??ulleb??p?r!a&sep&-onibru?onibru??znatac??oun??s!ivert?sabopmac??t!arp?e&nev?ssorg??n&arat?e&girga?rt?veneb????zz&era?urba???p&a?ohsdaerpsym,s?t??qa?r&a!m?s??b!a??c?f?g?k?me?o?p?s?t?v??s&a&b?iselgi&-ainobrac?ainobrac???b?c?elpan?i?m?o&t?x&bi,obdaili,??s?t?v??t&a?b?c?l?m?nomdeip?o!psgolb,?p?v??u&de?l?n?p??v&a?og?p?s?t?v??y&drabmol?ellav&-atsoa?atsoa??licis?nacsut??z&al?b?c?p??ìlrof&-anesec?anesec???derc?er?f?m?utni??je3a3abgm--nx?kh?l!.&topsgolb,vog??uda??m!.&gro?moc!.topsgolb,?ten?ude???n&a&morockivdnas?ruatser?tnuocca??e&g?m&eganam!.retuor,?piuqe??r??i!.ue?m?opdlog??opud?uocsid??o&b?cs!.&ude,vog:.ecivres,,??d?g?h?j?oferab?p&edemoh?s???p!.&bewanigap321,emon?gro?lbup?moc?t&en?ni?opsgolb,?ude?vog???r&a!m&law?s???epxe?op&er?pus!.ysrab,?s???s!.&a&daxiabme?rarik,?e&motoas?picnirp?rots??gro?lim?moc?o&c?dalusnoc?hon,?ten?ude??a&cmoc?f??e&b?r?uq??i!rolf?tned??o&h!.&duolc&p,rim,?e&lej,tiseerf,?flah,l&enapysae,rupmet,?s&pvtsaf,seccaduolc,?tsafym,vedumpw,??p!sua???urt??t!.&eman?gro?ibom?levart?m&oc?uesum??o&c?fni?r&ea?p???pooc?sboj?t&en?ni??ude?vog?zib??ayh?n?o!bba?irram???uognah?xen?y!.gro,?ztej??u&2&5te9--nx?yssp--nx??a!.&a&s?w??civ?d&i?lq??fnoc?gro?moc!.&pohsdaerpsym,stelduolc.lem,topsgolb,??nsa?ofni?sat?t&ca?en?n??ude!.&a&s?w??ci&lohtac?v??dlq?sat?t&ca?n??wsn!.sloohcs????vog!.&a&s?w??civ?dlq?sat???wsn?zo??ti??c!.&fni?gro?moc?ten?ude?vog??i??d&e!.tir.segap-tig,?iab??e!.&dcym,enozgniebllew,noitatsksid,odagod.citsalej,s&nd&ps,uolc,?ppatikria,?ysrab,??g!.&bew?gro?m&aug?oc??ofni?ten?ude?vog???h!.&0002?a&citore?idem?kitore??edszot?gro?ilus?letoh?m&alker?lif?t?urof??naltagni?o&c?ediv?fni?levynok?nisac??pohs?rarga?s&a&kal?zatu??emag?wen??t&lob?opsgolb,rops??virp?xe&s?zs??ytic?zsagoj??os?sut??l!.&etisbew321,topsgolb,??m!.&ca?gro?moc?oc?ro?ten?vog???n!.&duolcesirpretne,eni&esrem,m,?tenkcahs,?em!.ysrab,??o&ggnaw?y!c???r!.&3kl,a&i&kymlak,rikhsab,vodrom,?yegyda,?bps,ca,duolcrim,e&niram,rpcm,?g&bc,nitsohurger.citsalej,ro,?ianatsuk,k&ihclan,s&m,rogitayp,??li&amdlc.bh,m,?moc,natsegad,onijym,pp,ri&b,d&cm:.spv,,orue,?midalv,?s&ar,itym,?t&en,ias321,ni,opsgolb,set,?u&4an,de,?vo&g,n,?ynzorg,zakvakidalv,?myc?p?ug??s!.&a&d&golov,nagarak,?gulak,i&groeg,kymlak,lerak,nemra,rikhsab,ssakahk,vodrom,zahkba,?lut,rahkub,vut,yegyda,znep,?bps,da&baghsa,rgonilest,?gunel,i&anatsuk,hcos,ovan,ttailgot,?k&alhsygnam,ihclan,s&legnahkra,m,n&a&mrum,yrb,?i&buytka,nbo,??tiort,vorkop,??l&ocarak,ybmaj,?na&gruk,jiabreza,ts&egad,hkazak-&htron,tsae,???ovonavi,r&adonsark,imidalv,?t&enxe,nek&hsat,mihc,??vo&hsalab,n,?ynzorg,z&akvakidalv,emret,??t&amok?i&juf?masih????v!.&em,g&olb,ro??moc?nc,ten?ude?ved,??ykuyr??v&b?c!.&emon?gro?moc?t&ni?opsgolb,?ude???ed!.&2r,ated,e&docotua,erf-korgn,nilnigol,?gnigats-oned,hcetaidem,korgn,lecrev,o&ned,tpyrctfihs,?ppa-rettalp,s&egap,rekrow,?vr&esi,uc,?weiverpbuhtig,ylf,??ih?l!.&di?fnoc?gro?lim?moc?nsa?ten?ude?vog???m!.&eman?gro?lim?m&oc?uesum??o&fni?r&ea?p???pooc?t&en?ni??ude?vog?zib???o&g?m??rt?s!.&bog?der?gro?moc?ude???t!.&arukas,bew-eht-no,morf,naht-&esrow,retteb,?sndnyd,?d?i?won??uqhv--nx??w&a!.moc?hs?l??b!.&gro?oc???c!.&gro?moc?ten?ude??cp??e&iver!.oby,?n?s??g?k!.&bme?dni?gro?moc?ten?ude?vog???m!.&ca?gro?m&oc?uesum??oc?pooc?t&en?ni??ude?vog?zib??b??o&csom?h!s??n?w??p!.&344x,de?en?o&c?g??ro?snduolc,ualeb???r!.&ca?gro?lim?oc?pooc?ten?vog??n??t!.&a46oa0fz--nx?b&82wrzc--nx?ulc??emag?gro?l&im?ru,?moc!.reliamym,?t&en?opsgolb,?ude?v&di?og?ta0cu--nx??zibe?業商?織組?路網???z!.&ca?gro?lim?oc?vog????x&a!.&cm,eb,gg,s&e,u,?tac,ue,yx,?t??c!.&hta,ofni,vog???e&d&ef?nay??ma!nab??rof?s??ilften?jt?m!.&bog?gro?moc?t&en?opsgolb,?ude??g?ma2ibgy--nx??o&b!x??f?rex??rbgn--nx?s!.vog??x&am&jt?kt??x???y&4punu--nx?7rr03--nx?a&d!i&loh?rfkcalb??ot!.emyfilauqerp,??g?lp?p!ila??rot?ssin?wdaorb??b!.&duolcym,fo?hcetai",
+ "dem,lim?moc!.topsgolb,?vog??ab?gur??c!.&ca?dtl?gro?lim?m&oc!.&ecrofelacs.j,topsgolb,??t??orp?s&egolke?serp??ten?vog?zib??amrahp?nega??d&dadog?uts??e&kcoh?ltneb?n&dys?om?rotta??snikcm??g!.&eb,gro?moc?oc?ten?ude?vog??olonhcet!.oc,?rene??hpargotohp?id?k!.&gro?moc?ten?ude??s??l!.&clp?d&em?i??gro?hcs?moc?ten?ude?vog??f?imaf!nacirema??l&a?il??ppus??m!.&eman?gro?lim?moc?t&en?opsgolb,?ude?vog?zib??edaca!.laiciffo,?ra??n&a&ffit?pmoc??os??o&j?s??p!.&gro?lim?moc?pooc?ten?ude?vog???r&e&corg?grus?llag?viled??lewej?otcerid?tnuoc?uxul??s!.&gro?lim?moc?ten?ude?vog??pil??t&efas?i&c?ledif?n&ifx?ummoc!.&bdnevar,gon,murofym,???r&ahc?uces??srevinu??laer?r&ap!.oby,?eporp??uaeb??u!.&bug?gro?lim?moc!.topsgolb,?ten?ude??b!tseb???van!dlo??xes??z&a!.&eman?gro?lim?moc?o&fni?rp??pp?t&en?ni??ude?vog?zib???b!.&az,gro?jsg,moc?ten?ude?vog???c!.&4e,inum.duolc.&rsu,tlf,?m&laer,urtnecatem.motsuc,?oc,topsgolb,??d!.&cos?gro?lop?m&oc?t??ossa?t&en?ra??ude?vog???ib!.&duolcsd,e&ht-rof,mos-rof,rom-rof,?izoj,liartevitca,nafamm,p&i&-on,fles,?ohbew,tfym,?retteb-rof,snd&nyd,uolc,?xro,?g??k!.&duolcj,gro?lim?moc?t&en?ropeletzak.saapu,?ude?vog???m!.&ca?gro?lim?oc?ten?ude?v&da?og????n!.&asq-irom--nx?ca?gro?htlaeh?i&r&c?o&am?ām???wi!k???keeg?l&im?oohcs??neg?oc!.topsgolb,?t&en?nemailrap?vog???a!niflla???rawhcs?s!.&ca?gro?oc???t!.&c&a?s??e&m?n??ibom?l&etoh?im??o&c?fni?g??ro?vt???u!.&gro?moc?oc?ten??rwon??yx!.&e&nozlacol,tisgolb,?gnitfarc,otpaz,??zub??λε?υε?авксом?брс!.&гро?до?ка?р&бо?п!у?????г&б?ро??дкм?зақ?итед?килотак?леб?мок?н&йално?ом??рку?сур!.&арамас,бпс,гро,зиб,ичос,ксм,м&ок,ырк,?рим,я,??тйас?фр?юе?յահ?לארשי!.&בושי?הימדקא?ל&הצ?שממ????םוק?اي&روس?سيلم?ناتيروم??بر&ع?غملا??ة&كبش?ي&دوعسلا?روس??یدوعسلا??ت&ا&راما?لاصتا??را&ب?ڀ?ھب???ر&ئازجلا?ازاب?صم?طق??سنوت?عقوم?قارع?ك&تيب?يلوثاك??موك?ن&ا&تس&كاپ?کاپ??دوس?ر&يا?یا??مع?يلعلا??درالا?ميلا?ي&رحبلا?طسلف???ه&ارمه?يدوعسلا??وكمارا?يبظوبا?ۃیدوعسلا?टेन?त&राभ?ोराभ??नठगंस?मॉक?्मतराभ?ত&রাভ?ৰাভ??ালংাব?ਤਰਾਭ?તરાભ?ତରାଭ?ாயித்நஇ?ைக்ஙலஇ?்ரூப்பக்ஙிச?్తరాభ?ತರಾಭ?ംതരാഭ?ාකංල?มอค?ยทไ!.&จิกรุธ?ต็นเ?ร&ก์คงอ?าหท??ลาบฐัร?าษกึศ???ວາລ?ეგ?なんみ?アトス?トンイポ?ドウラク?ムコ?ル&グーグ?ーセ??ン&ゾマア?ョシッァフ??业企?东广?乐娱?你爱我?信中?务政?动移?博微?卦八?厅餐?司公?品食?善慈?团集?国中?國中?址网?坡加新?城商?尚时?山佛?店&商?网?酒大里嘉??府政?康健?息信?戏游?拉里格香?拿大?教主天?机手?构机!织组??标商?歌谷?浦利飞?港香!.&人個?司公?府政?絡網?織組?育教???湾台?灣&台?臺??物购?界世?益公?看点?科盈訊電?站网?籍書?线在?络网?网文中?聘招?販通?逊马亚?通联?里嘉?锡马淡?門澳?门澳?闻新?電家?국한?넷닷?성삼?컴닷??");
/**
* If a hostname is not a key in the EXCLUDE map, and if removing its leftmost component results
@@ -50,7 +56,7 @@ public final class PublicSuffixPatterns {
*/
public static final ImmutableMap<String, PublicSuffixType> UNDER =
TrieParser.parseTrie(
- "ac.vedwa,d&b?i.ym.ssr,uolc.&etiso&isnes,tnegam,?iaznab,rehcnar-no,scitats,??e&b.lrusnart,d.&ecapsrebu,yksurf,?noz.notirt,t&atse.etupmoc,is.&areduolc,hsmroftalp,tst,???g&oog.tnetnocresu,p??h&c.tenerif:.cvs,,k?trae.sppad:.zzb,,?k&c?f?nil.bewd,rowten.secla,u.hcs??ln.lrusnart,m&j?m?oc.&duolcmeaeboda.ved,edonil.recnalabedon,ico-remotsuc:.&ico,pco,sco,?,lrihwyap,mme0,osseccandcved,s&ecapsnaecolatigid,t&cejbo&edonil,rtluv,?nemelepiuq,?wanozama.&1-etupmoc,ble,etupmoc,??t&neyoj.snc,opsppa.r,???n&c.moc.swanozama.&ble,etupmoc,?ur.edoc,?o&c.pato,i.&duolciaznab.sdraykcab,elacsnoom,oir-no,reniatnoceruza,s&3k-no,olots,?xcq.sys,y5s,??p&j.&a&mahokoy?yogan??ebok?i&adnes?kasawak??oroppas?uhsuykatik??n?pa.&knalfhtron,repoleved,tegeb,??r&b.mon?e??s&edoc.owo,noitulos.rehid,w.rosivda,?t&a.&ofnistro.&nednuk,xe,?smcerutuf:.&ni,xe,?,?en.&cimonotpyrc,hvo.&gnitsoh,saapbew,???u&e.lrusnart,r.onijym.&gni&dnal,tsoh,?murtceps,spv,??ved.&e&gats&gts,lcl,?rahbew,?gts,lcl,yawetag,?z&c.murtnecatem.duolc,yx.tibelet,??");
+ "ac.vedwa,d&b?i.ym.ssr,uolc.&etiso&isnes,tnegam,?iaznab,rehcnar-no,scitats,??e&b.lrusnart,d.&ecapsrebu,yksurf,?noz.notirt,t&atse.etupmoc,is.&areduolc,hsmroftalp,tst,???g&oog.tnetnocresu,p??h&c.tenerif:.cvs,,k?trae.sppad:.zzb,,?k&c?f?nil.bewd,rowten.secla,u.hcs??ln.lrusnart,m&f.resu,j?m?oc.&duolcmeaeboda.ved,edo&c.redliub:-&gts,ved,?,nil.recnalabedon,?ico-remotsuc:.&ico,pco,sco,?,lrihwyap,mme0,osseccandcved,s&ecapsnaecolatigid,t&cejbo&edonil,rtluv,?nemelepiuq,?wanozama.&1-etupmoc,ble,etupmoc,??t&neyoj.snc,opsppa.r,???n&c.moc.swanozama.&ble,etupmoc,?ur.&dliub,e&doc,sabatad,?noitargim,??o&c.pato,i.&duolciaznab.sdraykcab,elacsnoom,nroca-no,oir-no,reniatnoceruza,s&3k-no,olots,?xcq.sys,y5s,??p&j.&a&mahokoy?yogan??ebok?i&adnes?kasawak??oroppas?uhsuykatik??n?pa.&knalfhtron,repoleved,tegeb,??r&b.mon?e??s&edoc.owo,noitulos.rehid,w.rosivda,?t&a.&ofnistro.&nednuk,xe,?smcerutuf:.&ni,xe,?,?en.&cimonotpyrc,hvo.&gnitsoh,saapbew,???u&e.lrusnart,r.onijym.&gni&dnal,tsoh,?murtceps,spv,??ved.&e&gats&gts,lcl,?rahbew,?gts,lcl,treclacol.resu,yawetag,?z&c.murtnecatem.duolc,yx.tibelet,??");
/**
* The elements in this map would pass the UNDER test, but are known not to be public suffixes and
diff --git a/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java b/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
index 89cdadd3d..82bf8b3c1 100644
--- a/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
+++ b/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
@@ -14,28 +14,40 @@
package com.google.thirdparty.publicsuffix;
+import static com.google.common.collect.Queues.newArrayDeque;
+
import com.google.common.annotations.GwtCompatible;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Queues;
import java.util.Deque;
/** Parser for a map of reversed domain names stored as a serialized radix tree. */
@GwtCompatible
final class TrieParser {
- private static final Joiner PREFIX_JOINER = Joiner.on("");
+
+ private static final Joiner DIRECT_JOINER = Joiner.on("");
/**
* Parses a serialized trie representation of a map of reversed public suffixes into an immutable
- * map of public suffixes.
+ * map of public suffixes. The encoded trie string may be broken into multiple chunks to avoid the
+ * 64k limit on string literal size. In-memory strings can be much larger (2G).
*/
- static ImmutableMap<String, PublicSuffixType> parseTrie(CharSequence encoded) {
+ static ImmutableMap<String, PublicSuffixType> parseTrie(CharSequence... encodedChunks) {
+ String encoded = DIRECT_JOINER.join(encodedChunks);
+ return parseFullString(encoded);
+ }
+
+ @VisibleForTesting
+ static ImmutableMap<String, PublicSuffixType> parseFullString(String encoded) {
ImmutableMap.Builder<String, PublicSuffixType> builder = ImmutableMap.builder();
int encodedLen = encoded.length();
int idx = 0;
+
while (idx < encodedLen) {
- idx += doParseTrieToBuilder(Queues.<CharSequence>newArrayDeque(), encoded, idx, builder);
+ idx += doParseTrieToBuilder(newArrayDeque(), encoded, idx, builder);
}
+
return builder.buildOrThrow();
}
@@ -59,9 +71,10 @@ final class TrieParser {
int idx = start;
char c = '\0';
- // Read all of the characters for this node.
+ // Read all the characters for this node.
for (; idx < encodedLen; idx++) {
c = encoded.charAt(idx);
+
if (c == '&' || c == '?' || c == '!' || c == ':' || c == ',') {
break;
}
@@ -74,17 +87,20 @@ final class TrieParser {
// '?' represents a leaf node, which represents a REGISTRY entry in map.
// ':' represents an interior node that represents a private entry in the map
// ',' represents a leaf node, which represents a private entry in the map.
- String domain = PREFIX_JOINER.join(stack);
+ String domain = DIRECT_JOINER.join(stack);
+
if (domain.length() > 0) {
builder.put(domain, PublicSuffixType.fromCode(c));
}
}
+
idx++;
if (c != '?' && c != ',') {
while (idx < encodedLen) {
// Read all the children
idx += doParseTrieToBuilder(stack, encoded, idx, builder);
+
if (encoded.charAt(idx) == '?' || encoded.charAt(idx) == ',') {
// An extra '?' or ',' after a child node indicates the end of all children of this node.
idx++;
@@ -92,6 +108,7 @@ final class TrieParser {
}
}
}
+
stack.pop();
return idx - start;
}
diff --git a/integration-tests/gradle/.gitignore b/integration-tests/gradle/.gitignore
new file mode 100644
index 000000000..f8b92c3aa
--- /dev/null
+++ b/integration-tests/gradle/.gitignore
@@ -0,0 +1,2 @@
+.gradle
+build
diff --git a/integration-tests/gradle/build.gradle.kts b/integration-tests/gradle/build.gradle.kts
new file mode 100644
index 000000000..79db509a4
--- /dev/null
+++ b/integration-tests/gradle/build.gradle.kts
@@ -0,0 +1,221 @@
+val runningGradle5 = gradle.gradleVersion.startsWith("5.")
+
+val guavaVersionJre =
+ "<version>(.*)</version>".toRegex().find(file("../../pom.xml").readText())?.groups?.get(1)?.value
+ ?: error("version not found in pom")
+
+val expectedReducedRuntimeClasspathAndroidVersion =
+ setOf(
+ "guava-${guavaVersionJre.replace("jre", "android")}.jar",
+ "failureaccess-1.0.1.jar",
+ "jsr305-3.0.2.jar",
+ "checker-qual-3.33.0.jar",
+ "error_prone_annotations-2.18.0.jar",
+ "listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar"
+ )
+val expectedReducedRuntimeClasspathJreVersion =
+ setOf(
+ "guava-$guavaVersionJre.jar",
+ "failureaccess-1.0.1.jar",
+ "jsr305-3.0.2.jar",
+ "checker-qual-3.33.0.jar",
+ "error_prone_annotations-2.18.0.jar",
+ "listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar"
+ )
+val expectedCompileClasspathAndroidVersion =
+ expectedReducedRuntimeClasspathAndroidVersion + setOf("j2objc-annotations-2.8.jar")
+val expectedCompileClasspathJreVersion =
+ expectedReducedRuntimeClasspathJreVersion + setOf("j2objc-annotations-2.8.jar")
+
+val extraLegacyDependencies =
+ setOf(
+ "google-collections-1.0.jar"
+ )
+
+buildscript {
+ val agpVersion = if (gradle.gradleVersion.startsWith("5.")) "3.6.4" else "7.0.4"
+ repositories {
+ google()
+ mavenCentral()
+ }
+ dependencies {
+ classpath("com.android.tools.build:gradle:$agpVersion") {
+ exclude(
+ group = "org.jetbrains.trove4j"
+ ) // Might not be available on Maven Central and not needed for this test
+ }
+ }
+}
+
+subprojects {
+ if (name.endsWith("Java")) {
+ apply(plugin = "java-library")
+ } else {
+ apply(plugin = "com.android.application")
+ the<com.android.build.gradle.AppExtension>().compileSdkVersion(30)
+ }
+
+ var expectedClasspath =
+ if (runningGradle5) {
+ // without Gradle Module Metadata (only the POM is used)
+ // - variant decision is made based on version suffix (android/jre) and not on the actual
+ // environment
+ // - runtime classpath equals the compile classpath
+ // - dependency conflict with Google Collections is not detected
+ if (name.startsWith("android")) {
+ expectedCompileClasspathAndroidVersion + extraLegacyDependencies
+ } else {
+ expectedCompileClasspathJreVersion + extraLegacyDependencies
+ }
+ } else {
+ // with Gradle Module Metadata
+ // - variant is chosen based on the actual environment, independent of version suffix
+ // - reduced runtime classpath is used (w/o annotation libraries)
+ // - capability conflicts are detected with Google Collections
+ if (name.contains("Android") && !name.contains("JreConstraint")) {
+ when {
+ name.contains("RuntimeClasspath") -> {
+ expectedReducedRuntimeClasspathAndroidVersion
+ }
+ name.contains("CompileClasspath") -> {
+ expectedCompileClasspathAndroidVersion
+ }
+ else -> {
+ error("unexpected classpath type: $name")
+ }
+ }
+ } else {
+ when {
+ name.contains("RuntimeClasspath") -> {
+ expectedReducedRuntimeClasspathJreVersion
+ }
+ name.contains("CompileClasspath") -> {
+ expectedCompileClasspathJreVersion
+ }
+ else -> {
+ error("unexpected classpath type: $name")
+ }
+ }
+ }
+ }
+ val guavaVersion =
+ if (name.startsWith("android")) {
+ guavaVersionJre.replace("jre", "android")
+ } else {
+ guavaVersionJre
+ }
+ val javaVersion = JavaVersion.VERSION_1_8
+
+ repositories {
+ mavenCentral()
+ mavenLocal()
+ }
+ val java = the<JavaPluginExtension>()
+ java.targetCompatibility = javaVersion
+ java.sourceCompatibility = javaVersion
+
+ if (!runningGradle5) {
+ configurations.all {
+ resolutionStrategy.capabilitiesResolution {
+ withCapability("com.google.collections:google-collections") {
+ candidates
+ .find {
+ val idField =
+ it.javaClass.getDeclaredMethod(
+ "getId"
+ ) // reflective access to make this compile with Gradle 5
+ (idField.invoke(it) as ModuleComponentIdentifier).module == "guava"
+ }
+ ?.apply { select(this) }
+ }
+ }
+ }
+
+ if (name.contains("AndroidConstraint")) {
+ dependencies {
+ constraints {
+ "api"("com.google.guava:guava") {
+ attributes {
+ // if the Gradle version is 7+, you can use
+ // TargetJvmEnvironment.TARGET_JVM_ENVIRONMENT_ATTRIBUTE
+ attribute(Attribute.of("org.gradle.jvm.environment", String::class.java), "android")
+ }
+ }
+ }
+ }
+ configurations.all {
+ resolutionStrategy.capabilitiesResolution {
+ withCapability("com.google.guava:guava") {
+ candidates
+ .find {
+ val variantName = it.javaClass.getDeclaredMethod("getVariantName")
+ (variantName.invoke(it) as String).contains("android")
+ }
+ ?.apply { select(this) }
+ }
+ }
+ }
+ }
+
+ if (name.contains("JreConstraint")) {
+ dependencies {
+ constraints {
+ "api"("com.google.guava:guava") {
+ attributes {
+ // if the Gradle version is 7+, you can use
+ // TargetJvmEnvironment.TARGET_JVM_ENVIRONMENT_ATTRIBUTE
+ attribute(
+ Attribute.of("org.gradle.jvm.environment", String::class.java),
+ "standard-jvm"
+ )
+ }
+ }
+ }
+ }
+ configurations.all {
+ resolutionStrategy.capabilitiesResolution {
+ withCapability("com.google.guava:guava") {
+ candidates
+ .find {
+ val variantName = it.javaClass.getDeclaredMethod("getVariantName")
+ (variantName.invoke(it) as String).contains("jre")
+ }
+ ?.apply { select(this) }
+ }
+ }
+ }
+ }
+ }
+
+ dependencies {
+ "api"("com.google.collections:google-collections:1.0")
+ "api"("com.google.guava:listenablefuture:1.0")
+ "api"("com.google.guava:guava:$guavaVersion")
+ }
+
+ tasks.register("testClasspath") {
+ doLast {
+ val classpathConfiguration =
+ if (project.name.contains("RuntimeClasspath")) {
+ if (project.name.endsWith("Java")) configurations["runtimeClasspath"]
+ else configurations["debugRuntimeClasspath"]
+ } else if (project.name.contains("CompileClasspath")) {
+ if (project.name.endsWith("Java")) configurations["compileClasspath"]
+ else configurations["debugCompileClasspath"]
+ } else {
+ error("unexpected classpath type: " + project.name)
+ }
+
+ val actualClasspath = classpathConfiguration.files.map { it.name }.toSet()
+ if (actualClasspath != expectedClasspath) {
+ throw RuntimeException(
+ """
+ Expected: ${expectedClasspath.sorted()}
+ Actual: ${actualClasspath.sorted()}
+ """
+ .trimIndent()
+ )
+ }
+ }
+ }
+}
diff --git a/integration-tests/gradle/gradle/wrapper/gradle-wrapper.jar b/integration-tests/gradle/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..afba10928
--- /dev/null
+++ b/integration-tests/gradle/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/integration-tests/gradle/gradle/wrapper/gradle-wrapper.properties b/integration-tests/gradle/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..4e86b9270
--- /dev/null
+++ b/integration-tests/gradle/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.2-bin.zip
+networkTimeout=10000
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/integration-tests/gradle/gradlew b/integration-tests/gradle/gradlew
new file mode 100755
index 000000000..65dcd68d6
--- /dev/null
+++ b/integration-tests/gradle/gradlew
@@ -0,0 +1,244 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original 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
+#
+# https://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.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/integration-tests/gradle/gradlew.bat b/integration-tests/gradle/gradlew.bat
new file mode 100755
index 000000000..93e3f59f1
--- /dev/null
+++ b/integration-tests/gradle/gradlew.bat
@@ -0,0 +1,92 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/integration-tests/gradle/settings.gradle.kts b/integration-tests/gradle/settings.gradle.kts
new file mode 100644
index 000000000..263163705
--- /dev/null
+++ b/integration-tests/gradle/settings.gradle.kts
@@ -0,0 +1,29 @@
+rootProject.name = "guava-integration-test"
+
+include("standardJvmCompileClasspathJava")
+
+include("androidCompileClasspathJava")
+
+include("standardJvmRuntimeClasspathJava")
+
+include("androidRuntimeClasspathJava")
+
+include("standardJvmCompileClasspathAndroid")
+
+include("androidCompileClasspathAndroid")
+
+include("standardJvmRuntimeClasspathAndroid")
+
+include("androidRuntimeClasspathAndroid")
+
+// Enforce 'android' variant in Java projects via constraint
+
+include("standardJvmAndroidConstraintCompileClasspathJava")
+
+include("androidAndroidConstraintCompileClasspathJava")
+
+// Enforce 'jre' variant in Android projects via constraint
+
+include("standardJvmJreConstraintCompileClasspathAndroid")
+
+include("androidJreConstraintCompileClasspathAndroid")
diff --git a/overview.html b/overview.html
new file mode 100644
index 000000000..794a5daf5
--- /dev/null
+++ b/overview.html
@@ -0,0 +1,11 @@
+<body>
+
+Guava is a set of core Java libraries from Google that includes new collection
+types (such as multimap and multiset), immutable collections, a graph library,
+and utilities for concurrency, I/O, hashing, primitives, strings, and more! It
+is widely used on most Java projects within Google, and widely used by many
+other companies as well.
+
+
+<p>For more information, see <a href="https://guava.dev/">guava.dev</a>.
+</body>
diff --git a/pom.xml b/pom.xml
index 13dd0985d..38df75f49 100644
--- a/pom.xml
+++ b/pom.xml
@@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
- <version>31.1-jre</version>
+ <version>32.1.2-jre</version>
<packaging>pom</packaging>
<name>Guava Maven Parent</name>
<description>Parent for guava artifacts</description>
@@ -14,14 +14,21 @@
<properties>
<!-- Override this with -Dtest.include="**/SomeTest.java" on the CLI -->
<test.include>%regex[.*.class]</test.include>
- <truth.version>1.1.2</truth.version>
- <checker-framework.version>3.12.0</checker-framework.version>
- <animal.sniffer.version>1.20</animal.sniffer.version>
- <maven-javadoc-plugin.version>3.1.0</maven-javadoc-plugin.version>
+ <truth.version>1.1.3</truth.version>
+ <maven-javadoc-plugin.version>3.4.1</maven-javadoc-plugin.version>
+ <javac.version>9+181-r4173-1</javac.version>
<!-- Empty for all JDKs but 9-12 -->
<maven-javadoc-plugin.additionalJOptions></maven-javadoc-plugin.additionalJOptions>
<maven-source-plugin.version>3.2.1</maven-source-plugin.version>
+ <project.build.outputTimestamp>2023-07-31T21:01:01Z</project.build.outputTimestamp>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <test.add.opens></test.add.opens>
+ <module.status>release</module.status>
+ <variant.jvmEnvironment>standard-jvm</variant.jvmEnvironment>
+ <variant.jvmEnvironmentVariantName>jre</variant.jvmEnvironmentVariantName>
+ <otherVariant.version>32.1.2-android</otherVariant.version>
+ <otherVariant.jvmEnvironment>android</otherVariant.jvmEnvironment>
+ <otherVariant.jvmEnvironmentVariantName>android</otherVariant.jvmEnvironmentVariantName>
</properties>
<issueManagement>
<system>GitHub Issues</system>
@@ -71,11 +78,11 @@
<testSourceDirectory>test</testSourceDirectory>
<resources>
<resource>
- <directory>src</directory>
- <excludes>
- <exclude>**/*.java</exclude>
- <exclude>**/*.sw*</exclude>
- </excludes>
+ <directory>..</directory>
+ <includes>
+ <include>LICENSE</include>
+ </includes>
+ <targetPath>META-INF</targetPath>
</resource>
</resources>
<testResources>
@@ -112,6 +119,9 @@
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
+ <configuration>
+ <source>${java.specification.version}</source>
+ </configuration>
</plugin>
</plugins>
<pluginManagement>
@@ -122,6 +132,8 @@
<configuration>
<source>1.8</source>
<target>1.8</target>
+ <encoding>UTF-8</encoding>
+ <parameters>true</parameters>
<compilerArgs>
<!--
Make includes/excludes fully work:
@@ -131,7 +143,24 @@
-->
<arg>-sourcepath</arg>
<arg>doesnotexist</arg>
+ <!-- https://errorprone.info/docs/installation#maven -->
+ <arg>-XDcompilePolicy=simple</arg>
+ <!-- -Xplugin:ErrorProne is set conditionally by a profile. -->
</compilerArgs>
+ <annotationProcessorPaths>
+ <path>
+ <groupId>com.google.errorprone</groupId>
+ <artifactId>error_prone_core</artifactId>
+ <version>2.16</version>
+ </path>
+ </annotationProcessorPaths>
+ <!-- Fork:
+
+ - for JDK8 because we use a javac9 bootclasspath
+
+ - for JDK9+ because we need args like add-exports
+ -->
+ <fork>true</fork>
</configuration>
</plugin>
<plugin>
@@ -152,8 +181,9 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
- <version>${animal.sniffer.version}</version>
+ <version>1.23</version>
<configuration>
+ <annotations>com.google.common.collect.IgnoreJRERequirement,com.google.common.hash.IgnoreJRERequirement,com.google.common.io.IgnoreJRERequirement,com.google.common.reflect.IgnoreJRERequirement,com.google.common.testing.IgnoreJRERequirement</annotations>
<checkTestClasses>true</checkTestClasses>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
@@ -224,7 +254,7 @@
<runOrder>alphabetical</runOrder>
<!-- Set max heap for tests. -->
<!-- Catch dependencies on the default locale by setting it to hi-IN. -->
- <argLine>-Xmx1536M -Duser.language=hi -Duser.country=IN</argLine>
+ <argLine>-Xmx1536M -Duser.language=hi -Duser.country=IN ${test.add.opens}</argLine>
</configuration>
</plugin>
<plugin>
@@ -232,6 +262,15 @@
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>3.3.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>3.4.0</version>
+ </plugin>
</plugins>
</pluginManagement>
</build>
@@ -262,87 +301,19 @@
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
- <version>${checker-framework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.checkerframework</groupId>
- <artifactId>checker-qual</artifactId>
- <version>${checker-framework.version}</version>
- <classifier>sources</classifier>
+ <version>3.33.0</version>
</dependency>
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
- <version>2.11.0</version>
+ <version>2.18.0</version>
</dependency>
<dependency>
<groupId>com.google.j2objc</groupId>
<artifactId>j2objc-annotations</artifactId>
- <version>1.3</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.13.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- <version>4.3</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <version>3.9.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.jimfs</groupId>
- <artifactId>jimfs</artifactId>
- <version>1.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.truth</groupId>
- <artifactId>truth</artifactId>
- <version>${truth.version}</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <!-- use the guava we're building. -->
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.google.truth.extensions</groupId>
- <artifactId>truth-java8-extension</artifactId>
- <version>${truth.version}</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <!-- use the guava we're building. -->
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.google.caliper</groupId>
- <artifactId>caliper</artifactId>
- <version>1.0-beta-2</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <!-- use the guava we're building. -->
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- </exclusions>
+ <version>2.8</version>
</dependency>
+ <!-- We avoid using dependencyManagement for test-only deps because of https://github.com/google/guava/issues/6654 -->
</dependencies>
</dependencyManagement>
<profiles>
@@ -379,7 +350,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
- <version>1.6</version>
+ <version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
@@ -395,21 +366,128 @@
</profile>
<profile>
<!--
- Passes JDK 9-12-specific `no-module-directories` flag to Javadoc tool,
+ Passes JDK 11-12-specific `no-module-directories` flag to Javadoc tool,
which is required to make symbol search work correctly in the generated
pages.
- This flag does not exist on 8 and 13+ (https://bugs.openjdk.java.net/browse/JDK-8215582).
+ This flag does not exist on 9-10 and 13+ (https://bugs.openjdk.java.net/browse/JDK-8215582).
Consider removing it once our release and test scripts are migrated to a recent JDK (17+).
-->
- <id>javadocs-jdk9-12</id>
+ <id>javadocs-jdk11-12</id>
<activation>
- <jdk>[9,13)</jdk>
+ <jdk>[11,13)</jdk>
</activation>
<properties>
<maven-javadoc-plugin.additionalJOptions>--no-module-directories</maven-javadoc-plugin.additionalJOptions>
</properties>
</profile>
+ <profile>
+ <id>open-jre-modules</id>
+ <activation>
+ <jdk>[9,]</jdk>
+ </activation>
+ <properties>
+ <!--
+ Some tests need reflective access to the internals of these packages. It is only the
+ tests themselves and not the code being tested that needs that access, though there's no
+ obvious way to ensure that.
+
+ We could consider arranging things so that only the tests we know need this would get
+ the add-opens. Right now that doesn't seem worth the effort, though.
+ -->
+ <test.add.opens>
+ --add-opens java.base/java.lang=ALL-UNNAMED
+ --add-opens java.base/java.util=ALL-UNNAMED
+ --add-opens java.base/sun.security.jca=ALL-UNNAMED
+ </test.add.opens>
+ </properties>
+ </profile>
+ <profile>
+ <id>javac9-for-jdk8</id>
+ <activation>
+ <jdk>1.8</jdk>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <!-- Under JDK8, we continue to use errorprone's javac9 (even
+ though we don't run Error Prone itself, which no longer
+ supports JDK8!).
+
+ Why? At some point, presumably after
+ https://github.com/google/guava/commit/e06a8cec65815599e510d7f9c1ea9d2a8eaa438a,
+ builds with JDK8 began failing animal-sniffer with the error:
+
+ Failed to check signatures: Bad class file .../CollectionFuture$ListFuture.class
+
+ One way of dealing with that would be to disable
+ animal-sniffer. And that would be fine for our -jre builds:
+ If we're building with JDK8, then clearly we're sticking to
+ JDK8 APIs. However, I assume (but did not confirm) that we'd
+ have the same issue with our -android builds, which need
+ animal-sniffer so that they can check that we're sticking to
+ JDK6-like APIs.
+
+ So instead, we use javac9, which doesn't lead to this error.
+ -->
+ <compilerArgs combine.children="append">
+ <arg>-J-Xbootclasspath/p:${settings.localRepository}/com/google/errorprone/javac/${javac.version}/javac-${javac.version}.jar</arg>
+ </compilerArgs>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ <profile>
+ <id>run-error-prone</id>
+ <activation>
+ <!--
+ Error Prone requires 11+: https://errorprone.info/docs/installation
+ We skip 12-15 because of https://github.com/google/error-prone/issues/3540.
+ -->
+ <jdk>[11,12),[16,)</jdk>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <compilerArgs combine.children="append">
+ <!-- https://errorprone.info/docs/installation#maven -->
+ <!-- TODO(cpovirk): Enable NullArgumentForNonNullParameter for
+ prod code. It's disabled automatically for "test code"
+ (which is good: our tests have intentional violations), but
+ Error Prone doesn't know it's building test code unless we
+ pass -XepCompilingTestOnlyCode, and that argument needs to
+ be passed as part of the same <arg> as -Xplugin:ErrorProne,
+ and I gave up trying to figure out how to do that for test
+ compilation only. -->
+ <arg>-Xplugin:ErrorProne -Xep:NullArgumentForNonNullParameter:OFF -Xep:Java8ApiChecker:ERROR</arg>
+ <!-- https://github.com/google/error-prone/blob/f8e33bc460be82ab22256a7ef8b979d7a2cacaba/docs/installation.md#jdk-16 -->
+ <!-- TODO(cpovirk): Use .mvn/jvm.config instead (per
+ https://errorprone.info/docs/installation#maven) if it can
+ be made not to interfere with JDK8 or if we stop building
+ with JDK8. -->
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>
+ <arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>
+ <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>
+ <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg>
+ </compilerArgs>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
</profiles>
</project>
diff --git a/proguard/base.pro b/proguard/base.pro
new file mode 100644
index 000000000..d696db4db
--- /dev/null
+++ b/proguard/base.pro
@@ -0,0 +1,33 @@
+# Note: We intentionally don't add the flags we'd need to make Flags and Enums
+# work. That's because the Proguard configuration required to make them work on
+# optimized code would preclude lots of optimization, like converting enums
+# into ints.
+
+# Throwables uses internal APIs for lazy stack trace resolution
+-dontnote sun.misc.SharedSecrets
+-keep class sun.misc.SharedSecrets {
+ *** getJavaLangAccess(...);
+}
+-dontnote sun.misc.JavaLangAccess
+-keep class sun.misc.JavaLangAccess {
+ *** getStackTraceElement(...);
+ *** getStackTraceDepth(...);
+}
+
+# FinalizableReferenceQueue calls this reflectively
+# Proguard is intelligent enough to spot the use of reflection onto this, so we
+# only need to keep the names, and allow it to be stripped out if
+# FinalizableReferenceQueue is unused.
+-keepnames class com.google.common.base.internal.Finalizer {
+ *** startFinalizer(...);
+}
+# However, it cannot "spot" that this method needs to be kept IF the class is.
+-keepclassmembers class com.google.common.base.internal.Finalizer {
+ *** startFinalizer(...);
+}
+-keepnames class com.google.common.base.FinalizableReference {
+ void finalizeReferent();
+}
+-keepclassmembers class com.google.common.base.FinalizableReference {
+ void finalizeReferent();
+}
diff --git a/proguard/cache.pro b/proguard/cache.pro
new file mode 100644
index 000000000..a67733b9e
--- /dev/null
+++ b/proguard/cache.pro
@@ -0,0 +1,12 @@
+# Striped64 uses this
+-dontwarn sun.misc.Unsafe
+
+# Striped64 appears to make some assumptions about object layout that
+# really might not be safe. This should be investigated.
+-keepclassmembers class com.google.common.cache.Striped64 {
+ *** base;
+ *** busy;
+}
+-keepclassmembers class com.google.common.cache.Striped64$Cell {
+ <fields>;
+}
diff --git a/proguard/collect.pro b/proguard/collect.pro
new file mode 100644
index 000000000..107706d2f
--- /dev/null
+++ b/proguard/collect.pro
@@ -0,0 +1,34 @@
+-dontwarn java.lang.SafeVarargs
+
+# The nested FieldSettersHolder class looks these up.
+#
+# We use -keepclassmembernames because we want for ImmutableMultimap and its
+# fields to be stripped if it's unused: -keepclassmembernames says that, *if*
+# you're keeping the fields, you need to leave their names untouched. (Anyone
+# who is using ImmutableMultimap will certainly be using its fields. So we
+# don't need to worry that an ImmutableMultimap user will have the fields
+# optimized away.)
+#
+# This configuration is untested....
+-keepclassmembernames class com.google.common.collect.ImmutableMultimap {
+ *** map;
+ *** size;
+}
+# similarly:
+-keepclassmembernames class com.google.common.collect.ConcurrentHashMultiset {
+ *** countMap;
+}
+# similarly:
+-keepclassmembernames class com.google.common.collect.ImmutableSetMultimap {
+ *** emptySet;
+}
+# similarly:
+-keepclassmembernames class com.google.common.collect.AbstractSortedMultiset {
+ *** comparator;
+}
+# similarly:
+-keepclassmembernames class com.google.common.collect.TreeMultiset {
+ *** range;
+ *** rootReference;
+ *** header;
+}
diff --git a/proguard/concurrent.pro b/proguard/concurrent.pro
new file mode 100644
index 000000000..a73c22a66
--- /dev/null
+++ b/proguard/concurrent.pro
@@ -0,0 +1,40 @@
+# Futures.getChecked, in both of its variants, is incompatible with proguard.
+
+# Used by AtomicReferenceFieldUpdater and sun.misc.Unsafe
+-keepclassmembers class com.google.common.util.concurrent.AbstractFuture** {
+ *** waiters;
+ *** value;
+ *** listeners;
+ *** thread;
+ *** next;
+}
+-keepclassmembers class com.google.common.util.concurrent.AtomicDouble {
+ *** value;
+}
+-keepclassmembers class com.google.common.util.concurrent.AggregateFutureState {
+ *** remaining;
+ *** seenExceptions;
+}
+
+# Since Unsafe is using the field offsets of these inner classes, we don't want
+# to have class merging or similar tricks applied to these classes and their
+# fields. It's safe to allow obfuscation, since the by-name references are
+# already preserved in the -keep statement above.
+-keep,allowshrinking,allowobfuscation class com.google.common.util.concurrent.AbstractFuture** {
+ <fields>;
+}
+
+# AbstractFuture uses this
+-dontwarn sun.misc.Unsafe
+
+# MoreExecutors references AppEngine
+-dontnote com.google.appengine.api.ThreadManager
+-keep class com.google.appengine.api.ThreadManager {
+ static *** currentRequestThreadFactory(...);
+}
+-dontnote com.google.apphosting.api.ApiProxy
+-keep class com.google.apphosting.api.ApiProxy {
+ static *** getCurrentEnvironment (...);
+}
+
+-dontwarn java.lang.SafeVarargs
diff --git a/proguard/hash.pro b/proguard/hash.pro
new file mode 100644
index 000000000..bc6f0adbc
--- /dev/null
+++ b/proguard/hash.pro
@@ -0,0 +1,12 @@
+# LittleEndianByteArray uses this
+-dontwarn sun.misc.Unsafe
+
+# Striped64 appears to make some assumptions about object layout that
+# really might not be safe. This should be investigated.
+-keepclassmembers class com.google.common.hash.Striped64 {
+ *** base;
+ *** busy;
+}
+-keepclassmembers class com.google.common.hash.Striped64$Cell {
+ <fields>;
+}
diff --git a/proguard/io.pro b/proguard/io.pro
new file mode 100644
index 000000000..f0df3cc3c
--- /dev/null
+++ b/proguard/io.pro
@@ -0,0 +1,3 @@
+-keep class java.lang.Throwable {
+ *** addSuppressed(...);
+}
diff --git a/proguard/primitives.pro b/proguard/primitives.pro
new file mode 100644
index 000000000..6968e0fa5
--- /dev/null
+++ b/proguard/primitives.pro
@@ -0,0 +1,2 @@
+# UnsignedBytes uses this
+-dontwarn sun.misc.Unsafe
diff --git a/proguard/reflect.pro b/proguard/reflect.pro
new file mode 100644
index 000000000..620cbd314
--- /dev/null
+++ b/proguard/reflect.pro
@@ -0,0 +1,9 @@
+# Warning: common.reflect (like reflection in general) is typically slow and
+# unreliable under Android. We do not recommend using it. This Proguard config
+# exists only to avoid breaking the builds of users who already have
+# common.reflect in their transitive dependencies.
+#
+-dontwarn com.google.common.reflect.Invokable
+-dontwarn com.google.common.reflect.Invokable$ConstructorInvokable
+-dontwarn com.google.common.reflect.Invokable$MethodInvokable
+-dontwarn com.google.common.reflect.Parameter
diff --git a/util/gradle_integration_tests.sh b/util/gradle_integration_tests.sh
new file mode 100755
index 000000000..9378e6717
--- /dev/null
+++ b/util/gradle_integration_tests.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+set -eu
+
+mvn clean install --projects '!guava-testlib,!guava-tests,!guava-bom,!guava-gwt' -Dmaven.test.skip=true -Dmaven.javadoc.skip=true
+mvn clean install --projects '!guava-testlib,!guava-tests,!guava-bom' -Dmaven.test.skip=true -Dmaven.javadoc.skip=true -f android
+
+# Gradle Wrapper overwrites some files when it runs.
+# To avoid modifying the Git client, we copy everything we need to another directory.
+# That provides general hygiene, including avoiding release errors:
+#
+# Preparing to update Javadoc and JDiff for the release...
+# error: Your local changes to the following files would be overwritten by checkout:
+# integration-tests/gradle/gradle/wrapper/gradle-wrapper.jar
+# integration-tests/gradle/gradle/wrapper/gradle-wrapper.properties
+# integration-tests/gradle/gradlew
+# integration-tests/gradle/gradlew.bat
+# Please commit your changes or stash them before you switch branches.
+
+GRADLE_TEMP="$(mktemp -d)"
+trap 'rm -rf "${GRADLE_TEMP}"' EXIT
+
+# The Gradle tests need the pom.xml only to read its version number.
+# (And the file needs to be two directory levels up from the Gradle build file.)
+# TODO(cpovirk): Find a better way to give them that information.
+cp pom.xml "${GRADLE_TEMP}"
+
+for version in 5.6.4 7.0.2; do
+ # Enter a subshell so that we return to the current directory afterward.
+ (
+ cp -r integration-tests "${GRADLE_TEMP}/${version}"
+ cd "${GRADLE_TEMP}/${version}/gradle"
+ ./gradlew wrapper --gradle-version="${version}"
+ ./gradlew testClasspath
+ )
+done
diff --git a/util/set_version.sh b/util/set_version.sh
deleted file mode 100755
index 9db8c7ffa..000000000
--- a/util/set_version.sh
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/bin/bash
-
-set -eu
-
-if (( $# != 1 )); then
- echo "Usage: set_versions.sh <version>" >&2
- exit 1
-fi
-
-version="$1"
-
-mvn versions:set versions:commit -DnewVersion="${version}-jre"
-mvn versions:set versions:commit -DnewVersion="${version}-android" -f android
-git commit -am "Set version numbers to ${version}"