Skip to content

Commit

Permalink
Transform bytes to byte[] instead of ByteString
Browse files Browse the repository at this point in the history
  • Loading branch information
Duzhinsky committed Dec 8, 2023
1 parent c7d0e9d commit 17a712b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.jetbrains.annotations.NotNull;
import org.sudu.protogen.descriptors.Field;
import org.sudu.protogen.generator.GenerationContext;
import org.sudu.protogen.generator.type.BytesType;
import org.sudu.protogen.generator.type.PrimitiveTypeModel;
import org.sudu.protogen.generator.type.TypeModel;

Expand All @@ -23,14 +24,12 @@ public PrimitiveFieldTypeProcessor(@NotNull GenerationContext context) {
case DOUBLE -> boxIfNullable(field, TypeName.DOUBLE);
case BOOLEAN -> boxIfNullable(field, TypeName.BOOLEAN);
case STRING -> boxIfNullable(field, ClassName.get(String.class));
case BYTE_STRING -> new TypeModel(ClassName.get("com.google.protobuf", "ByteString"));
case BYTE_STRING -> new BytesType();
default -> next(field);
};
}

private TypeModel boxIfNullable(@NotNull Field field, TypeName primitive) {
return field.isNullable()
? new TypeModel(primitive.box())
: new PrimitiveTypeModel(primitive);
return field.isNullable() ? new TypeModel(primitive.box()) : new PrimitiveTypeModel(primitive);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.sudu.protogen.generator.type;

import com.google.protobuf.ByteString;
import com.squareup.javapoet.ArrayTypeName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.TypeName;

import java.util.Set;

public class BytesType extends TypeModel {

public BytesType() {
super(ArrayTypeName.of(TypeName.BYTE));
}

@Override
public CodeBlock toGrpcTransformer(CodeBlock expr, Set<String> usedDefinitions) {
return CodeBlock.of("$T.copyFrom($L)", ByteString.class, expr);
}

@Override
public CodeBlock fromGrpcTransformer(CodeBlock expr, Set<String> usedDefinitions) {
return CodeBlock.of("$L.toByteArray()", expr);
}
}
4 changes: 4 additions & 0 deletions tests/src/test/proto/general.proto
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,8 @@ message GrpcWithOneofs {
int32 b= 3;
}
option (.protogen.builder_for_nullable) = false;
}

message GrpcByteObject {
bytes content = 1;
}

0 comments on commit 17a712b

Please sign in to comment.