1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14
15package com.google.common.collect;
16
17import static com.google.common.base.Preconditions.checkArgument;
18import static com.google.common.base.Preconditions.checkNotNull;
19import static com.google.common.collect.BoundType.CLOSED;
20
21import com.google.common.annotations.GwtCompatible;
22import com.google.common.annotations.GwtIncompatible;
23
24import java.io.Serializable;
25import java.util.Collection;
26
27import javax.annotation.Nullable;
28
29/**
30 * An implementation of {@link ContiguousSet} that contains one or more elements.
31 *
32 * @author Gregory Kick
33 */
34@GwtCompatible(emulated = true)
35@SuppressWarnings("unchecked") // allow ungenerified Comparable types
36final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> {
37  private final Range<C> range;
38
39  RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) {
40    super(domain);
41    this.range = range;
42  }
43
44  // Abstract method doesn't exist in GWT emulation
45  /* @Override */ ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) {
46    return range.intersection(Ranges.upTo(toElement, BoundType.forBoolean(inclusive)))
47        .asSet(domain);
48  }
49
50  // Abstract method doesn't exist in GWT emulation
51  /* @Override */ int indexOf(Object target) {
52    return contains(target) ? (int) domain.distance(first(), (C) target) : -1;
53  }
54
55  // Abstract method doesn't exist in GWT emulation
56  /* @Override */ ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement,
57      boolean toInclusive) {
58    return range.intersection(Ranges.range(fromElement, BoundType.forBoolean(fromInclusive),
59        toElement, BoundType.forBoolean(toInclusive))).asSet(domain);
60  }
61
62  // Abstract method doesn't exist in GWT emulation
63  /* @Override */ ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) {
64    return range.intersection(Ranges.downTo(fromElement, BoundType.forBoolean(inclusive)))
65        .asSet(domain);
66  }
67
68  @Override public UnmodifiableIterator<C> iterator() {
69    return new AbstractLinkedIterator<C>(first()) {
70      final C last = last();
71
72      @Override
73      protected C computeNext(C previous) {
74        return equalsOrThrow(previous, last) ? null : domain.next(previous);
75      }
76    };
77  }
78
79  private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) {
80    return right != null && Range.compareOrThrow(left, right) == 0;
81  }
82
83  @Override boolean isPartialView() {
84    return false;
85  }
86
87  @Override public C first() {
88    return range.lowerBound.leastValueAbove(domain);
89  }
90
91  @Override public C last() {
92    return range.upperBound.greatestValueBelow(domain);
93  }
94
95  @Override public int size() {
96    long distance = domain.distance(first(), last());
97    return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1;
98  }
99
100  @Override public boolean contains(Object object) {
101    try {
102      return range.contains((C) object);
103    } catch (ClassCastException e) {
104      return false;
105    }
106  }
107
108  @Override public boolean containsAll(Collection<?> targets) {
109    try {
110      return range.containsAll((Iterable<? extends C>) targets);
111    } catch (ClassCastException e) {
112      return false;
113    }
114  }
115
116  @Override public boolean isEmpty() {
117    return false;
118  }
119
120  // copied to make sure not to use the GWT-emulated version
121  @Override public Object[] toArray() {
122    return ObjectArrays.toArrayImpl(this);
123  }
124
125  // copied to make sure not to use the GWT-emulated version
126  @Override public <T> T[] toArray(T[] other) {
127    return ObjectArrays.toArrayImpl(this, other);
128  }
129
130  @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) {
131    checkNotNull(other);
132    checkArgument(this.domain.equals(other.domain));
133    if (other.isEmpty()) {
134      return other;
135    } else {
136      C lowerEndpoint = Ordering.natural().max(this.first(), other.first());
137      C upperEndpoint = Ordering.natural().min(this.last(), other.last());
138      return (lowerEndpoint.compareTo(upperEndpoint) < 0)
139          ? Ranges.closed(lowerEndpoint, upperEndpoint).asSet(domain)
140          : new EmptyContiguousSet<C>(domain);
141    }
142  }
143
144  @Override public Range<C> range() {
145    return range(CLOSED, CLOSED);
146  }
147
148  @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) {
149    return Ranges.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain),
150        range.upperBound.withUpperBoundType(upperBoundType, domain));
151  }
152
153  @Override public boolean equals(Object object) {
154    if (object == this) {
155      return true;
156    } else if (object instanceof RegularContiguousSet<?>) {
157      RegularContiguousSet<?> that = (RegularContiguousSet<?>) object;
158      if (this.domain.equals(that.domain)) {
159        return this.first().equals(that.first())
160            && this.last().equals(that.last());
161      }
162    }
163    return super.equals(object);
164  }
165
166  // copied to make sure not to use the GWT-emulated version
167  @Override public int hashCode() {
168    return Sets.hashCodeImpl(this);
169  }
170
171  @GwtIncompatible("serialization")
172  private static final class SerializedForm<C extends Comparable> implements Serializable {
173    final Range<C> range;
174    final DiscreteDomain<C> domain;
175
176    private SerializedForm(Range<C> range, DiscreteDomain<C> domain) {
177      this.range = range;
178      this.domain = domain;
179    }
180
181    private Object readResolve() {
182      return new RegularContiguousSet<C>(range, domain);
183    }
184  }
185
186  @GwtIncompatible("serialization")
187  @Override Object writeReplace() {
188    return new SerializedForm<C>(range, domain);
189  }
190
191  private static final long serialVersionUID = 0;
192}
193