Skip to content

Commit ac7c96b

Browse files
l46kokcopybara-github
authored andcommitted
Fix bytes(string) standard function to respect evaluateCanonicalTypesToNativeValues flag
PiperOrigin-RevId: 814012812
1 parent 0c7b10f commit ac7c96b

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

bundle/src/test/java/dev/cel/bundle/CelImplTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2107,6 +2107,23 @@ public void program_evaluateCanonicalTypesToNativeTypesDisabled_producesProtoVal
21072107
assertThat(result).containsExactly(com.google.protobuf.NullValue.NULL_VALUE, expectedNestedMap);
21082108
}
21092109

2110+
@Test
2111+
public void program_evaluateCanonicalTypesToNativeTypesDisabled_producesBytesProto()
2112+
throws Exception {
2113+
Cel cel =
2114+
standardCelBuilderWithMacros()
2115+
.addMessageTypes(TestAllTypes.getDescriptor())
2116+
.setContainer(CelContainer.ofName("cel.expr.conformance.proto3"))
2117+
.setOptions(CelOptions.current().evaluateCanonicalTypesToNativeValues(false).build())
2118+
.build();
2119+
CelAbstractSyntaxTree ast =
2120+
cel.compile("TestAllTypes{single_bytes: bytes('abc')}.single_bytes").getAst();
2121+
2122+
ByteString result = (ByteString) cel.createProgram(ast).eval();
2123+
2124+
assertThat(result).isEqualTo(ByteString.copyFromUtf8("abc"));
2125+
}
2126+
21102127
@Test
21112128
public void toBuilder_isImmutable() {
21122129
CelBuilder celBuilder = CelFactory.standardCelBuilder();

runtime/src/main/java/dev/cel/runtime/standard/BytesFunction.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,15 @@ public enum BytesOverload implements CelStandardOverload {
5050
}
5151
}),
5252
STRING_TO_BYTES(
53-
(celOptions, runtimeEquality) ->
54-
CelFunctionBinding.from("string_to_bytes", String.class, CelByteString::copyFromUtf8)),
53+
(celOptions, runtimeEquality) -> {
54+
if (celOptions.evaluateCanonicalTypesToNativeValues()) {
55+
return CelFunctionBinding.from(
56+
"string_to_bytes", String.class, CelByteString::copyFromUtf8);
57+
} else {
58+
return CelFunctionBinding.from(
59+
"string_to_bytes", String.class, ByteString::copyFromUtf8);
60+
}
61+
}),
5562
;
5663

5764
private final FunctionBindingCreator bindingCreator;

0 commit comments

Comments
 (0)