TracedBufferedReader.java 11.8 KB
Newer Older
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.iotdb.db.engine.modification.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * Copied from {@link java.io.BufferedReader}, trace the read position by modifying the fill()
 * method.
 */
public class TracedBufferedReader extends Reader {
  private Reader in;

  private char cb[];
  private int nChars, nextChar;

  private static final int INVALIDATED = -2;
  private static final int UNMARKED = -1;
  private int markedChar = UNMARKED;
  private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

  /** If the next character is a line feed, skip it */
  private boolean skipLF = false;

  /** The skipLF flag when the mark was set */
  private boolean markedSkipLF = false;

  private static int defaultCharBufferSize = 8192;
  private static int defaultExpectedLineLength = 80;

  /** the total bytes number already filled into cb */
  private long totalFilledBytesNum = 0;

  /**
   * Creates a buffering character-input stream that uses an input buffer of the specified size.
   *
   * @param in A Reader
   * @param sz Input-buffer size
   * @exception IllegalArgumentException If {@code sz <= 0}
   */
  public TracedBufferedReader(Reader in, int sz) {
    super(in);
69 70 71
    if (sz <= 0) {
      throw new IllegalArgumentException("Buffer size <= 0");
    }
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    this.in = in;
    cb = new char[sz];
    nextChar = nChars = 0;
  }

  /**
   * Creates a buffering character-input stream that uses a default-sized input buffer.
   *
   * @param in A Reader
   */
  public TracedBufferedReader(Reader in) {
    this(in, defaultCharBufferSize);
  }

  /** Checks to make sure that the stream has not been closed */
  private void ensureOpen() throws IOException {
88 89 90
    if (in == null) {
      throw new IOException("Stream closed");
    }
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
  }

  /** {@link BufferedReader#fill()} */
  private void fill() throws IOException {
    int dst;
    if (markedChar <= UNMARKED) {
      /* No mark */
      dst = 0;
    } else {
      /* Marked */
      int delta = nextChar - markedChar;
      if (delta >= readAheadLimit) {
        /* Gone past read-ahead limit: Invalidate mark */
        markedChar = INVALIDATED;
        readAheadLimit = 0;
        dst = 0;
      } else {
        if (readAheadLimit <= cb.length) {
          /* Shuffle in the current buffer */
          System.arraycopy(cb, markedChar, cb, 0, delta);
          markedChar = 0;
          dst = delta;
        } else {
          /* Reallocate buffer to accommodate read-ahead limit */
          char ncb[] = new char[readAheadLimit];
          System.arraycopy(cb, markedChar, ncb, 0, delta);
          cb = ncb;
          markedChar = 0;
          dst = delta;
        }
        nextChar = nChars = delta;
      }
    }

    int n;
    do {
      n = in.read(cb, dst, cb.length - dst);
    } while (n == 0);
    if (n > 0) {
      nChars = dst + n;
      nextChar = dst;
      totalFilledBytesNum = totalFilledBytesNum + n;
    }
  }

  /** {@link BufferedReader#read()} */
137
  @Override
138 139 140 141 142 143
  public int read() throws IOException {
    synchronized (lock) {
      ensureOpen();
      for (; ; ) {
        if (nextChar >= nChars) {
          fill();
144 145 146
          if (nextChar >= nChars) {
            return -1;
          }
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
        }
        if (skipLF) {
          skipLF = false;
          if (cb[nextChar] == '\n') {
            nextChar++;
            continue;
          }
        }
        return cb[nextChar++];
      }
    }
  }

  /** {@link BufferedReader#read1(char[], int, int)} */
  private int read1(char[] cbuf, int off, int len) throws IOException {
    if (nextChar >= nChars) {
      /* If the requested length is at least as large as the buffer, and
      if there is no mark/reset activity, and if line feeds are not
      being skipped, do not bother to copy the characters into the
      local buffer.  In this way buffered streams will cascade
      harmlessly. */
      if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
        return in.read(cbuf, off, len);
      }
      fill();
    }
173 174 175
    if (nextChar >= nChars) {
      return -1;
    }
176 177 178 179
    if (skipLF) {
      skipLF = false;
      if (cb[nextChar] == '\n') {
        nextChar++;
180 181 182 183 184 185
        if (nextChar >= nChars) {
          fill();
        }
        if (nextChar >= nChars) {
          return -1;
        }
186 187 188 189 190 191 192 193 194
      }
    }
    int n = Math.min(len, nChars - nextChar);
    System.arraycopy(cb, nextChar, cbuf, off, n);
    nextChar += n;
    return n;
  }

  /** {@link BufferedReader#read(char[], int, int)} */
195
  @Override
196 197 198 199 200 201 202 203 204 205 206 207 208 209
  public int read(char cbuf[], int off, int len) throws IOException {
    synchronized (lock) {
      ensureOpen();
      if ((off < 0)
          || (off > cbuf.length)
          || (len < 0)
          || ((off + len) > cbuf.length)
          || ((off + len) < 0)) {
        throw new IndexOutOfBoundsException();
      } else if (len == 0) {
        return 0;
      }

      int n = read1(cbuf, off, len);
210 211 212
      if (n <= 0) {
        return n;
      }
213 214
      while ((n < len) && in.ready()) {
        int n1 = read1(cbuf, off + n, len - n);
215 216 217
        if (n1 <= 0) {
          break;
        }
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        n += n1;
      }
      return n;
    }
  }

  /** {@link BufferedReader#readLine(boolean)} */
  String readLine(boolean ignoreLF) throws IOException {
    StringBuilder s = null;
    int startChar;

    synchronized (lock) {
      ensureOpen();
      boolean omitLF = ignoreLF || skipLF;

      bufferLoop:
      for (; ; ) {

236 237 238
        if (nextChar >= nChars) {
          fill();
        }
239 240
        if (nextChar >= nChars) {
          /* EOF */
241 242 243 244 245
          if (s != null && s.length() > 0) {
            return s.toString();
          } else {
            return null;
          }
246 247 248 249 250 251
        }
        boolean eol = false;
        char c = 0;
        int i;

        /* Skip a leftover '\n', if necessary */
252 253 254
        if (omitLF && (cb[nextChar] == '\n')) {
          nextChar++;
        }
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
        skipLF = false;
        omitLF = false;

        charLoop:
        for (i = nextChar; i < nChars; i++) {
          c = cb[i];
          if ((c == '\n') || (c == '\r')) {
            eol = true;
            break charLoop;
          }
        }

        startChar = nextChar;
        nextChar = i;

        if (eol) {
          String str;
          if (s == null) {
            str = new String(cb, startChar, i - startChar);
          } else {
            s.append(cb, startChar, i - startChar);
            str = s.toString();
          }
          nextChar++;
          if (c == '\r') {
            skipLF = true;
            if (read() != -1) {
              nextChar--;
            }
          }
          return str;
        }

288 289 290
        if (s == null) {
          s = new StringBuilder(defaultExpectedLineLength);
        }
291 292 293 294 295 296 297 298 299 300 301
        s.append(cb, startChar, i - startChar);
      }
    }
  }

  /** {@link BufferedReader#readLine()} */
  public String readLine() throws IOException {
    return readLine(false);
  }

  /** {@link BufferedReader#skip(long)} */
302
  @Override
303 304 305 306 307 308 309 310
  public long skip(long n) throws IOException {
    if (n < 0L) {
      throw new IllegalArgumentException("skip value is negative");
    }
    synchronized (lock) {
      ensureOpen();
      long r = n;
      while (r > 0) {
311 312 313 314 315 316 317
        if (nextChar >= nChars) {
          fill();
        }
        if (nextChar >= nChars) {
          /* EOF */
          break;
        }
318 319 320 321 322 323
        if (skipLF) {
          skipLF = false;
          if (cb[nextChar] == '\n') {
            nextChar++;
          }
        }
324
        long d = (long) nChars - nextChar;
325 326 327 328 329 330 331 332 333 334 335 336 337 338
        if (r <= d) {
          nextChar += r;
          r = 0;
          break;
        } else {
          r -= d;
          nextChar = nChars;
        }
      }
      return n - r;
    }
  }

  /** {@link BufferedReader#ready()} */
339
  @Override
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  public boolean ready() throws IOException {
    synchronized (lock) {
      ensureOpen();

      /*
       * If newline needs to be skipped and the next char to be read
       * is a newline character, then just skip it right away.
       */
      if (skipLF) {
        /* Note that in.ready() will return true if and only if the next
         * read on the stream will not block.
         */
        if (nextChar >= nChars && in.ready()) {
          fill();
        }
        if (nextChar < nChars) {
356 357 358
          if (cb[nextChar] == '\n') {
            nextChar++;
          }
359 360 361 362 363 364 365 366
          skipLF = false;
        }
      }
      return (nextChar < nChars) || in.ready();
    }
  }

  /** {@link BufferedReader#markSupported()} */
367
  @Override
368 369 370 371 372
  public boolean markSupported() {
    return true;
  }

  /** {@link BufferedReader#mark(int)} */
373
  @Override
374 375 376 377 378 379 380 381 382 383 384 385 386
  public void mark(int readAheadLimit) throws IOException {
    if (readAheadLimit < 0) {
      throw new IllegalArgumentException("Read-ahead limit < 0");
    }
    synchronized (lock) {
      ensureOpen();
      this.readAheadLimit = readAheadLimit;
      markedChar = nextChar;
      markedSkipLF = skipLF;
    }
  }

  /** {@link BufferedReader#reset()} */
387
  @Override
388 389 390
  public void reset() throws IOException {
    synchronized (lock) {
      ensureOpen();
391
      if (markedChar < 0) {
392
        throw new IOException((markedChar == INVALIDATED) ? "Mark invalid" : "Stream not marked");
393
      }
394 395 396 397 398 399
      nextChar = markedChar;
      skipLF = markedSkipLF;
    }
  }

  /** {@link BufferedReader#close()} */
400
  @Override
401 402
  public void close() throws IOException {
    synchronized (lock) {
403 404 405
      if (in == null) {
        return;
      }
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
      try {
        in.close();
      } finally {
        in = null;
        cb = null;
      }
    }
  }

  /** {@link BufferedReader#lines()} */
  public Stream<String> lines() {
    Iterator<String> iter =
        new Iterator<String>() {
          String nextLine = null;

          @Override
          public boolean hasNext() {
            if (nextLine != null) {
              return true;
            } else {
              try {
                nextLine = readLine();
                return (nextLine != null);
              } catch (IOException e) {
                throw new UncheckedIOException(e);
              }
            }
          }

          @Override
          public String next() {
            if (nextLine != null || hasNext()) {
              String line = nextLine;
              nextLine = null;
              return line;
            } else {
              throw new NoSuchElementException();
            }
          }
        };
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED | Spliterator.NONNULL),
        false);
  }

  /**
   * Returns this reader's file position.
   *
   * @return This reader's file position, a non-negative integer counting the number of bytes from
   *     the beginning of the file to the current position
   */
  public long position() {
    // position = totalFilledBytesNum - lastFilledBytesNum + readOffsetInLastFilledBytes
    // lastFilledBytesNum = nChars - dst, readOffsetInLastFilledBytes = nextChar - dst
    return totalFilledBytesNum - nChars + nextChar;
  }
}