001/* 002 * Copyright (C) 2012 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.collect; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkElementIndex; 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.collect.Maps.immutableEntry; 021import static java.util.Collections.sort; 022 023import com.google.common.annotations.GwtIncompatible; 024import com.google.common.annotations.J2ktIncompatible; 025import com.google.common.collect.SortedLists.KeyAbsentBehavior; 026import com.google.common.collect.SortedLists.KeyPresentBehavior; 027import com.google.errorprone.annotations.CanIgnoreReturnValue; 028import com.google.errorprone.annotations.DoNotCall; 029import com.google.errorprone.annotations.DoNotMock; 030import java.io.InvalidObjectException; 031import java.io.ObjectInputStream; 032import java.io.Serializable; 033import java.util.List; 034import java.util.Map; 035import java.util.Map.Entry; 036import java.util.NoSuchElementException; 037import java.util.function.Function; 038import java.util.stream.Collector; 039import org.jspecify.annotations.Nullable; 040 041/** 042 * A {@link RangeMap} whose contents will never change, with many other important properties 043 * detailed at {@link ImmutableCollection}. 044 * 045 * @author Louis Wasserman 046 * @since 14.0 047 */ 048@GwtIncompatible // NavigableMap 049public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K, V>, Serializable { 050 051 private static final ImmutableRangeMap<Comparable<?>, Object> EMPTY = 052 new ImmutableRangeMap<>(ImmutableList.<Range<Comparable<?>>>of(), ImmutableList.of()); 053 054 /** 055 * Returns a {@code Collector} that accumulates the input elements into a new {@code 056 * ImmutableRangeMap}. As in {@link Builder}, overlapping ranges are not permitted. 057 * 058 * @since 33.2.0 (available since 23.1 in guava-jre) 059 */ 060 @SuppressWarnings("Java7ApiChecker") 061 @IgnoreJRERequirement // Users will use this only if they're already using streams. 062 public static <T extends @Nullable Object, K extends Comparable<? super K>, V> 063 Collector<T, ?, ImmutableRangeMap<K, V>> toImmutableRangeMap( 064 Function<? super T, Range<K>> keyFunction, 065 Function<? super T, ? extends V> valueFunction) { 066 return CollectCollectors.toImmutableRangeMap(keyFunction, valueFunction); 067 } 068 069 /** 070 * Returns an empty immutable range map. 071 * 072 * <p><b>Performance note:</b> the instance returned is a singleton. 073 */ 074 @SuppressWarnings("unchecked") 075 public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of() { 076 return (ImmutableRangeMap<K, V>) EMPTY; 077 } 078 079 /** Returns an immutable range map mapping a single range to a single value. */ 080 public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of(Range<K> range, V value) { 081 return new ImmutableRangeMap<>(ImmutableList.of(range), ImmutableList.of(value)); 082 } 083 084 @SuppressWarnings("unchecked") 085 public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> copyOf( 086 RangeMap<K, ? extends V> rangeMap) { 087 if (rangeMap instanceof ImmutableRangeMap) { 088 return (ImmutableRangeMap<K, V>) rangeMap; 089 } 090 Map<Range<K>, ? extends V> map = rangeMap.asMapOfRanges(); 091 ImmutableList.Builder<Range<K>> rangesBuilder = new ImmutableList.Builder<>(map.size()); 092 ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<>(map.size()); 093 for (Entry<Range<K>, ? extends V> entry : map.entrySet()) { 094 rangesBuilder.add(entry.getKey()); 095 valuesBuilder.add(entry.getValue()); 096 } 097 return new ImmutableRangeMap<>(rangesBuilder.build(), valuesBuilder.build()); 098 } 099 100 /** Returns a new builder for an immutable range map. */ 101 public static <K extends Comparable<?>, V> Builder<K, V> builder() { 102 return new Builder<>(); 103 } 104 105 /** 106 * A builder for immutable range maps. Overlapping ranges are prohibited. 107 * 108 * @since 14.0 109 */ 110 @DoNotMock 111 public static final class Builder<K extends Comparable<?>, V> { 112 private final List<Entry<Range<K>, V>> entries; 113 114 public Builder() { 115 this.entries = Lists.newArrayList(); 116 } 117 118 /** 119 * Associates the specified range with the specified value. 120 * 121 * @throws IllegalArgumentException if {@code range} is empty 122 */ 123 @CanIgnoreReturnValue 124 public Builder<K, V> put(Range<K> range, V value) { 125 checkNotNull(range); 126 checkNotNull(value); 127 checkArgument(!range.isEmpty(), "Range must not be empty, but was %s", range); 128 entries.add(immutableEntry(range, value)); 129 return this; 130 } 131 132 /** Copies all associations from the specified range map into this builder. */ 133 @CanIgnoreReturnValue 134 public Builder<K, V> putAll(RangeMap<K, ? extends V> rangeMap) { 135 for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) { 136 put(entry.getKey(), entry.getValue()); 137 } 138 return this; 139 } 140 141 @CanIgnoreReturnValue 142 Builder<K, V> combine(Builder<K, V> builder) { 143 entries.addAll(builder.entries); 144 return this; 145 } 146 147 /** 148 * Returns an {@code ImmutableRangeMap} containing the associations previously added to this 149 * builder. 150 * 151 * @throws IllegalArgumentException if any two ranges inserted into this builder overlap 152 */ 153 public ImmutableRangeMap<K, V> build() { 154 sort(entries, Range.<K>rangeLexOrdering().onKeys()); 155 ImmutableList.Builder<Range<K>> rangesBuilder = new ImmutableList.Builder<>(entries.size()); 156 ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<>(entries.size()); 157 for (int i = 0; i < entries.size(); i++) { 158 Range<K> range = entries.get(i).getKey(); 159 if (i > 0) { 160 Range<K> prevRange = entries.get(i - 1).getKey(); 161 if (range.isConnected(prevRange) && !range.intersection(prevRange).isEmpty()) { 162 throw new IllegalArgumentException( 163 "Overlapping ranges: range " + prevRange + " overlaps with entry " + range); 164 } 165 } 166 rangesBuilder.add(range); 167 valuesBuilder.add(entries.get(i).getValue()); 168 } 169 return new ImmutableRangeMap<>(rangesBuilder.build(), valuesBuilder.build()); 170 } 171 } 172 173 private final transient ImmutableList<Range<K>> ranges; 174 private final transient ImmutableList<V> values; 175 176 ImmutableRangeMap(ImmutableList<Range<K>> ranges, ImmutableList<V> values) { 177 this.ranges = ranges; 178 this.values = values; 179 } 180 181 @Override 182 public @Nullable V get(K key) { 183 int index = 184 SortedLists.binarySearch( 185 ranges, 186 Range::lowerBound, 187 Cut.belowValue(key), 188 KeyPresentBehavior.ANY_PRESENT, 189 KeyAbsentBehavior.NEXT_LOWER); 190 if (index == -1) { 191 return null; 192 } else { 193 Range<K> range = ranges.get(index); 194 return range.contains(key) ? values.get(index) : null; 195 } 196 } 197 198 @Override 199 public @Nullable Entry<Range<K>, V> getEntry(K key) { 200 int index = 201 SortedLists.binarySearch( 202 ranges, 203 Range::lowerBound, 204 Cut.belowValue(key), 205 KeyPresentBehavior.ANY_PRESENT, 206 KeyAbsentBehavior.NEXT_LOWER); 207 if (index == -1) { 208 return null; 209 } else { 210 Range<K> range = ranges.get(index); 211 return range.contains(key) ? immutableEntry(range, values.get(index)) : null; 212 } 213 } 214 215 @Override 216 public Range<K> span() { 217 if (ranges.isEmpty()) { 218 throw new NoSuchElementException(); 219 } 220 Range<K> firstRange = ranges.get(0); 221 Range<K> lastRange = ranges.get(ranges.size() - 1); 222 return Range.create(firstRange.lowerBound, lastRange.upperBound); 223 } 224 225 /** 226 * Guaranteed to throw an exception and leave the {@code RangeMap} unmodified. 227 * 228 * @throws UnsupportedOperationException always 229 * @deprecated Unsupported operation. 230 */ 231 @Deprecated 232 @Override 233 @DoNotCall("Always throws UnsupportedOperationException") 234 public final void put(Range<K> range, V value) { 235 throw new UnsupportedOperationException(); 236 } 237 238 /** 239 * Guaranteed to throw an exception and leave the {@code RangeMap} unmodified. 240 * 241 * @throws UnsupportedOperationException always 242 * @deprecated Unsupported operation. 243 */ 244 @Deprecated 245 @Override 246 @DoNotCall("Always throws UnsupportedOperationException") 247 public final void putCoalescing(Range<K> range, V value) { 248 throw new UnsupportedOperationException(); 249 } 250 251 /** 252 * Guaranteed to throw an exception and leave the {@code RangeMap} unmodified. 253 * 254 * @throws UnsupportedOperationException always 255 * @deprecated Unsupported operation. 256 */ 257 @Deprecated 258 @Override 259 @DoNotCall("Always throws UnsupportedOperationException") 260 public final void putAll(RangeMap<K, ? extends V> rangeMap) { 261 throw new UnsupportedOperationException(); 262 } 263 264 /** 265 * Guaranteed to throw an exception and leave the {@code RangeMap} unmodified. 266 * 267 * @throws UnsupportedOperationException always 268 * @deprecated Unsupported operation. 269 */ 270 @Deprecated 271 @Override 272 @DoNotCall("Always throws UnsupportedOperationException") 273 public final void clear() { 274 throw new UnsupportedOperationException(); 275 } 276 277 /** 278 * Guaranteed to throw an exception and leave the {@code RangeMap} unmodified. 279 * 280 * @throws UnsupportedOperationException always 281 * @deprecated Unsupported operation. 282 */ 283 @Deprecated 284 @Override 285 @DoNotCall("Always throws UnsupportedOperationException") 286 public final void remove(Range<K> range) { 287 throw new UnsupportedOperationException(); 288 } 289 290 @Override 291 public ImmutableMap<Range<K>, V> asMapOfRanges() { 292 if (ranges.isEmpty()) { 293 return ImmutableMap.of(); 294 } 295 RegularImmutableSortedSet<Range<K>> rangeSet = 296 new RegularImmutableSortedSet<>(ranges, Range.<K>rangeLexOrdering()); 297 return new ImmutableSortedMap<>(rangeSet, values); 298 } 299 300 @Override 301 public ImmutableMap<Range<K>, V> asDescendingMapOfRanges() { 302 if (ranges.isEmpty()) { 303 return ImmutableMap.of(); 304 } 305 RegularImmutableSortedSet<Range<K>> rangeSet = 306 new RegularImmutableSortedSet<>(ranges.reverse(), Range.<K>rangeLexOrdering().reverse()); 307 return new ImmutableSortedMap<>(rangeSet, values.reverse()); 308 } 309 310 @Override 311 public ImmutableRangeMap<K, V> subRangeMap(final Range<K> range) { 312 if (checkNotNull(range).isEmpty()) { 313 return ImmutableRangeMap.of(); 314 } else if (ranges.isEmpty() || range.encloses(span())) { 315 return this; 316 } 317 int lowerIndex = 318 SortedLists.binarySearch( 319 ranges, 320 Range::upperBound, 321 range.lowerBound, 322 KeyPresentBehavior.FIRST_AFTER, 323 KeyAbsentBehavior.NEXT_HIGHER); 324 int upperIndex = 325 SortedLists.binarySearch( 326 ranges, 327 Range::lowerBound, 328 range.upperBound, 329 KeyPresentBehavior.ANY_PRESENT, 330 KeyAbsentBehavior.NEXT_HIGHER); 331 if (lowerIndex >= upperIndex) { 332 return ImmutableRangeMap.of(); 333 } 334 final int off = lowerIndex; 335 final int len = upperIndex - lowerIndex; 336 ImmutableList<Range<K>> subRanges = 337 new ImmutableList<Range<K>>() { 338 @Override 339 public int size() { 340 return len; 341 } 342 343 @Override 344 public Range<K> get(int index) { 345 checkElementIndex(index, len); 346 if (index == 0 || index == len - 1) { 347 return ranges.get(index + off).intersection(range); 348 } else { 349 return ranges.get(index + off); 350 } 351 } 352 353 @Override 354 boolean isPartialView() { 355 return true; 356 } 357 358 // redeclare to help optimizers with b/310253115 359 @SuppressWarnings("RedundantOverride") 360 @Override 361 @J2ktIncompatible // serialization 362 Object writeReplace() { 363 return super.writeReplace(); 364 } 365 }; 366 final ImmutableRangeMap<K, V> outer = this; 367 return new ImmutableRangeMap<K, V>(subRanges, values.subList(lowerIndex, upperIndex)) { 368 @Override 369 public ImmutableRangeMap<K, V> subRangeMap(Range<K> subRange) { 370 if (range.isConnected(subRange)) { 371 return outer.subRangeMap(subRange.intersection(range)); 372 } else { 373 return ImmutableRangeMap.of(); 374 } 375 } 376 377 // redeclare to help optimizers with b/310253115 378 @SuppressWarnings("RedundantOverride") 379 @Override 380 @J2ktIncompatible // serialization 381 Object writeReplace() { 382 return super.writeReplace(); 383 } 384 }; 385 } 386 387 @Override 388 public int hashCode() { 389 return asMapOfRanges().hashCode(); 390 } 391 392 @Override 393 public boolean equals(@Nullable Object o) { 394 if (o instanceof RangeMap) { 395 RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o; 396 return asMapOfRanges().equals(rangeMap.asMapOfRanges()); 397 } 398 return false; 399 } 400 401 @Override 402 public String toString() { 403 return asMapOfRanges().toString(); 404 } 405 406 /** 407 * This class is used to serialize ImmutableRangeMap instances. Serializes the {@link 408 * #asMapOfRanges()} form. 409 */ 410 private static class SerializedForm<K extends Comparable<?>, V> implements Serializable { 411 412 private final ImmutableMap<Range<K>, V> mapOfRanges; 413 414 SerializedForm(ImmutableMap<Range<K>, V> mapOfRanges) { 415 this.mapOfRanges = mapOfRanges; 416 } 417 418 Object readResolve() { 419 if (mapOfRanges.isEmpty()) { 420 return of(); 421 } else { 422 return createRangeMap(); 423 } 424 } 425 426 Object createRangeMap() { 427 Builder<K, V> builder = new Builder<>(); 428 for (Entry<Range<K>, V> entry : mapOfRanges.entrySet()) { 429 builder.put(entry.getKey(), entry.getValue()); 430 } 431 return builder.build(); 432 } 433 434 private static final long serialVersionUID = 0; 435 } 436 437 Object writeReplace() { 438 return new SerializedForm<>(asMapOfRanges()); 439 } 440 441 @J2ktIncompatible // java.io.ObjectInputStream 442 private void readObject(ObjectInputStream stream) throws InvalidObjectException { 443 throw new InvalidObjectException("Use SerializedForm"); 444 } 445 446 private static final long serialVersionUID = 0; 447}