View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.data.pipeline.core.util;
19  
20  import org.apache.commons.lang3.Range;
21  
22  import java.math.BigInteger;
23  import java.util.Iterator;
24  import java.util.NoSuchElementException;
25  
26  /**
27   * Interval to range iterator.
28   * <p>
29   * It's not thread-safe.
30   * </p>
31   */
32  public final class IntervalToRangeIterator implements Iterator<Range<Long>> {
33      
34      private final BigInteger maximum;
35      
36      private final BigInteger interval;
37      
38      private BigInteger current;
39      
40      public IntervalToRangeIterator(final long minimum, final long maximum, final long interval) {
41          if (minimum > maximum) {
42              throw new IllegalArgumentException("minimum greater than maximum");
43          }
44          if (interval < 0L) {
45              throw new IllegalArgumentException("interval is less than zero");
46          }
47          this.maximum = BigInteger.valueOf(maximum);
48          this.interval = BigInteger.valueOf(interval);
49          this.current = BigInteger.valueOf(minimum);
50      }
51      
52      @Override
53      public boolean hasNext() {
54          return current.compareTo(maximum) <= 0;
55      }
56      
57      @Override
58      public Range<Long> next() {
59          if (!hasNext()) {
60              throw new NoSuchElementException("");
61          }
62          BigInteger upperLimit = min(maximum, current.add(interval));
63          Range<Long> result = Range.between(current.longValue(), upperLimit.longValue());
64          current = upperLimit.add(BigInteger.ONE);
65          return result;
66      }
67      
68      private BigInteger min(final BigInteger one, final BigInteger another) {
69          return one.compareTo(another) < 0 ? one : another;
70      }
71  }