1 /* Copyright 2017 Google Inc. All Rights Reserved. 2 3 Distributed under MIT license. 4 See file LICENSE for detail or copy at https://opensource.org/licenses/MIT 5 */ 6 7 package org.brotli.wrapper.enc; 8 9 import java.io.IOException; 10 import java.nio.ByteBuffer; 11 import java.nio.channels.ClosedChannelException; 12 import java.nio.channels.WritableByteChannel; 13 14 /** 15 * WritableByteChannel that wraps native brotli encoder. 16 */ 17 public class BrotliEncoderChannel extends Encoder implements WritableByteChannel { 18 /** The default internal buffer size used by the decoder. */ 19 private static final int DEFAULT_BUFFER_SIZE = 16384; 20 21 private final Object mutex = new Object(); 22 23 /** 24 * Creates a BrotliEncoderChannel. 25 * 26 * @param destination underlying destination 27 * @param params encoding settings 28 * @param bufferSize intermediate buffer size 29 */ 30 public BrotliEncoderChannel(WritableByteChannel destination, Encoder.Parameters params, 31 int bufferSize) throws IOException { 32 super(destination, params, bufferSize); 33 } 34 35 public BrotliEncoderChannel(WritableByteChannel destination, Encoder.Parameters params) 36 throws IOException { 37 this(destination, params, DEFAULT_BUFFER_SIZE); 38 } 39 40 public BrotliEncoderChannel(WritableByteChannel destination) throws IOException { 41 this(destination, new Encoder.Parameters()); 42 } 43 44 @Override 45 public boolean isOpen() { 46 synchronized (mutex) { 47 return !closed; 48 } 49 } 50 51 @Override 52 public void close() throws IOException { 53 synchronized (mutex) { 54 super.close(); 55 } 56 } 57 58 @Override 59 public int write(ByteBuffer src) throws IOException { 60 synchronized (mutex) { 61 if (closed) { 62 throw new ClosedChannelException(); 63 } 64 int result = 0; 65 while (src.hasRemaining() && encode(EncoderJNI.Operation.PROCESS)) { 66 int limit = Math.min(src.remaining(), inputBuffer.remaining()); 67 ByteBuffer slice = src.slice(); 68 slice.limit(limit); 69 inputBuffer.put(slice); 70 result += limit; 71 src.position(src.position() + limit); 72 } 73 return result; 74 } 75 } 76 } 77