summaryrefslogtreecommitdiff
path: root/android_icu4j/src/main/java/android/icu/message2/InputSource.java
blob: 7122486e81333d465dc69e33830f4ce1677167e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/* GENERATED SOURCE. DO NOT MODIFY. */
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: https://www.unicode.org/copyright.html

package android.icu.message2;

class InputSource {
    final String buffer;

    private int cursor;
    private int lastReadCursor = -1;
    private int lastReadCount = 0;

    InputSource(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input string should not be null");
        }
        this.buffer = input;
        this.cursor = 0;
    }

    boolean atEnd() {
        return cursor >= buffer.length();
    }

    int peekChar() {
        if (atEnd()) {
            return -1;
        }
        return buffer.charAt(cursor);
    }

    int readCodePoint() {
        // TODO: remove this?
        // START Detect possible infinite loop
        if (lastReadCursor != cursor) {
            lastReadCursor = cursor;
            lastReadCount = 1;
        } else {
            lastReadCount++;
            if (lastReadCount >= 10) {
                throw new RuntimeException("Stuck in a loop!");
            }
        }
        // END Detect possible infinite loop

        if (atEnd()) {
            return -1;
        }

        char c = buffer.charAt(cursor++);
        if (Character.isHighSurrogate(c)) {
            if (!atEnd()) {
                char c2 = buffer.charAt(cursor++);
                if (Character.isLowSurrogate(c2)) {
                    return Character.toCodePoint(c, c2);
                } else { // invalid, high surrogate followed by non-surrogate
                    cursor--;
                    return c;
                }
            }
        }
        return c;
    }

    // Backup a number of characters.
    void backup(int amount) {
        // TODO: validate
        cursor -= amount;
    }

    int getPosition() {
        return cursor;
    }

    void skip(int amount) {
        // TODO: validate
        cursor += amount;
    }

    void gotoPosition(int position) {
        // TODO: validate
        cursor = position;
    }
}