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