diff --git a/core/src/test/scala/eu/neverblink/jelly/core/ProtoAuxiliarySpec.scala b/core/src/test/scala/eu/neverblink/jelly/core/ProtoAuxiliarySpec.scala index 6dda1d9b9..059f63bdd 100644 --- a/core/src/test/scala/eu/neverblink/jelly/core/ProtoAuxiliarySpec.scala +++ b/core/src/test/scala/eu/neverblink/jelly/core/ProtoAuxiliarySpec.scala @@ -101,6 +101,20 @@ class ProtoAuxiliarySpec extends AnyWordSpec, Matchers: } exception.getMessage should include("depth exceeded: 65") } + + "not preserve the cached size on clone()" in { + // .clone() should not preserve the cached size, as the cloned object will likely be modified + // right after cloning. + // Cloning while preserving the cached size leads to weird, hard-to-debug issues, for example: + // https://github.com/Jelly-RDF/cli/pull/126 + val frame = RdfStreamFrame.newInstance() + .addRows(RdfStreamRow.newInstance().setTriple(RdfTriple.newInstance())) + val s = frame.getSerializedSize + s should be > 0 + frame.getCachedSize should be (s) + val clonedFrame = frame.clone() + clonedFrame.getCachedSize should be(-1) + } } // Tests for the core-protos-google module diff --git a/crunchy-protoc-plugin/src/main/scala/eu/neverblink/protoc/java/gen/MessageGenerator.scala b/crunchy-protoc-plugin/src/main/scala/eu/neverblink/protoc/java/gen/MessageGenerator.scala index de4980086..bcff72dad 100644 --- a/crunchy-protoc-plugin/src/main/scala/eu/neverblink/protoc/java/gen/MessageGenerator.scala +++ b/crunchy-protoc-plugin/src/main/scala/eu/neverblink/protoc/java/gen/MessageGenerator.scala @@ -375,7 +375,11 @@ class MessageGenerator(val info: MessageInfo): .addParameter(info.typeName, "other", Modifier.FINAL) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .returns(info.mutableTypeName) - copyFrom.addStatement("cachedSize = other.cachedSize") + // Reset cached size -- definitely do not copy it from the other message, because this object + // will likely be modified right after copying, leading to an incorrect cached size. + // Cloning while preserving the cached size leads to weird, hard-to-debug issues, for example: + // https://github.com/Jelly-RDF/cli/pull/126 + copyFrom.addStatement("cachedSize = -1") fields.foreach(_.generateCopyFromCode(copyFrom)) oneOfGenerators.foreach(_.generateCopyFromCode(copyFrom)) copyFrom.addStatement("return this")