Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid un-necessary byte copies when decoding a Vert.x Buffer to a protobuf object and perform more optimal allocation #136

Merged
merged 1 commit into from
Mar 5, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
package io.vertx.grpc.common.impl;

import io.grpc.Decompressor;
import io.grpc.KnownLength;
import io.grpc.MethodDescriptor;
import io.netty.buffer.ByteBufInputStream;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.buffer.impl.BufferImpl;
import io.vertx.grpc.common.GrpcMessage;
import io.vertx.grpc.common.GrpcMessageDecoder;

Expand All @@ -29,15 +33,31 @@ public BridgeMessageDecoder(MethodDescriptor.Marshaller<T> marshaller, Decompres
this.decompressor = decompressor;
}

private static class KnownLengthStream extends ByteBufInputStream implements KnownLength {
public KnownLengthStream(Buffer buffer) {
super(((BufferImpl)buffer).getByteBuf(), buffer.length());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the buffer is doesn't have any weird requirement re release ref cnt?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does create a slice but closing the ByteBufInputStream releases it

}

@Override
public void close() {
try {
super.close();
} catch (IOException ignore) {
}
}
}

@Override
public T decode(GrpcMessage msg) {
if (msg.encoding().equals("identity")) {
return marshaller.parse(new ByteArrayInputStream(msg.payload().getBytes()));
} else {
try (InputStream in = decompressor.decompress(new ByteArrayInputStream(msg.payload().getBytes()))) {
return marshaller.parse(in);
} catch (IOException e) {
throw new RuntimeException(e);
try (KnownLengthStream kls = new KnownLengthStream(msg.payload())) {
if (msg.encoding().equals("identity")) {
return marshaller.parse(kls);
} else {
try (InputStream in = decompressor.decompress(kls)) {
return marshaller.parse(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Expand Down