diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/StringArrayReader.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/StringArrayReader.java index 372f7c256..409acbeb3 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/StringArrayReader.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/StringArrayReader.java @@ -24,7 +24,11 @@ import java.io.IOException; /** * A Reader that reads from an underlying String array, assuming each * array element corresponds to one line of text. - * + *
+ * Note: This class is not thread safe, concurrent reads might produce + * unexpected results! Checkstyle only works with one thread so + * currently there is no need to introduce synchronization here. + *
* @author Lars Kühne */ class StringArrayReader extends Reader @@ -71,9 +75,7 @@ class StringArrayReader extends Reader /** @see Reader */ public int read(char[] aCbuf, int aOff, int aLen) throws IOException { - if (mClosed) { - throw new IOException("already closed"); - } + ensureOpen(); int retVal = 0; @@ -105,4 +107,37 @@ class StringArrayReader extends Reader } return retVal; } + + /** @see Reader */ + public int read() throws IOException + { + if (mUnreportedNewline) { + mUnreportedNewline = false; + return '\n'; + } + + if (mArrayIdx < mUnderlyingArray.length + && mStringIdx < mUnderlyingArray[mArrayIdx].length() ) + { + // this is the common case, + // avoid char[] creation in super.read for performance + ensureOpen(); + return mUnderlyingArray[mArrayIdx].charAt(mStringIdx++); + } + else { + // don't bother duplicating the new line handling above + // for the uncommon case + return super.read(); + } + } + + /** Throws an IOException if the reader has already been closed. */ + private void ensureOpen() throws IOException + { + if (mClosed) { + throw new IOException("already closed"); + } + } + + } diff --git a/src/tests/com/puppycrawl/tools/checkstyle/StringArrayReaderTest.java b/src/tests/com/puppycrawl/tools/checkstyle/StringArrayReaderTest.java index d4a7b0e72..59612ebe5 100644 --- a/src/tests/com/puppycrawl/tools/checkstyle/StringArrayReaderTest.java +++ b/src/tests/com/puppycrawl/tools/checkstyle/StringArrayReaderTest.java @@ -12,7 +12,7 @@ public class StringArrayReaderTest super(name); } - public void testMisc() + public void testClose() { final StringArrayReader o = new StringArrayReader(new String[] {""}); assertNotNull(o); @@ -24,4 +24,25 @@ public class StringArrayReaderTest catch (IOException e) { } } + + public void testLineBreakSingleChar() + { + final StringArrayReader o = new StringArrayReader(new String[] {"a", "bc"}); + try { + int a = o.read(); + assertEquals('a', a); + int nl1 = o.read(); + assertEquals('\n', nl1); + int b = o.read(); + assertEquals('b', b); + int c = o.read(); + assertEquals('c', c); + int nl2 = o.read(); + assertEquals('\n', nl2); + int eof = o.read(); + assertEquals(-1, eof); + } + catch (IOException ex) { + } + } }