001package io.jstach.jstachio.output; 002 003import java.io.ByteArrayOutputStream; 004import java.nio.ByteBuffer; 005import java.nio.channels.ReadableByteChannel; 006import java.nio.charset.Charset; 007 008/** 009 * An encoded output optimized for producing a single {@link ByteBuffer}. The 010 * {@link #bufferSizeHint()} is usually the size of the entire output and usually 011 * implementations of this type are {@linkplain #isReusable() reusable} with care. 012 * 013 * @author agentgt 014 */ 015public non-sealed interface ByteBufferEncodedOutput extends BufferedEncodedOutput { 016 017 /** 018 * Gets a byte buffer view of the data. 019 * @return byte buffer 020 */ 021 public ByteBuffer asByteBuffer(); 022 023 /** 024 * Create a buffered encoded output backed by an array that will grow as needed 025 * analagous to StringBuilder and/or {@link ByteArrayOutputStream}. <strong>This 026 * output is more optimized for getting byte array or a ByteBuffer as well a reuse. 027 * </strong> 028 * @param charset the expected encoding 029 * @param initialSize the initial size of the backing array. 030 * @return buffered output 031 */ 032 public static ByteBufferEncodedOutput ofByteArray(Charset charset, int initialSize) { 033 return new ByteBufferedOutputStream(initialSize, charset); 034 } 035 036 /** 037 * Calls {@link #ofByteArray(Charset, int)} with initial size of 038 * {@value ByteBufferedOutputStream#BUFFER_SIZE}. 039 * @param charset the expected encoding 040 * @return buffered output 041 */ 042 public static ByteBufferEncodedOutput ofByteArray(Charset charset) { 043 return new ByteBufferedOutputStream(ByteBufferedOutputStream.BUFFER_SIZE, charset); 044 } 045 046 @Override 047 default ReadableByteChannel asReadableByteChannel() { 048 return BufferedReadableByteChannel.of(this, asByteBuffer()); 049 } 050 051}