001/* 002 * SPDX-License-Identifier: Apache-2.0 003 * 004 * Copyright 2024-2026 The Enola <https://enola.dev> Authors 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); 007 * you may not use this file except in compliance with the License. 008 * You may obtain a copy of the License at 009 * 010 * https://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package dev.enola.common; 019 020import java.io.IOException; 021import java.io.Writer; 022 023/** 024 * {@link Writer} implementation that outputs to a {@link StringBuilder}. 025 * 026 * <p>This is alternative to {@link java.io.StringWriter}, which internally uses a {@link 027 * StringBuffer}. This is faster (!) - at the expense of not (!) being concurrency multi thread safe 028 * - which often is not required. 029 */ 030public final class StringBuilderWriter extends Writer { 031 032 private final StringBuilder builder = new StringBuilder(); 033 034 @Override 035 public void write(String str) throws IOException { 036 builder.append(str); 037 } 038 039 @Override 040 public void write(char[] cbuf) throws IOException { 041 builder.append(cbuf); 042 } 043 044 @Override 045 public void write(char[] cbuf, int off, int len) throws IOException { 046 if (len == 0) return; 047 builder.append(cbuf, off, len); 048 } 049 050 @Override 051 public void write(String str, int off, int len) throws IOException { 052 if (len == 0) return; 053 builder.append(str, off, off + len); // not off, len! 054 } 055 056 @Override 057 public void write(int c) throws IOException { 058 builder.append((char) c); // sic! 059 } 060 061 @Override 062 public Writer append(char c) throws IOException { 063 builder.append(c); 064 return this; 065 } 066 067 @Override 068 public String toString() { 069 return builder.toString(); 070 } 071 072 @Override 073 public void flush() throws IOException {} 074 075 @Override 076 public void close() throws IOException {} 077}