KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jruby > util > string > UcharIterator


1 package org.jruby.util.string;
2
3 /**
4  * UcharIterator - an Iterator on Unicode characters in a UTF-8 byte array.
5  *
6  * <p>A conventional Iterator, remove() is not supported, and there's an extra
7  * nextChar() method that returns a naked int as opposed to a wrapped Integer.
8  * </p>
9  *
10  * @see org.jruby.util.string.Ustr
11  */

12
13 public class UcharIterator implements java.util.Iterator JavaDoc, java.io.Serializable JavaDoc {
14     private static final long serialVersionUID = -2821982911687539515L;
15     private Ustr u;
16     private int next;
17     
18     /**
19      * Creates a new UcharIterator starting at an offset in a buffer.
20      *
21      * @param s the byte array containing UTF-8-encoded Unicode characters.
22      * @param offset how far into the array to start iterating.
23      */

24     public UcharIterator(byte[] s, int offset) {
25         u = new Ustr(s, offset);
26         u.prepareNext();
27         next = u.nextChar();
28     }
29     
30     /**
31      * Tests whether there are any more characters in the buffer.
32      *
33      * @return true or false depending on whether there are more characters.
34      */

35     public boolean hasNext() {
36         return (next != 0);
37     }
38     
39     /**
40      * Retrieve the next Unicode character from a UTF-8 byte buffer, wrapped
41      * in an Integer object. Throws NoSuchElementException if hasNext
42      * would return false.
43      *
44      * @return the next Unicode character as a java.lang.Integer
45      * @throws NoSuchElementException
46      */

47     public Object JavaDoc next() {
48         if (next == 0)
49             throw new java.util.NoSuchElementException JavaDoc("Ran off end of array");
50         Integer JavaDoc i = new Integer JavaDoc(next);
51         next = u.nextChar();
52         return i;
53     }
54     
55     /**
56      * Retrieve the next Unicode character from a UTF-8 byte buffer and return
57      * it as an int. Once the null-termination is hit, returns 0 as many times
58      * as you want to call it.
59      *
60      * @return the next Unicode character as an int, 0 on end-of-string.
61      */

62     public int nextChar() {
63         int i = next;
64         if (i != 0)
65             next = u.nextChar();
66         return i;
67     }
68     
69     /**
70      * Throws an UnsupportedOperationException.
71      *
72      * @throws UnsupportedOperationException
73      */

74     public void remove() {
75         throw new UnsupportedOperationException JavaDoc("UcharIterator doesn't remove");
76     }
77     
78 }
79
Popular Tags