@@ -55,12 +55,18 @@ public class CharSequenceInputStream extends InputStream {
5555 * @param cs the input character sequence
5656 * @param charset the character set name to use
5757 * @param bufferSize the buffer size to use.
58+ * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character
5859 */
5960 public CharSequenceInputStream (final CharSequence cs , final Charset charset , final int bufferSize ) {
6061 super ();
6162 this .encoder = charset .newEncoder ()
6263 .onMalformedInput (CodingErrorAction .REPLACE )
6364 .onUnmappableCharacter (CodingErrorAction .REPLACE );
65+ // Ensure that buffer is long enough to hold a complete character
66+ final float maxBytesPerChar = encoder .maxBytesPerChar ();
67+ if (bufferSize < maxBytesPerChar ) {
68+ throw new IllegalArgumentException ("Buffer size " + bufferSize + " is less than maxBytesPerChar " + maxBytesPerChar );
69+ }
6470 this .bbuf = ByteBuffer .allocate (bufferSize );
6571 this .bbuf .flip ();
6672 this .cbuf = CharBuffer .wrap (cs );
@@ -73,6 +79,7 @@ public CharSequenceInputStream(final CharSequence cs, final Charset charset, fin
7379 * @param cs the input character sequence
7480 * @param charset the character set name to use
7581 * @param bufferSize the buffer size to use.
82+ * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character
7683 */
7784 public CharSequenceInputStream (final CharSequence cs , final String charset , final int bufferSize ) {
7885 this (cs , Charset .forName (charset ), bufferSize );
@@ -84,6 +91,7 @@ public CharSequenceInputStream(final CharSequence cs, final String charset, fina
8491 *
8592 * @param cs the input character sequence
8693 * @param charset the character set name to use
94+ * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character
8795 */
8896 public CharSequenceInputStream (final CharSequence cs , final Charset charset ) {
8997 this (cs , charset , BUFFER_SIZE );
@@ -95,6 +103,7 @@ public CharSequenceInputStream(final CharSequence cs, final Charset charset) {
95103 *
96104 * @param cs the input character sequence
97105 * @param charset the character set name to use
106+ * @throws IllegalArgumentException if the buffer is not large enough to hold a complete character
98107 */
99108 public CharSequenceInputStream (final CharSequence cs , final String charset ) {
100109 this (cs , charset , BUFFER_SIZE );
@@ -112,9 +121,6 @@ private void fillBuffer() throws CharacterCodingException {
112121 if (result .isError ()) {
113122 result .throwException ();
114123 }
115- // if (result.isUnderflow()) {
116- // result.throwException();
117- // }
118124 this .bbuf .flip ();
119125 }
120126
0 commit comments