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