001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2025-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.io.util;
019
020import java.io.IOException;
021import java.io.Writer;
022import java.nio.CharBuffer;
023
024// See also org.apache.commons.io.output.AppendableWriter; but
025//   we (a) want to avoid the dependency; and (b) handle flush() and close().
026public class AppendableWriter extends java.io.Writer {
027    private final Appendable appendable;
028
029    public AppendableWriter(Appendable appendable) {
030        this.appendable = appendable;
031    }
032
033    @Override
034    public Writer append(char c) throws IOException {
035        appendable.append(c);
036        return this;
037    }
038
039    @Override
040    public Writer append(CharSequence csq) throws IOException {
041        appendable.append(csq);
042        return this;
043    }
044
045    @Override
046    public Writer append(CharSequence csq, int start, int end) throws IOException {
047        appendable.append(csq, start, end);
048        return this;
049    }
050
051    @Override
052    public void write(String str, int off, int len) throws IOException {
053        appendable.append(str, off, off + len); // !!
054    }
055
056    @Override
057    public void write(String str) throws IOException {
058        appendable.append(str);
059    }
060
061    @Override
062    public void write(int c) throws IOException {
063        appendable.append((char) c);
064    }
065
066    @Override
067    public void write(char[] cbuf) throws IOException {
068        appendable.append(CharBuffer.wrap(cbuf));
069    }
070
071    @Override
072    public void write(char[] cbuf, int off, int len) throws IOException {
073        // This cannot work if it doesn't happen to be at the right boundary?
074        // But we cannot really do anything better here... or can we?
075        // org.apache.commons.io.output.AppendableWriter also does it.
076        appendable.append(CharBuffer.wrap(cbuf, off, len));
077    }
078
079    @Override
080    public void flush() throws IOException {
081        if (appendable instanceof java.io.Flushable flushable) flushable.flush();
082    }
083
084    @Override
085    public void close() throws IOException {
086        if (appendable instanceof java.io.Closeable closeable) closeable.close();
087    }
088}