01: // Copyright (c) 2001, 2003, 2006 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.lists.*;
07: import gnu.math.IntNum;
08: import gnu.mapping.*;
09: import gnu.kawa.xml.KNode;
10: import gnu.kawa.xml.UntypedAtomic;
11:
12: public class IntegerRange extends MethodProc // implements Inlineable
13: {
14: public static final IntegerRange integerRange = new IntegerRange(
15: "to");
16:
17: public IntegerRange(String name) {
18: setName(name);
19: }
20:
21: public static final IntNum MIN_INT = IntNum.make(Integer.MIN_VALUE);
22: public static final IntNum MAX_INT = IntNum.make(Integer.MAX_VALUE);
23:
24: /*
25: public static void integerRange(int first, int last, Consumer out)
26: {
27: int step = first > last ? -1 : 1;
28: for (;;)
29: {
30: out.writeInt(first);
31: if (first == last)
32: break;
33: first += step;
34: }
35: }
36: */
37:
38: public static void integerRange(IntNum first, IntNum last,
39: Consumer out) {
40: if (IntNum.compare(first, MIN_INT) >= 0
41: && IntNum.compare(last, MAX_INT) <= 0) {
42: int fst = first.intValue();
43: int lst = last.intValue();
44: if (fst <= lst) {
45: for (;;) {
46: out.writeInt(fst);
47: if (fst == lst)
48: break;
49: fst++;
50: }
51: }
52: return;
53: }
54: while (IntNum.compare(first, last) <= 0) {
55: out.writeObject(first);
56: first = IntNum.add(first, 1);
57: }
58: }
59:
60: public void apply(CallContext ctx) {
61: Consumer consumer = ctx.consumer;
62: Object first = ctx.getNextArg();
63: Object last = ctx.getNextArg();
64: ctx.lastArg();
65: first = KNode.atomicValue(first);
66: last = KNode.atomicValue(last);
67: if (first == Values.empty || first == null
68: || last == Values.empty || last == null)
69: return;
70: if (first instanceof UntypedAtomic)
71: first = IntNum.valueOf(first.toString().trim(), 10);
72: if (last instanceof UntypedAtomic)
73: last = IntNum.valueOf(last.toString().trim(), 10);
74: integerRange((IntNum) first, (IntNum) last, ctx.consumer);
75: }
76: }
|