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