summaryrefslogtreecommitdiff
path: root/dicore3/command/src/main/java/io/dico/dicore/command/parameter/ArgumentBuffer.java
blob: aa69730a28c07c6f48d5b0f61d77579b629daddf (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package io.dico.dicore.command.parameter;

import io.dico.dicore.command.CommandException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * Buffer for the arguments.
 * Easy to traverse for the parser.
 */
public class ArgumentBuffer extends AbstractList<String> implements Iterator<String>, RandomAccess {
    private String[] array;
    private int cursor = 0; // index of the next return value
    private transient ArgumentBuffer unaffectingCopy = null; // see #getUnaffectingCopy()

    public ArgumentBuffer(String label, String[] args) {
        this(combine(label, args));
    }

    private static String[] combine(String label, String[] args) {
        String[] result;
        //if (args.length > 0 && "".equals(args[args.length - 1])) {
        //    // drop the last element of args if it is empty
        //    result = args;
        //} else {
        result = new String[args.length + 1];
        //}
        System.arraycopy(args, 0, result, 1, result.length - 1);
        result[0] = Objects.requireNonNull(label);
        return result;
    }

    /**
     * Constructs a new ArgumentBuffer using the given array, without copying it first.
     * None of the array its elements should be empty.
     *
     * @param array the array
     * @throws NullPointerException if the array or any of its elements are null
     */
    public ArgumentBuffer(String[] array) {
        for (String elem : array) {
            if (elem == null) throw new NullPointerException("ArgumentBuffer array element");
        }
        this.array = array;

    }

    public int getCursor() {
        return cursor;
    }

    public @NotNull ArgumentBuffer setCursor(int cursor) {
        if (cursor <= 0) {
            cursor = 0;
        } else if (size() <= cursor) {
            cursor = size();
        }
        this.cursor = cursor;
        return this;
    }

    @Override
    public int size() {
        return array.length;
    }

    @Override
    public @NotNull String get(int index) {
        return array[index];
    }

    public int nextIndex() {
        return cursor;
    }

    public int previousIndex() {
        return cursor - 1;
    }

    public int remainingElements() {
        return size() - nextIndex() - 1;
    }

    @Override
    public boolean hasNext() {
        return nextIndex() < size();
    }

    public boolean hasPrevious() {
        return 0 <= previousIndex();
    }

    /**
     * Unlike conventional ListIterator implementations, this returns null if there is no next element
     *
     * @return the next value, or null
     */
    @Override
    public @Nullable String next() {
        return hasNext() ? get(cursor++) : null;
    }

    public @NotNull String requireNext(String parameterName) throws CommandException {
        String next = next();
        if (next == null) {
            throw CommandException.missingArgument(parameterName);
        }
        return next;
    }

    // useful for completion code
    public @NotNull String nextOrEmpty() {
        return hasNext() ? get(cursor++) : "";
    }

    /**
     * Unlike conventional ListIterator implementations, this returns null if there is no previous element
     *
     * @return the previous value, or null
     */
    public @Nullable String previous() {
        return hasPrevious() ? get(--cursor) : null;
    }

    public @Nullable String peekNext() {
        return hasNext() ? get(cursor) : null;
    }

    public @Nullable String peekPrevious() {
        return hasPrevious() ? get(cursor - 1) : null;
    }

    public @NotNull ArgumentBuffer advance() {
        return advance(1);
    }

    public @NotNull ArgumentBuffer advance(int amount) {
        cursor = Math.min(Math.max(0, cursor + amount), size());
        return this;
    }

    public @NotNull ArgumentBuffer rewind() {
        return rewind(1);
    }

    public @NotNull ArgumentBuffer rewind(int amount) {
        return advance(-amount);
    }

    @NotNull String[] getArray() {
        return array;
    }

    public @NotNull String[] getArrayFromCursor() {
        return getArrayFromIndex(cursor);
    }

    public @NotNull String[] getArrayFromIndex(int index) {
        return Arrays.copyOfRange(array, index, array.length);
    }

    public @NotNull String getRawInput() {
        return String.join(" ", array);
    }

    public @NotNull String[] toArray() {
        return array.clone();
    }

    @Override
    public @NotNull Iterator<String> iterator() {
        return this;
    }

    @Override
    public @NotNull ListIterator<String> listIterator() {
        return new ListIterator<String>() {
            @Override
            public boolean hasNext() {
                return ArgumentBuffer.this.hasNext();
            }

            @Override
            public String next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return ArgumentBuffer.this.next();
            }

            @Override
            public boolean hasPrevious() {
                return ArgumentBuffer.this.hasPrevious();
            }

            @Override
            public String previous() {
                if (!hasPrevious()) {
                    throw new NoSuchElementException();
                }
                return ArgumentBuffer.this.previous();
            }

            @Override
            public int nextIndex() {
                return ArgumentBuffer.this.nextIndex();
            }

            @Override
            public int previousIndex() {
                return ArgumentBuffer.this.previousIndex();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

            @Override
            public void set(String s) {
                throw new UnsupportedOperationException();
            }

            @Override
            public void add(String s) {
                throw new UnsupportedOperationException();
            }
        };
    }

    public void dropTrailingEmptyElements() {
        int removeCount = 0;
        String[] array = this.array;
        for (int i = array.length - 1; i >= 0; i--) {
            if ("".equals(array[i])) {
                removeCount++;
            }
        }

        if (removeCount > 0) {
            String[] newArray = new String[array.length - removeCount];
            System.arraycopy(array, 0, newArray, 0, newArray.length);
            this.array = newArray;

            if (cursor > newArray.length) {
                cursor = newArray.length;
            }
        }
    }

    /**
     * Preprocess this argument buffer with the given preprocessor
     *
     * @param preProcessor preprocessor
     * @return a new ArgumentBuffer with processed contents. Might be this buffer if nothing changed.
     */
    public @NotNull ArgumentBuffer preprocessArguments(IArgumentPreProcessor preProcessor) {
        return preProcessor.process(this, -1);
    }

    /**
     * Allows a piece of code to traverse this buffer without modifying its cursor.
     * After this method has been called for the first time on this instance, if this method
     * or the {@link #clone()} method are called, the operation carried out on the prior result has finished.
     * As such, the same instance might be returned again.
     *
     * @return A view of this buffer that doesn't affect this buffer's cursor.
     */
    public ArgumentBuffer getUnaffectingCopy() {
        // the copy doesn't alter the cursor of this ArgumentBuffer when moved, but traverses the same array reference.
        // there is only ever one copy of an ArgumentBuffer, the cursor of which is updated on every call to this method.

        ArgumentBuffer unaffectingCopy = this.unaffectingCopy;
        if (unaffectingCopy == null) {
            this.unaffectingCopy = unaffectingCopy = new ArgumentBuffer(array);
        }
        unaffectingCopy.cursor = this.cursor;
        return unaffectingCopy;
    }

    @SuppressWarnings("MethodDoesntCallSuperMethod")
    public @NotNull ArgumentBuffer clone() {
        ArgumentBuffer result = getUnaffectingCopy();
        this.unaffectingCopy = null;
        return result;
    }

    @Override
    public String toString() {
        return String.format("ArgumentBuffer(size = %d, cursor = %d)", size(), getCursor());
    }

}