PageRenderTime 45ms CodeModel.GetById 29ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/src/com/google/appengine/datanucleus/query/SlicingIterable.java

http://datanucleus-appengine.googlecode.com/
Java | 61 lines | 34 code | 6 blank | 21 comment | 6 complexity | e98fdaafa2b65ac1e3ebe43589c1d46d MD5 | raw file
 1/**********************************************************************
 2Copyright (c) 2009 Google Inc.
 3
 4Licensed under the Apache License, Version 2.0 (the "License");
 5you may not use this file except in compliance with the License.
 6You may obtain a copy of the License at
 7
 8http://www.apache.org/licenses/LICENSE-2.0
 9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15**********************************************************************/
16package com.google.appengine.datanucleus.query;
17
18import java.util.Iterator;
19
20/**
21 * Produces {@link Iterator Iterators} that respect the provided
22 * offset and limit.
23 *
24 * @author Max Ross <maxr@google.com>
25 */
26class SlicingIterable<T> implements Iterable<T> {
27
28  private final int offset;
29  private final Integer limit;
30  private final Iterable<T> data;
31
32  SlicingIterable(int offset, Integer limit, Iterable<T> data) {
33    this.offset = offset;
34    this.limit = limit;
35    this.data = data;
36  }
37
38  public Iterator<T> iterator() {
39    return new AbstractIterator<T>() {
40      private int remainingOffset = offset;
41      private Integer numEntitiesReturned = 0;
42      private final Iterator<T> iter = data.iterator();
43
44      protected T computeNext() {
45        if (numEntitiesReturned.equals(limit)) {
46          endOfData();
47        }
48        T next = null;
49        while (iter.hasNext() && remainingOffset-- >= 0) {
50          next = iter.next();
51        }
52        if (remainingOffset >= 0 || next == null) {
53          endOfData();
54        }
55        remainingOffset = 0;
56        numEntitiesReturned++;
57        return next;
58      }
59    };
60  }
61}