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 * https://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
18 package org.apache.commons.text;
19
20 import java.io.Reader;
21
22 /**
23 * A Reader that, upon reading, inspects the char array it has been given access to (positions beyond offset+len that may contain stale data), records them,
24 * then supplies its normal data.
25 */
26 class SpyReader extends Reader {
27
28 private boolean done;
29 private char[] observedExtra;
30 private final char[] supply;
31
32 SpyReader(final String supply) {
33 this.supply = supply.toCharArray();
34 }
35
36 @Override
37 public void close() {
38 // empty
39 }
40
41 boolean observedStaleChars(final String marker) {
42 if (observedExtra == null) {
43 return false;
44 }
45 return new String(observedExtra).contains(marker);
46 }
47
48 @Override
49 public int read(final char[] cbuf, final int off, final int len) {
50 if (done) {
51 return -1;
52 }
53 done = true;
54 // Record chars in the buffer beyond where we will write
55 final int toWrite = Math.min(supply.length, len);
56 final int staleStart = off + toWrite;
57 final int staleLen = cbuf.length - staleStart;
58 if (staleLen > 0) {
59 observedExtra = new char[staleLen];
60 System.arraycopy(cbuf, staleStart, observedExtra, 0, staleLen);
61 }
62 System.arraycopy(supply, 0, cbuf, off, toWrite);
63 return toWrite;
64 }
65 }