001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2024-2025 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.resource;
019
020import com.google.common.net.MediaType;
021
022import java.io.IOException;
023import java.io.Writer;
024
025public class AppendableResource extends WriterResource {
026
027    public AppendableResource(Appendable appendable, MediaType mediaType) {
028        super(writerToAppendable(appendable), mediaType);
029    }
030
031    private static Writer writerToAppendable(Appendable appendable) {
032        return new Writer() {
033            @Override
034            public void write(char[] cbuf) throws IOException {
035                for (var c : cbuf) appendable.append(c);
036            }
037
038            @Override
039            public void write(char[] cbuf, int off, int len) throws IOException {
040                for (int i = off; i < off + len; i++) appendable.append(cbuf[i]);
041            }
042
043            @Override
044            public void write(String str) throws IOException {
045                appendable.append(str);
046            }
047
048            @Override
049            public void write(int character) throws IOException {
050                appendable.append((char) character);
051            }
052
053            @Override
054            public void write(String str, int off, int len) throws IOException {
055                appendable.append(str.substring(off, off + len));
056            }
057
058            @Override
059            public void flush() throws IOException {}
060
061            @Override
062            public void close() throws IOException {}
063        };
064    }
065}