KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > xquery > util > IntegerRange


1 // Copyright (c) 2001, 2003, 2006 Per M.A. Bothner and Brainfood Inc.
2
// This is free software; for terms and warranty disclaimer see ./COPYING.
3

4 package gnu.xquery.util;
5 import gnu.lists.*;
6 import gnu.math.IntNum;
7 import gnu.mapping.*;
8 import gnu.kawa.xml.KNode;
9 import gnu.kawa.xml.UntypedAtomic;
10
11 public class IntegerRange extends MethodProc // implements Inlineable
12
{
13   public static final IntegerRange integerRange = new IntegerRange("to");
14
15   public IntegerRange(String JavaDoc name)
16   {
17     setName(name);
18   }
19
20   public static final IntNum MIN_INT = IntNum.make(Integer.MIN_VALUE);
21   public static final IntNum MAX_INT = IntNum.make(Integer.MAX_VALUE);
22
23   /*
24   public static void integerRange(int first, int last, Consumer out)
25   {
26     int step = first > last ? -1 : 1;
27     for (;;)
28       {
29     out.writeInt(first);
30     if (first == last)
31       break;
32     first += step;
33       }
34   }
35   */

36
37   public static void integerRange(IntNum first, IntNum last, Consumer out)
38   {
39     if (IntNum.compare(first, MIN_INT) >= 0
40     && IntNum.compare(last, MAX_INT) <= 0)
41       {
42     int fst = first.intValue();
43     int lst = last.intValue();
44     if (fst <= lst)
45       {
46         for (;;)
47           {
48         out.writeInt(fst);
49         if (fst == lst)
50           break;
51         fst++;
52           }
53       }
54     return;
55       }
56     while (IntNum.compare(first, last) <= 0)
57       {
58     out.writeObject(first);
59     first = IntNum.add(first, 1);
60       }
61   }
62
63   public void apply (CallContext ctx)
64   {
65     Consumer consumer = ctx.consumer;
66     Object JavaDoc first = ctx.getNextArg();
67     Object JavaDoc last = ctx.getNextArg();
68     ctx.lastArg();
69     first = KNode.atomicValue(first);
70     last = KNode.atomicValue(last);
71     if (first == Values.empty || first == null
72         || last == Values.empty || last == null)
73       return;
74     if (first instanceof UntypedAtomic)
75       first = IntNum.valueOf(first.toString().trim(), 10);
76     if (last instanceof UntypedAtomic)
77       last = IntNum.valueOf(last.toString().trim(), 10);
78     integerRange((IntNum) first, (IntNum) last, ctx.consumer);
79   }
80 }
81
Popular Tags