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