44996b92a8ffc1d14b65fce383296c83e4bdeb62
[vxquery.git] / vxquery-core / src / main / java / org / apache / vxquery / runtime / functions / strings / SubstringAfterCharacterIterator.java
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.vxquery.runtime.functions.strings;
18
19 public class SubstringAfterCharacterIterator implements ICharacterIterator {
20 private ICharacterIterator searchIterator;
21 private final UTF8StringCharacterIterator stringIterator;
22 private boolean found = false;
23
24 public SubstringAfterCharacterIterator(UTF8StringCharacterIterator stringIterator) {
25 this.stringIterator = stringIterator;
26 }
27
28 public void setSearch(ICharacterIterator searchIterator) {
29 this.searchIterator = searchIterator;
30 }
31
32 @Override
33 public char next() {
34 int c1 = ICharacterIterator.EOS_CHAR;
35 if (!found) {
36 searchIterator.reset();
37 int currentByteOffset = 0;
38 boolean firstPass = true;
39 while (true) {
40 c1 = stringIterator.next();
41 int c2 = searchIterator.next();
42 if (firstPass) {
43 // Save character and location for next call.
44 currentByteOffset = stringIterator.getByteOffset();
45 firstPass = false;
46 }
47 if (c2 == ICharacterIterator.EOS_CHAR) {
48 // End of search string. Found the substring.
49 found = true;
50 break;
51 }
52 if (c1 == ICharacterIterator.EOS_CHAR) {
53 // End of string. Stop.
54 return (char) 0;
55 }
56 if (c1 != c2) {
57 // No match found. Move the next character.
58 searchIterator.reset();
59 stringIterator.setByteOffset(currentByteOffset);
60 firstPass = true;
61 }
62 }
63 }
64
65 if (c1 != ICharacterIterator.EOS_CHAR) {
66 return (char) c1;
67 }
68 return stringIterator.next();
69 }
70
71 @Override
72 public void reset() {
73 stringIterator.reset();
74 }
75 }

Copyright 2016, The Apache Software Foundation.