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