| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.om; |
| 9 | |
| 10 | import net.sf.saxon.trans.XPathException; |
| 11 | |
| 12 | /** |
| 13 | * A sequence that wraps an iterator, without being materialized. It can only be used once. |
| 14 | */ |
| 15 | public class LazySequence<T extends Item<?>> implements Sequence<T> { |
| 16 | |
| 17 | SequenceIterator<T> iterator; |
| 18 | boolean used = false; |
| 19 | |
| 20 | /** |
| 21 | * Create a virtual sequence backed by an iterator |
| 22 | * @param iterator the iterator that delivers the items in the sequence |
| 23 | */ |
| 24 | |
| 25 | public LazySequence(SequenceIterator<T> iterator) { |
| 26 | this.iterator = iterator; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Get the first item in the sequence. This calls iterate() internally, which means it can only |
| 31 | * be called once; the method should only be used if the client requires only the first item in |
| 32 | * the sequence (or knows that the sequence has length one). |
| 33 | * @return the first item, or null if the sequence is empty |
| 34 | * @throws XPathException if an error occurs evaluating the underlying expression |
| 35 | */ |
| 36 | |
| 37 | public T head() throws XPathException { |
| 38 | return iterate().next(); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Iterate over all the items in the sequence. The first time this is called it returns the original |
| 43 | * iterator backing the sequence. On subsequent calls it clones the original iterator. |
| 44 | * @return an iterator over the items in the sequence |
| 45 | * @throws XPathException if evaluation of the iterator fails. |
| 46 | * @throws IllegalStateException if iterate() has already been called |
| 47 | */ |
| 48 | |
| 49 | public synchronized SequenceIterator<T> iterate() throws XPathException { |
| 50 | if (used) { |
| 51 | throw new IllegalStateException("A LazySequence can only be read once"); |
| 52 | } else { |
| 53 | used = true; |
| 54 | return iterator; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | @Override |
| 59 | public Sequence<T> makeRepeatable() throws XPathException { |
| 60 | return materialize(); |
| 61 | } |
| 62 | } |
| 63 |