GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Codec-compression: Add BrotliDecompressor (#17146) · netty/netty@b8fb58f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-compression/src
    • main/java/io/netty/handler/codec/compression
      • BrotliDecompressor.java
      • BrotliEncoder.java
    • test/java/io/netty/handler/codec/compression
      • BrotliDecompressorTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliDecompressor.java‎

Copy file name to clipboard
+194Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/*
2+
* Copyright 2025 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.handler.codec.compression;
17+
18+
import com.aayushatharva.brotli4j.decoder.DecoderJNI;
19+
import io.netty.buffer.ByteBuf;
20+
import io.netty.buffer.ByteBufAllocator;
21+
import io.netty.util.internal.ObjectUtil;
22+
import io.netty.util.internal.UnstableApi;
23+
24+
import java.io.IOException;
25+
import java.nio.ByteBuffer;
26+
27+
/**
28+
* Decompresses a {@link ByteBuf} encoded with the brotli format.
29+
*
30+
* See <a href="https://github.com/google/brotli">brotli</a>.
31+
*/
32+
@UnstableApi
33+
public final class BrotliDecompressor implements Decompressor {
34+
private final ByteBufAllocator allocator;
35+
private DecoderJNI.Wrapper decoder;
36+
private ByteBuf unusedInput;
37+
38+
static {
39+
try {
40+
Brotli.ensureAvailability();
41+
} catch (Throwable throwable) {
42+
throw new ExceptionInInitializerError(throwable);
43+
}
44+
}
45+
46+
BrotliDecompressor(Builder builder, ByteBufAllocator allocator) throws DecompressionException {
47+
this.allocator = allocator;
48+
try {
49+
this.decoder = new DecoderJNI.Wrapper(builder.inputBufferSize, builder.maxOutputChunkSize);
50+
} catch (IOException ioe) {
51+
throw new DecompressionException(ioe);
52+
}
53+
}
54+
55+
@Override
56+
public Status status() throws DecompressionException {
57+
while (true) {
58+
switch (decoder.getStatus()) {
59+
case ERROR:
60+
throw new DecompressionException("Brotli error status");
61+
case DONE:
62+
return Status.COMPLETE;
63+
case NEEDS_MORE_INPUT:
64+
if (decoder.hasOutput()) {
65+
return Status.NEED_OUTPUT;
66+
}
67+
if (unusedInput == null) {
68+
return Status.NEED_INPUT;
69+
}
70+
addSomeInput(unusedInput);
71+
if (!unusedInput.isReadable()) {
72+
unusedInput.release();
73+
unusedInput = null;
74+
}
75+
break;
76+
case OK:
77+
decoder.push(0);
78+
break;
79+
case NEEDS_MORE_OUTPUT:
80+
return Status.NEED_OUTPUT;
81+
default:
82+
throw new AssertionError("Unknown status: " + decoder.getStatus());
83+
}
84+
}
85+
}
86+
87+
@Override
88+
public void addInput(ByteBuf buf) throws DecompressionException {
89+
try {
90+
if (unusedInput != null) {
91+
throw new IllegalStateException("Not in state NEED_INPUT");
92+
}
93+
addSomeInput(buf);
94+
} catch (Throwable t) {
95+
buf.release();
96+
throw t;
97+
}
98+
if (buf.isReadable()) {
99+
this.unusedInput = buf;
100+
} else {
101+
buf.release();
102+
}
103+
}
104+
105+
private void addSomeInput(ByteBuf buf) {
106+
ByteBuffer decoderInputBuffer = decoder.getInputBuffer();
107+
decoderInputBuffer.clear();
108+
int readBytes = readBytes(buf, decoderInputBuffer);
109+
decoder.push(readBytes);
110+
}
111+
112+
@Override
113+
public void endOfInput() throws DecompressionException {
114+
if (decoder.getStatus() == DecoderJNI.Status.NEEDS_MORE_INPUT) {
115+
assert unusedInput == null : "Expected to be in NEED_INPUT state";
116+
decoder.push(0);
117+
if (decoder.getStatus() == DecoderJNI.Status.NEEDS_MORE_INPUT) {
118+
throw new DecompressionException("Truncated brotli stream");
119+
}
120+
}
121+
}
122+
123+
@Override
124+
public ByteBuf takeOutput() throws DecompressionException {
125+
ByteBuffer nativeBuffer = decoder.pull();
126+
// nativeBuffer actually wraps brotli's internal buffer so we need to copy its content
127+
// size limited by maxOutputChunkSize
128+
ByteBuf copy = allocator.buffer(nativeBuffer.remaining());
129+
copy.writeBytes(nativeBuffer);
130+
return copy;
131+
}
132+
133+
@Override
134+
public void close() {
135+
if (decoder != null) {
136+
decoder.destroy();
137+
decoder = null;
138+
}
139+
if (unusedInput != null) {
140+
unusedInput.release();
141+
unusedInput = null;
142+
}
143+
}
144+
145+
private static int readBytes(ByteBuf in, ByteBuffer dest) {
146+
int limit = Math.min(in.readableBytes(), dest.remaining());
147+
ByteBuffer slice = dest.slice();
148+
slice.limit(limit);
149+
in.readBytes(slice);
150+
dest.position(dest.position() + limit);
151+
return limit;
152+
}
153+
154+
@UnstableApi
155+
public static Builder builder() {
156+
return new Builder();
157+
}
158+
159+
@UnstableApi
160+
public static final class Builder extends AbstractDecompressorBuilder {
161+
private int inputBufferSize = 8 * 1024;
162+
private int maxOutputChunkSize = 64 * 1024;
163+
164+
Builder() {
165+
}
166+
167+
/**
168+
* Desired size of the input buffer in bytes. Default 8K.
169+
*
170+
* @param inputBufferSize desired size of the input buffer in bytes
171+
* @return This builder
172+
*/
173+
public Builder inputBufferSize(int inputBufferSize) {
174+
this.inputBufferSize = ObjectUtil.checkPositive(inputBufferSize, "inputBufferSize");
175+
return this;
176+
}
177+
178+
/**
179+
* Number of bytes of output to consume at a time. Default 64K.
180+
*
181+
* @param maxOutputChunkSize Maximum output chunk size
182+
* @return This builder
183+
*/
184+
public Builder maxOutputChunkSize(int maxOutputChunkSize) {
185+
this.maxOutputChunkSize = ObjectUtil.checkPositive(maxOutputChunkSize, "maxOutputChunkSize");
186+
return this;
187+
}
188+
189+
@Override
190+
public Decompressor build(ByteBufAllocator allocator) throws DecompressionException {
191+
return new DefensiveDecompressor(new BrotliDecompressor(this, allocator));
192+
}
193+
}
194+
}
Collapse file

‎codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliEncoder.java‎

Copy file name to clipboardExpand all lines: codec-compression/src/main/java/io/netty/handler/codec/compression/BrotliEncoder.java
+9-8Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,10 @@ public boolean isSharable() {
154154
* @throws IOException If an error occurred during closure
155155
*/
156156
public void finish(ChannelHandlerContext ctx) throws IOException {
157-
finishEncode(ctx, ctx.newPromise());
157+
finishEncode(ctx);
158158
}
159159

160-
private ChannelFuture finishEncode(ChannelHandlerContext ctx, ChannelPromise promise) throws IOException {
160+
private ChannelFuture finishEncode(ChannelHandlerContext ctx) throws IOException {
161161
Writer writer;
162162

163163
if (isSharable) {
@@ -169,13 +169,14 @@ private ChannelFuture finishEncode(ChannelHandlerContext ctx, ChannelPromise pro
169169
if (writer != null) {
170170
writer.close();
171171
this.writer = null;
172+
return writer.closeFuture;
172173
}
173-
return promise;
174+
return ctx.newSucceededFuture();
174175
}
175176

176177
@Override
177178
public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
178-
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
179+
ChannelFuture f = finishEncode(ctx);
179180
EncoderUtil.closeAfterFinishEncode(ctx, f, promise);
180181
}
181182

@@ -188,11 +189,13 @@ private static final class Writer implements WritableByteChannel {
188189
private ByteBuf writableBuffer;
189190
private final BrotliEncoderChannel brotliEncoderChannel;
190191
private final ChannelHandlerContext ctx;
192+
private final ChannelPromise closeFuture;
191193
private boolean isClosed;
192194

193195
private Writer(Encoder.Parameters parameters, ChannelHandlerContext ctx) throws IOException {
194196
brotliEncoderChannel = new BrotliEncoderChannel(this, parameters);
195197
this.ctx = ctx;
198+
this.closeFuture = ctx.newPromise();
196199
}
197200

198201
private void encode(ByteBuf msg, boolean preferDirect) throws Exception {
@@ -241,15 +244,13 @@ public boolean isOpen() {
241244

242245
@Override
243246
public void close() {
244-
final ChannelPromise promise = ctx.newPromise();
245-
246247
ctx.executor().execute(new Runnable() {
247248
@Override
248249
public void run() {
249250
try {
250-
finish(promise);
251+
finish(closeFuture);
251252
} catch (IOException ex) {
252-
promise.setFailure(new IllegalStateException("Failed to finish encoding", ex));
253+
closeFuture.setFailure(new IllegalStateException("Failed to finish encoding", ex));
253254
}
254255
}
255256
});
Collapse file

‎codec-compression/src/test/java/io/netty/handler/codec/compression/BrotliDecompressorTest.java‎

Copy file name to clipboard
+82Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
* Copyright 2025 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.handler.codec.compression;
17+
18+
import io.netty.buffer.ByteBuf;
19+
import io.netty.buffer.ByteBufAllocator;
20+
import io.netty.channel.ChannelHandler;
21+
import org.junit.jupiter.api.Test;
22+
23+
import static org.junit.jupiter.api.Assertions.assertEquals;
24+
import static org.junit.jupiter.api.Assertions.assertThrows;
25+
26+
public class BrotliDecompressorTest extends AbstractDecompressorTest {
27+
@Override
28+
protected ChannelHandler createCompressor() {
29+
return new BrotliEncoder();
30+
}
31+
32+
@Override
33+
protected Decompressor.AbstractDecompressorBuilder createDecompressor() {
34+
return BrotliDecompressor.builder();
35+
}
36+
37+
@Test
38+
public void reportsOutputBeforeMoreInput() throws Exception {
39+
ByteBuf[] data = largeData();
40+
41+
try (Decompressor decompressor = createDecompressor().build(ByteBufAllocator.DEFAULT)) {
42+
assertEquals(Decompressor.Status.NEED_INPUT, decompressor.status());
43+
decompressor.addInput(data[0]);
44+
data[0] = null;
45+
46+
assertEquals(Decompressor.Status.NEED_OUTPUT, decompressor.status());
47+
decompressor.takeOutput().release();
48+
} finally {
49+
for (ByteBuf buffer : data) {
50+
if (buffer != null) {
51+
buffer.release();
52+
}
53+
}
54+
}
55+
}
56+
57+
@Test
58+
public void endOfInputRejectsTruncatedStream() throws Exception {
59+
ByteBuf[] data = smallData();
60+
ByteBuf truncated = data[0].readRetainedSlice(data[0].readableBytes() - 1);
61+
62+
try (Decompressor decompressor = createDecompressor().build(ByteBufAllocator.DEFAULT)) {
63+
assertEquals(Decompressor.Status.NEED_INPUT, decompressor.status());
64+
decompressor.addInput(truncated);
65+
truncated = null;
66+
67+
while (decompressor.status() == Decompressor.Status.NEED_OUTPUT) {
68+
decompressor.takeOutput().release();
69+
}
70+
71+
assertEquals(Decompressor.Status.NEED_INPUT, decompressor.status());
72+
assertThrows(DecompressionException.class, decompressor::endOfInput);
73+
} finally {
74+
if (truncated != null) {
75+
truncated.release();
76+
}
77+
for (ByteBuf buffer : data) {
78+
buffer.release();
79+
}
80+
}
81+
}
82+
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.