Skip to content

Commit

Permalink
Do not wrap Writer, but return it as-is
Browse files Browse the repository at this point in the history
  • Loading branch information
mkarg committed Dec 28, 2024
1 parent 4c7de8c commit 80601a9
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/java.base/share/classes/java/io/Writer.java
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ public void close() throws IOException {
* {@code Appendable}. The writer is initially open and writing appends
* after the last character in the builder.
*
* <p> If the appendable is a {code Writer}, it is returned.
*
* <p> The resulting writer is not safe for use by multiple
* concurrent threads. If the writer is to be used by more than one
* thread it should be controlled by appropriate synchronization.
Expand All @@ -158,14 +160,18 @@ public void close() throws IOException {
* changes, the behavior is undefined.
*
* @param a {@code Appendable} consuming the character stream.
* @return a {@code Writer} which writes characters into {@code a}
* @return a {@code Writer} which writes characters into {@code a}, or
* {@code a} if it is a {@code Writer}.
* @throws NullPointerException if {@code a} is {@code null}
*
* @since 25
*/
public static Writer of(final Appendable a) {
Objects.requireNonNull(a);

if (a instanceof Writer w)
return w;

return new Writer() {
private boolean isClosed;

Expand All @@ -178,10 +184,7 @@ private void ensureOpen() throws IOException {
@Override
public void write(int c) throws IOException {
ensureOpen();
switch (a) {
case Writer w -> w.write(c);
default -> a.append((char) c);
}
a.append((char) c);
}

@Override
Expand All @@ -195,7 +198,6 @@ public void write(char[] cbuf, int off, int len) throws IOException {
case StringBuilder sb -> sb.append(cbuf, off, len);
case StringBuffer sb -> sb.append(cbuf, off, len);
case CharBuffer cb -> cb.put(cbuf, off, len);
case Writer w -> w.write(cbuf, off, len);
default -> {
for (int i = 0; i < len; i++)
a.append(cbuf[off + i]);
Expand All @@ -210,18 +212,14 @@ public void write(String str) throws IOException {
case StringBuilder sb -> sb.append(str);
case StringBuffer sb -> sb.append(str);
case CharBuffer cb -> cb.put(str);
case Writer w -> w.write(str);
default -> a.append(str);
}
}

@Override
public void write(String str, int off, int len) throws IOException {
ensureOpen();
switch (a) {
case Writer w -> w.write(str, off, len);
default -> a.append(str, off, off + len);
}
a.append(str, off, off + len);
}

@Override
Expand Down

0 comments on commit 80601a9

Please sign in to comment.