| 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.functions; |
| 9 | |
| 10 | import net.sf.saxon.expr.XPathContext; |
| 11 | import net.sf.saxon.om.Item; |
| 12 | import net.sf.saxon.om.Sequence; |
| 13 | import net.sf.saxon.om.SequenceIterator; |
| 14 | import net.sf.saxon.trans.XPathException; |
| 15 | |
| 16 | |
| 17 | /** |
| 18 | * Implementation of aggregate functions such as sum() and avg() that supply a fold() function. Such |
| 19 | * functions are automatically streamable. |
| 20 | */ |
| 21 | public abstract class FoldingFunction extends SystemFunction { |
| 22 | |
| 23 | /** |
| 24 | * Create the Fold object which actually performs the evaluation. Must be implemented |
| 25 | * in every subclass. |
| 26 | * @param context the dynamic evaluation context |
| 27 | * @param additionalArguments the values of all arguments other than the first. |
| 28 | * @return the Fold object used to compute the function |
| 29 | * @throws XPathException if a dynamic error occurs |
| 30 | */ |
| 31 | |
| 32 | public abstract Fold getFold(XPathContext context, Sequence... additionalArguments) throws XPathException; |
| 33 | |
| 34 | /** |
| 35 | * Evaluate the expression |
| 36 | * |
| 37 | * @param context the dynamic evaluation context |
| 38 | * @param arguments the values of the arguments, supplied as Sequences |
| 39 | * @return the result of the evaluation, in the form of a Sequence |
| 40 | * @throws net.sf.saxon.trans.XPathException |
| 41 | * if a dynamic error occurs during the evaluation of the expression |
| 42 | */ |
| 43 | public Sequence<?> call(XPathContext context, Sequence[] arguments) throws XPathException { |
| 44 | Sequence[] additionalArgs = new Sequence[arguments.length - 1]; |
| 45 | System.arraycopy(arguments, 1, additionalArgs, 0, additionalArgs.length); |
| 46 | Fold fold = getFold(context, additionalArgs); |
| 47 | SequenceIterator iter = arguments[0].iterate(); |
| 48 | Item item; |
| 49 | while ((item = iter.next()) != null) { |
| 50 | fold.processItem(item); |
| 51 | if (fold.isFinished()) { |
| 52 | break; |
| 53 | } |
| 54 | } |
| 55 | return fold.result(); |
| 56 | } |
| 57 | |
| 58 | public String getStreamerName() { |
| 59 | return "Fold"; |
| 60 | } |
| 61 | } |
| 62 |