Skip to content

Improve OutputStream and Writer emulation #10119

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions user/super/com/google/gwt/emul/java/io/ByteArrayOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

package java.io;

import java.nio.charset.Charset;

/**
* A specialized {@link OutputStream} for class for writing content to an
* (internal) byte array. As bytes are written to this stream, the byte array
Expand Down Expand Up @@ -175,6 +177,18 @@ public String toString(String charsetName) throws UnsupportedEncodingException {
return new String(buf, 0, count, charsetName);
}

/**
* Returns the contents of this ByteArrayOutputStream as a string converted
* according to the encoding declared in {@code charsetName}.
*
* @param charset
* the encoding to use when translating this stream to a string.
* @return this stream's current contents as an encoded string.
*/
public String toString(Charset charset) {
return new String(buf, 0, count, charset);
}

/**
* Writes {@code count} bytes from the byte array {@code buffer} starting at
* offset {@code index} to this stream.
Expand Down Expand Up @@ -203,6 +217,18 @@ public void write(byte[] buffer, int offset, int len) {
this.count += len;
}

/**
* Writes all bytes from the byte array {@code buffer} to this stream.
*
* @param buffer
* the buffer to be written.
* @throws NullPointerException
* if {@code buffer} is {@code null}.
*/
public void writeBytes(byte[] buffer) {
write(buffer, 0, buffer.length);
}

/**
* Writes the specified byte {@code oneByte} to the OutputStream. Only the
* low order byte of {@code oneByte} is written.
Expand Down
27 changes: 26 additions & 1 deletion user/super/com/google/gwt/emul/java/io/OutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
* @see InputStream
*
* <p>The implementation provided by this class behaves as described in the Java
* API documentation except for {@link write(int)} which throws an exception of
* API documentation except for {@link #write(int)} which throws an exception of
* type {@link java.lang.UnsupportedOperationException} instead of being
* abstract.
*/
Expand Down Expand Up @@ -130,4 +130,29 @@ public void write(byte[] buffer, int offset, int count) throws IOException {
* if an error occurs while writing to this stream.
*/
public abstract void write(int oneByte) throws IOException;

public static OutputStream nullOutputStream() {
return new OutputStream() {
private boolean closed;

@Override
public void write(int b) throws IOException {
if (closed) {
throw new IOException();
}
}

public void write(byte[] buffer, int offset, int count) throws IOException {
IOUtils.checkOffsetAndCount(buffer, offset, count);
if (closed) {
throw new IOException();
}
}

@Override
public void close() {
closed = true;
}
};
}
}
50 changes: 50 additions & 0 deletions user/super/com/google/gwt/emul/java/io/Writer.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,54 @@ public Writer append(CharSequence csq, int start, int end) throws IOException {
write(csq.subSequence(start, end).toString());
return this;
}

public static Writer nullWriter() {
return new Writer() {
private boolean closed;

@Override
public void write(char[] buffer, int off, int len) throws IOException {
IOUtils.checkOffsetAndCount(buffer, off, len);
ensureOpen();
}

public void write(int oneChar) throws IOException {
ensureOpen();
}

public void write(String str, int offset, int count) throws IOException {
IOUtils.checkOffsetAndCount(str, offset, count);
ensureOpen();
}

public Writer append(CharSequence csq) throws IOException {
ensureOpen();
return this;
}

public Writer append(CharSequence csq, int start, int end) throws IOException {
ensureOpen();
if (csq != null) {
IOUtils.checkOffsetAndCount(csq.toString(), start, end - start);
}
return this;
}

@Override
public void flush() throws IOException {
ensureOpen();
}

@Override
public void close() {
closed = true;
}

private void ensureOpen() throws IOException {
if (closed) {
throw new IOException();
}
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
Expand Down Expand Up @@ -137,8 +138,17 @@ public void testToStringWithCharsetNameAndNonEmptyStream() throws IOException {
assertEquals(expectedString, actualString);
}

public void testToStringWithCharsetAndNonEmptyStream() throws IOException {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1);
final String expectedString = "Hello";

outputStream.write(expectedString.getBytes(StandardCharsets.UTF_8));
final String actualString = outputStream.toString(StandardCharsets.UTF_8);
assertEquals(expectedString, actualString);
}

public void testWriteSingleValues() throws IOException {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2);
outputStream = new ByteArrayOutputStream(2);
assertEquals(0, outputStream.size());

for (int i = 0; i < 3; i++) {
Expand All @@ -149,4 +159,15 @@ public void testWriteSingleValues() throws IOException {
final byte[] actualBytes = outputStream.toByteArray();
assertTrue(Arrays.equals(expectedBytes, actualBytes));
}

public void testWriteBytes() throws IOException {
outputStream = new ByteArrayOutputStream(2);
assertEquals(0, outputStream.size());
outputStream.writeBytes(TEST_ARRAY);
final byte[] actualBytes = outputStream.toByteArray();
assertTrue(Arrays.equals(TEST_ARRAY, actualBytes));
outputStream.writeBytes(new byte[0]);
final byte[] actualBytes2 = outputStream.toByteArray();
assertTrue(Arrays.equals(TEST_ARRAY, actualBytes));
}
}
12 changes: 12 additions & 0 deletions user/test/com/google/gwt/emultest/java/io/OutputStreamTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,16 @@ public void testDefaultBehaviorOfFlush() throws IOException {
// should do nothing (including not throwing an exception).
outputStream.flush();
}

public void testNullOutputStream() throws IOException {
OutputStream nullStream = OutputStream.nullOutputStream();
nullStream.write(42);
nullStream.close();
try {
nullStream.write(1);
fail("Writing to a closed stream should fail.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth noting perhaps that StringReader ignores close, and would fail this style of test. This goes against the JRE implementation and javadoc. There may be others that are wrong too.

public void close() throws IOException { }

Definitely not asking for this to be fixed here, just noting it.

} catch (IOException expected) {
// expected
}
}
}
30 changes: 30 additions & 0 deletions user/test/com/google/gwt/emultest/java/io/WriterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,34 @@ public void testWriteNonEmptySubstring() throws IOException {
writer.write(str, 1, 2);
assertTrue(Arrays.equals("ol".toCharArray(), writer.toCharArray()));
}

public void testNullWriter() throws IOException {
Writer nullWriter = Writer.nullWriter();
nullWriter.write(42);
nullWriter.append('a');
nullWriter.write("hola", 1, 2);
nullWriter.close();
// writing to closed stream fails
assertThrows(IOException.class, () -> nullWriter.write(42));
assertThrows(IOException.class, () -> nullWriter.append('a'));
assertThrows(IOException.class, () -> nullWriter.append("hola", 1, 2));
// bounds check takes precedence over closed stream check
assertThrows(IndexOutOfBoundsException.class,
() -> nullWriter.write("hola", 1, 10));
assertThrows(IndexOutOfBoundsException.class,
() -> nullWriter.write(new char[]{'h', 'o', 'l', 'a'}, 1, 10));
}

private void assertThrows(Class<? extends Exception> ex, Throwing toTest) {
try {
toTest.run();
fail("should have failed");
} catch (Exception expected) {
assertEquals(ex, expected.getClass());
}
}

private interface Throwing {
void run() throws Exception;
}
}