1 package com.puppycrawl.tools.checkstyle; 20 21 import java.io.Reader ; 22 import java.io.IOException ; 23 24 34 final class StringArrayReader extends Reader 35 { 36 37 private final String [] mUnderlyingArray; 38 39 40 private final int[] mLenghtArray; 41 42 43 private int mArrayIdx; 44 45 46 private int mStringIdx; 47 48 49 private boolean mUnreportedNewline; 50 51 52 private boolean mClosed; 53 54 59 StringArrayReader(String [] aUnderlyingArray) 60 { 61 final int length = aUnderlyingArray.length; 62 mUnderlyingArray = new String [length]; 63 System.arraycopy(aUnderlyingArray, 0, mUnderlyingArray, 0, length); 64 65 mLenghtArray = new int[length]; 68 for (int i = 0; i < length; i++) { 69 mLenghtArray[i] = mUnderlyingArray[i].length(); 70 } 71 } 72 73 74 public void close() 75 { 76 mClosed = true; 77 } 78 79 80 private boolean dataAvailable() 81 { 82 return (mUnderlyingArray.length > mArrayIdx); 83 } 84 85 86 public int read(char[] aCbuf, int aOff, int aLen) throws IOException 87 { 88 ensureOpen(); 89 90 int retVal = 0; 91 92 if (!mUnreportedNewline && (mUnderlyingArray.length <= mArrayIdx)) { 93 return -1; 94 } 95 96 while ((retVal < aLen) && (mUnreportedNewline || dataAvailable())) { 97 if (mUnreportedNewline) { 98 aCbuf[aOff + retVal] = '\n'; 99 retVal++; 100 mUnreportedNewline = false; 101 } 102 103 if ((retVal < aLen) && dataAvailable()) { 104 final String currentStr = mUnderlyingArray[mArrayIdx]; 105 final int currentLenth = mLenghtArray[mArrayIdx]; 106 final int srcEnd = Math.min(currentLenth, 107 mStringIdx + aLen - retVal); 108 currentStr.getChars(mStringIdx, srcEnd, aCbuf, aOff + retVal); 109 retVal += srcEnd - mStringIdx; 110 mStringIdx = srcEnd; 111 112 if (mStringIdx >= currentLenth) { 113 mArrayIdx++; 114 mStringIdx = 0; 115 mUnreportedNewline = true; 116 } 117 } 118 } 119 return retVal; 120 } 121 122 123 public int read() throws IOException 124 { 125 if (mUnreportedNewline) { 126 mUnreportedNewline = false; 127 return '\n'; 128 } 129 130 if ((mArrayIdx < mUnderlyingArray.length) 131 && (mStringIdx < mLenghtArray[mArrayIdx])) 132 { 133 ensureOpen(); 136 return mUnderlyingArray[mArrayIdx].charAt(mStringIdx++); 137 } 138 return super.read(); 141 } 142 143 148 private void ensureOpen() throws IOException 149 { 150 if (mClosed) { 151 throw new IOException ("already closed"); 152 } 153 } 154 } 155 | Popular Tags |