001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2024 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.io.util;
020
021import java.io.IOException;
022import java.io.Reader;
023import java.nio.Buffer;
024import java.nio.charset.Charset;
025import java.util.function.Consumer;
026import org.jgrapes.core.Components;
027import org.jgrapes.io.events.Input;
028
029/**
030 * Starts a thread with a synchronous consumer of input provided by a
031 * {@link Reader} which is fed with data from {@link ManagedBuffer}s
032 * (usually obtained from {@link Input} events).
033 *  
034 * @since 2.8.0
035 */
036public class ManagedBufferStreamer implements InputConsumer {
037
038    private final ManagedBufferReader reader = new ManagedBufferReader();
039
040    /**
041     * Instantiates a new managed buffer streamer.
042     *
043     * @param processor the processor
044     */
045    public ManagedBufferStreamer(Consumer<Reader> processor) {
046        Thread thread = (Components.useVirtualThreads() ? Thread.ofVirtual()
047            : Thread.ofPlatform()).start(() -> {
048                processor.accept(reader);
049            });
050        ThreadCleaner.watch(this, thread);
051    }
052
053    /**
054     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
055     * is invoked with `ManagedBuffer<ByteBuffer>`. Defaults to UTF-8. 
056     * Must be set before the first invocation of 
057     * {@link #feed(ManagedBuffer)}.  
058     *
059     * @param charset the charset
060     * @return the managed buffer streamer
061     */
062    public ManagedBufferStreamer charset(Charset charset) {
063        reader.charset(charset);
064        return this;
065    }
066
067    /**
068     * Feed data to underlying the reader
069     * (see {@link ManagedBufferReader#feed). 
070     * 
071     * @param buffer the buffer
072     * @throws IOException Signals that an I/O exception has occurred.
073     */
074    @Override
075    public <W extends Buffer> void feed(ManagedBuffer<W> buffer) {
076        reader.feed(buffer);
077    }
078}