aboutsummaryrefslogtreecommitdiff
path: root/java/org/brotli/wrapper/enc/BrotliOutputStream.java
blob: 5bd3957779cc39d2480123947c3af8faf152d30d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* Copyright 2017 Google Inc. All Rights Reserved.

   Distributed under MIT license.
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/

package org.brotli.wrapper.enc;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;

/**
 * Output stream that wraps native brotli encoder.
 */
public class BrotliOutputStream extends OutputStream {
  /** The default internal buffer size used by the encoder. */
  private static final int DEFAULT_BUFFER_SIZE = 16384;

  private final Encoder encoder;

  /**
   * Creates a BrotliOutputStream.
   *
   * @param destination underlying destination
   * @param params encoding settings
   * @param bufferSize intermediate buffer size
   */
  public BrotliOutputStream(OutputStream destination, Encoder.Parameters params, int bufferSize)
      throws IOException {
    this.encoder = new Encoder(Channels.newChannel(destination), params, bufferSize);
  }

  public BrotliOutputStream(OutputStream destination, Encoder.Parameters params)
      throws IOException {
    this(destination, params, DEFAULT_BUFFER_SIZE);
  }

  public BrotliOutputStream(OutputStream destination) throws IOException {
    this(destination, new Encoder.Parameters());
  }

  @Override
  public void close() throws IOException {
    encoder.close();
  }

  @Override
  public void flush() throws IOException {
    if (encoder.closed) {
      throw new IOException("write after close");
    }
    encoder.flush();
  }

  @Override
  public void write(int b) throws IOException {
    if (encoder.closed) {
      throw new IOException("write after close");
    }
    while (!encoder.encode(EncoderJNI.Operation.PROCESS)) {
      // Busy-wait loop.
    }
    encoder.inputBuffer.put((byte) b);
  }

  @Override
  public void write(byte[] b) throws IOException {
    this.write(b, 0, b.length);
  }

  @Override
  public void write(byte[] b, int off, int len) throws IOException {
    if (encoder.closed) {
      throw new IOException("write after close");
    }
    while (len > 0) {
      if (!encoder.encode(EncoderJNI.Operation.PROCESS)) {
        continue;
      }
      int limit = Math.min(len, encoder.inputBuffer.remaining());
      encoder.inputBuffer.put(b, off, limit);
      off += limit;
      len -= limit;
    }
  }
}