01: // Copyright (c) 2001 Per M.A. Bothner and Brainfood Inc.
02: // This is free software; for terms and warranty disclaimer see ./COPYING.
03:
04: package gnu.xquery.util;
05:
06: import gnu.mapping.*;
07: import gnu.lists.*;
08:
09: /** Extracts a sub-range from a value sequence.
10: * Implements XQuery 'sublist'. */
11:
12: public class SubList extends MethodProc {
13: public static final SubList subList = new SubList();
14:
15: public int numArgs() {
16: return 0x3002;
17: }
18:
19: public static void subList(Object seq, double start, double end,
20: Consumer out) {
21: if (seq instanceof Values) {
22: Values vals = (Values) seq;
23: int n = 0;
24: int i = 0;
25: while (++n < start) {
26: i = vals.nextDataIndex(i);
27: if (i < 0)
28: return;
29: }
30: int startPosition = i;
31: int endPosition = i;
32: while (n++ < end) {
33: i = vals.nextDataIndex(i);
34: if (i < 0)
35: break;
36: endPosition = i;
37: }
38: vals.consumeIRange(startPosition, endPosition, out);
39: } else {
40: if (start <= 1 && end >= 2)
41: out.writeObject(seq);
42: }
43: }
44:
45: public void apply(CallContext ctx) {
46: Consumer consumer = ctx.consumer;
47: Object seq = ctx.getNextArg();
48: double d1 = Math.round(StringUtils.asDouble(ctx.getNextArg()));
49: Object eof = Sequence.eofValue;
50: Object arg2 = ctx.getNextArg(eof);
51: ctx.lastArg();
52: double d2 = arg2 != eof ? Math
53: .round(StringUtils.asDouble(arg2))
54: : Double.POSITIVE_INFINITY;
55: subList(seq, d1, d1 + d2, consumer);
56: }
57: }
|