diff --git a/CHANGES.txt b/CHANGES.txt index e4eb58cebfebf..6b7517a75d4e0 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -20,6 +20,7 @@ Unreleased Changes (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) * Fix repeated enum extension size in field listener * Enable Any Text Expansion for Descriptors::DebugString() * Switch from int{8,16,32,64} to int{8,16,32,64}_t + * Reduce memory usage of the DescriptorPool type. Java * Optimized FieldDescriptor.valueOf() to avoid array copying. @@ -32,6 +33,9 @@ Unreleased Changes (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) * Fix for optimization when reading doubles from binary wire format * Replace toArray implementation with toJSON. + Kotlin + * Suppress NOTHING_TO_INLINE in Kotlin generated inline functions. + 2021-06-04 version 3.17.3 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) Python * Note: This is the last release to support Python 2.7. Future releases will diff --git a/Makefile.am b/Makefile.am index 604932cef08f0..7e16f691ef061 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1039,6 +1039,7 @@ python_EXTRA_DIST= \ python/google/protobuf/internal/packed_field_test.proto \ python/google/protobuf/internal/proto_builder_test.py \ python/google/protobuf/internal/python_message.py \ + python/google/protobuf/internal/python_protobuf.cc \ python/google/protobuf/internal/reflection_test.py \ python/google/protobuf/internal/service_reflection_test.py \ python/google/protobuf/internal/symbol_database_test.py \ @@ -1093,6 +1094,7 @@ python_EXTRA_DIST= \ python/google/protobuf/pyext/repeated_scalar_container.h \ python/google/protobuf/pyext/safe_numerics.h \ python/google/protobuf/pyext/scoped_pyobject_ptr.h \ + python/google/protobuf/python_protobuf.h \ python/google/protobuf/reflection.py \ python/google/protobuf/service.py \ python/google/protobuf/service_reflection.py \ diff --git a/benchmarks/util/result_parser.py b/benchmarks/util/result_parser.py index 896f47a105f4c..bdf3a9980a763 100644 --- a/benchmarks/util/result_parser.py +++ b/benchmarks/util/result_parser.py @@ -300,29 +300,44 @@ def get_result_from_file(cpp_file="", return __results + if __name__ == "__main__": parser = argparse.ArgumentParser() - parser.add_argument("-cpp", "--cpp_input_file", - help="The CPP benchmark result file's name", - default="") - parser.add_argument("-java", "--java_input_file", - help="The Java benchmark result file's name", - default="") - parser.add_argument("-python", "--python_input_file", - help="The Python benchmark result file's name", - default="") - parser.add_argument("-go", "--go_input_file", - help="The golang benchmark result file's name", - default="") - parser.add_argument("-node", "--node_input_file", - help="The node.js benchmark result file's name", - default="") - parser.add_argument("-php", "--php_input_file", - help="The pure php benchmark result file's name", - default="") - parser.add_argument("-php_c", "--php_c_input_file", - help="The php with c ext benchmark result file's name", - default="") + parser.add_argument( + "-cpp", + "--cpp_input_file", + help="The CPP benchmark result file's name", + default="") + parser.add_argument( + "-java", + "--java_input_file", + help="The Java benchmark result file's name", + default="") + parser.add_argument( + "-python", + "--python_input_file", + help="The Python benchmark result file's name", + default="") + parser.add_argument( + "-go", + "--go_input_file", + help="The golang benchmark result file's name", + default="") + parser.add_argument( + "-node", + "--node_input_file", + help="The node.js benchmark result file's name", + default="") + parser.add_argument( + "-php", + "--php_input_file", + help="The pure php benchmark result file's name", + default="") + parser.add_argument( + "-php_c", + "--php_c_input_file", + help="The php with c ext benchmark result file's name", + default="") args = parser.parse_args() results = get_result_from_file( diff --git a/conformance/binary_json_conformance_suite.cc b/conformance/binary_json_conformance_suite.cc index 0275e2e30b31c..b12978fa6506a 100644 --- a/conformance/binary_json_conformance_suite.cc +++ b/conformance/binary_json_conformance_suite.cc @@ -219,21 +219,21 @@ string GetNonDefaultValue(FieldDescriptor::Type type) { #define UNKNOWN_FIELD 666 enum class Packed { - UNSPECIFIED = 0, - TRUE = 1, - FALSE = 2, + kUnspecified = 0, + kTrue = 1, + kFalse = 2, }; const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type, bool repeated, bool is_proto3, - Packed packed = Packed::UNSPECIFIED) { + Packed packed = Packed::kUnspecified) { const Descriptor* d = is_proto3 ? TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor(); for (int i = 0; i < d->field_count(); i++) { const FieldDescriptor* f = d->field(i); if (f->type() == type && f->is_repeated() == repeated) { - if ((packed == Packed::TRUE && !f->is_packed()) || - (packed == Packed::FALSE && f->is_packed())) { + if ((packed == Packed::kTrue && !f->is_packed()) || + (packed == Packed::kFalse && f->is_packed())) { continue; } return f; @@ -243,10 +243,10 @@ const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type, string packed_string = ""; const string repeated_string = repeated ? "Repeated " : "Singular "; const string proto_string = is_proto3 ? "Proto3" : "Proto2"; - if (packed == Packed::TRUE) { + if (packed == Packed::kTrue) { packed_string = "Packed "; } - if (packed == Packed::FALSE) { + if (packed == Packed::kFalse) { packed_string = "Unpacked "; } GOOGLE_LOG(FATAL) << "Couldn't find field with type: " << repeated_string.c_str() @@ -796,9 +796,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( // Test repeated fields. if (FieldDescriptor::IsTypePackable(type)) { const FieldDescriptor* packed_field = - GetFieldForType(type, true, is_proto3, Packed::TRUE); + GetFieldForType(type, true, is_proto3, Packed::kTrue); const FieldDescriptor* unpacked_field = - GetFieldForType(type, true, is_proto3, Packed::FALSE); + GetFieldForType(type, true, is_proto3, Packed::kFalse); string default_proto_packed; string default_proto_unpacked; diff --git a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java index 8717f9efbbf55..2e1cc6bdcbe94 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java @@ -87,7 +87,7 @@ public static CodedInputStream newInstance(final InputStream input, int bufferSi throw new IllegalArgumentException("bufferSize must be > 0"); } if (input == null) { - // TODO(nathanmittler): Ideally we should throw here. This is done for backward compatibility. + // Ideally we would throw here. This is done for backward compatibility. return newInstance(EMPTY_BYTE_ARRAY); } return new StreamDecoder(input, bufferSize); @@ -1146,7 +1146,7 @@ public int readRawLittleEndian32() throws IOException { final byte[] buffer = this.buffer; pos = tempPos + FIXED32_SIZE; - return (((buffer[tempPos] & 0xff)) + return ((buffer[tempPos] & 0xff) | ((buffer[tempPos + 1] & 0xff) << 8) | ((buffer[tempPos + 2] & 0xff) << 16) | ((buffer[tempPos + 3] & 0xff) << 24)); @@ -1162,7 +1162,7 @@ public long readRawLittleEndian64() throws IOException { final byte[] buffer = this.buffer; pos = tempPos + FIXED64_SIZE; - return (((buffer[tempPos] & 0xffL)) + return ((buffer[tempPos] & 0xffL) | ((buffer[tempPos + 1] & 0xffL) << 8) | ((buffer[tempPos + 2] & 0xffL) << 16) | ((buffer[tempPos + 3] & 0xffL) << 24) @@ -1871,7 +1871,7 @@ public int readRawLittleEndian32() throws IOException { } pos = tempPos + FIXED32_SIZE; - return (((UnsafeUtil.getByte(tempPos) & 0xff)) + return ((UnsafeUtil.getByte(tempPos) & 0xff) | ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xff) << 24)); @@ -1886,7 +1886,7 @@ public long readRawLittleEndian64() throws IOException { } pos = tempPos + FIXED64_SIZE; - return (((UnsafeUtil.getByte(tempPos) & 0xffL)) + return ((UnsafeUtil.getByte(tempPos) & 0xffL) | ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xffL) << 24) @@ -2014,11 +2014,16 @@ private ByteBuffer slice(long begin, long end) throws IOException { int prevPos = buffer.position(); int prevLimit = buffer.limit(); try { + // Casts to Buffer here are required for Java 8 compatibility + // no matter what tricorder tells you. see + // https://issues.apache.org/jira/browse/MRESOLVER-85 ((Buffer) buffer).position(bufferPos(begin)); ((Buffer) buffer).limit(bufferPos(end)); return buffer.slice(); } catch (IllegalArgumentException e) { - throw InvalidProtocolBufferException.truncatedMessage(); + InvalidProtocolBufferException ex = InvalidProtocolBufferException.truncatedMessage(); + ex.initCause(e); + throw ex; } finally { ((Buffer) buffer).position(prevPos); ((Buffer) buffer).limit(prevLimit); @@ -2660,7 +2665,7 @@ public int readRawLittleEndian32() throws IOException { final byte[] buffer = this.buffer; pos = tempPos + FIXED32_SIZE; - return (((buffer[tempPos] & 0xff)) + return ((buffer[tempPos] & 0xff) | ((buffer[tempPos + 1] & 0xff) << 8) | ((buffer[tempPos + 2] & 0xff) << 16) | ((buffer[tempPos + 3] & 0xff) << 24)); @@ -2987,7 +2992,7 @@ private List readRawBytesSlowPathRemainingChunks(int sizeLeft) throws IO // by allocating and reading only a small chunk at a time, so that the // malicious message must actually *be* extremely large to cause // problems. Meanwhile, we limit the allowed size of a message elsewhere. - final List chunks = new ArrayList(); + final List chunks = new ArrayList<>(); while (sizeLeft > 0) { // TODO(nathanmittler): Consider using a value larger than DEFAULT_BUFFER_SIZE. @@ -3134,16 +3139,16 @@ private void skipRawBytesSlowPath(final int size) throws IOException { */ private static final class IterableDirectByteBufferDecoder extends CodedInputStream { /** The object that need to decode. */ - private Iterable input; + private final Iterable input; /** The {@link Iterator} with type {@link ByteBuffer} of {@code input} */ - private Iterator iterator; + private final Iterator iterator; /** The current ByteBuffer; */ private ByteBuffer currentByteBuffer; /** - * If {@code true}, indicates that all the buffer are backing a {@link ByteString} and are + * If {@code true}, indicates that all the buffers are backing a {@link ByteString} and are * therefore considered to be an immutable input source. */ - private boolean immutable; + private final boolean immutable; /** * If {@code true}, indicates that calls to read {@link ByteString} or {@code byte[]} * may return slices of the underlying buffer, rather than copies. @@ -3516,8 +3521,7 @@ public ByteString readBytes() throws IOException { currentByteBufferPos += size; return result; } else { - byte[] bytes; - bytes = new byte[size]; + byte[] bytes = new byte[size]; UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size); currentByteBufferPos += size; return ByteString.wrap(bytes); @@ -3738,7 +3742,7 @@ public int readRawLittleEndian32() throws IOException { if (currentRemaining() >= FIXED32_SIZE) { long tempPos = currentByteBufferPos; currentByteBufferPos += FIXED32_SIZE; - return (((UnsafeUtil.getByte(tempPos) & 0xff)) + return ((UnsafeUtil.getByte(tempPos) & 0xff) | ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xff) << 24)); @@ -3754,7 +3758,7 @@ public long readRawLittleEndian64() throws IOException { if (currentRemaining() >= FIXED64_SIZE) { long tempPos = currentByteBufferPos; currentByteBufferPos += FIXED64_SIZE; - return (((UnsafeUtil.getByte(tempPos) & 0xffL)) + return ((UnsafeUtil.getByte(tempPos) & 0xffL) | ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xffL) << 24) @@ -3875,11 +3879,6 @@ public byte[] readRawBytes(final int length) throws IOException { * Try to get raw bytes from {@code input} with the size of {@code length} and copy to {@code * bytes} array. If the size is bigger than the number of remaining bytes in the input, then * throw {@code truncatedMessage} exception. - * - * @param bytes - * @param offset - * @param length - * @throws IOException */ private void readRawBytesTo(byte[] bytes, int offset, final int length) throws IOException { if (length >= 0 && length <= remaining()) { @@ -3966,6 +3965,9 @@ private ByteBuffer slice(int begin, int end) throws IOException { int prevPos = currentByteBuffer.position(); int prevLimit = currentByteBuffer.limit(); try { + // casts to Buffer here are required for Java 8 compatibility + // no matter what tricorder tells you. see + // https://issues.apache.org/jira/browse/MRESOLVER-85 ((Buffer) currentByteBuffer).position(begin); ((Buffer) currentByteBuffer).limit(end); return currentByteBuffer.slice(); diff --git a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java index bc84595d92e94..064aa3f741339 100644 --- a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java +++ b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java @@ -57,7 +57,7 @@ *

The test mechanism employed here is based on the pattern in {@code * com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest} * - *

This test is temporarily disabled while we figure out how to fix the class loading used for + *

This test is temporarily disabled while we figure out how to fix the class loading used for * testing lite functionality. */ @SuppressWarnings("JUnit4ClassUsedInJUnit3") diff --git a/java/core/src/test/java/com/google/protobuf/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java index 936a525d980b1..27d7e692fdac9 100644 --- a/java/core/src/test/java/com/google/protobuf/TestUtil.java +++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java @@ -3758,7 +3758,9 @@ public void assertReflectionRepeatedSettersRejectNull(Message.Builder builder) /** @param filePath The path relative to {@link #getTestDataDir}. */ public static String readTextFromFile(String filePath) { - return readBytesFromFile(filePath).toStringUtf8().replace(System.getProperty("line.separator"), "\n"); + return readBytesFromFile(filePath) + .toStringUtf8() + .replace(System.getProperty("line.separator"), "\n"); } private static File getTestDataDir() { diff --git a/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt b/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt index d8982ebdadafd..206c19f1c30d7 100644 --- a/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt +++ b/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt @@ -34,14 +34,14 @@ import com.google.protobuf.ExtensionLite import com.google.protobuf.MessageLite /** - * Implementation for ExtensionList and ExtensionListLite. Like [DslList], represents an - * unmodifiable view of a repeated proto field -- in this case, an extension field -- but - * supports querying the extension. + * Implementation for ExtensionList and ExtensionListLite. Like [DslList], represents an + * unmodifiable view of a repeated proto field -- in this case, an extension field -- but supports + * querying the extension. */ -class ExtensionList @OnlyForUseByGeneratedProtoCode constructor( - val extension: ExtensionLite>, - private val delegate: List -) : List by delegate { +class ExtensionList +@OnlyForUseByGeneratedProtoCode +constructor(val extension: ExtensionLite>, private val delegate: List) : + List by delegate { override fun iterator(): Iterator = UnmodifiableIterator(delegate.iterator()) override fun listIterator(): ListIterator = UnmodifiableListIterator(delegate.listIterator()) diff --git a/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt b/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt index 65f0324281bed..f3cbf2d04ab9d 100644 --- a/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt +++ b/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt @@ -75,119 +75,110 @@ class Proto2Test { @Test fun testSetters() { assertThat( - testAllTypes { - optionalInt32 = 101 - optionalInt64 = 102 - optionalUint32 = 103 - optionalUint64 = 104 - optionalSint32 = 105 - optionalSint64 = 106 - optionalFixed32 = 107 - optionalFixed64 = 108 - optionalSfixed32 = 109 - optionalSfixed64 = 110 - optionalFloat = 111.0f - optionalDouble = 112.0 - optionalBool = true - optionalString = "115" - optionalBytes = toBytes("116") - optionalGroup = - TestAllTypesKt.optionalGroup { a = 117 } - optionalNestedMessage = nestedMessage { bb = 118 } - optionalForeignMessage = foreignMessage { c = 119 } - optionalImportMessage = - ImportMessage.newBuilder().setD(120).build() - optionalPublicImportMessage = - PublicImportMessage.newBuilder().setE(126).build() - optionalLazyMessage = nestedMessage { bb = 127 } - optionalNestedEnum = NestedEnum.BAZ - optionalForeignEnum = ForeignEnum.FOREIGN_BAZ - optionalImportEnum = ImportEnum.IMPORT_BAZ - optionalStringPiece = "124" - optionalCord = "125" - repeatedInt32.add(201) - repeatedInt64.add(202) - repeatedUint32.add(203) - repeatedUint64.add(204) - repeatedSint32.add(205) - repeatedSint64.add(206) - repeatedFixed32.add(207) - repeatedFixed64.add(208) - repeatedSfixed32.add(209) - repeatedSfixed64.add(210) - repeatedFloat.add(211f) - repeatedDouble.add(212.0) - repeatedBool.add(true) - repeatedString.add("215") - repeatedBytes.add(toBytes("216")) - repeatedGroup.add(TestAllTypesKt.repeatedGroup { a = 217 }) - repeatedNestedMessage.add(nestedMessage { bb = 218 }) - repeatedForeignMessage.add(foreignMessage { c = 219 }) - repeatedImportMessage.add( - ImportMessage.newBuilder().setD(220).build() - ) - repeatedLazyMessage.add(nestedMessage { bb = 227 }) - repeatedNestedEnum.add(NestedEnum.BAR) - repeatedForeignEnum.add(ForeignEnum.FOREIGN_BAR) - repeatedImportEnum.add(ImportEnum.IMPORT_BAR) - repeatedStringPiece.add("224") - repeatedCord.add("225") - repeatedInt32 += 301 - repeatedInt64 += 302 - repeatedUint32 += 303 - repeatedUint64 += 304 - repeatedSint32 += 305 - repeatedSint64 += 306 - repeatedFixed32 += 307 - repeatedFixed64 += 308 - repeatedSfixed32 += 309 - repeatedSfixed64 += 310 - repeatedFloat += 311f - repeatedDouble += 312.0 - repeatedBool += false - repeatedString += "315" - repeatedBytes += toBytes("316") - repeatedGroup += TestAllTypesKt.repeatedGroup { a = 317 } - repeatedNestedMessage += nestedMessage { bb = 318 } - repeatedForeignMessage += foreignMessage { c = 319 } - repeatedImportMessage += - ImportMessage.newBuilder().setD(320).build() - repeatedLazyMessage += - TestAllTypesKt.nestedMessage { bb = 327 } - repeatedNestedEnum += NestedEnum.BAZ - repeatedForeignEnum += ForeignEnum.FOREIGN_BAZ - repeatedImportEnum += ImportEnum.IMPORT_BAZ - repeatedStringPiece += "324" - repeatedCord += "325" - defaultInt32 = 401 - defaultInt64 = 402 - defaultUint32 = 403 - defaultUint64 = 404 - defaultSint32 = 405 - defaultSint64 = 406 - defaultFixed32 = 407 - defaultFixed64 = 408 - defaultSfixed32 = 409 - defaultSfixed64 = 410 - defaultFloat = 411f - defaultDouble = 412.0 - defaultBool = false - defaultString = "415" - defaultBytes = toBytes("416") - defaultNestedEnum = NestedEnum.FOO - defaultForeignEnum = ForeignEnum.FOREIGN_FOO - defaultImportEnum = ImportEnum.IMPORT_FOO - defaultStringPiece = "424" - defaultCord = "425" - oneofUint32 = 601 - oneofNestedMessage = - TestAllTypesKt.nestedMessage { bb = 602 } - oneofString = "603" - oneofBytes = toBytes("604") - } - ).isEqualTo( - TestUtil.getAllSetBuilder().build() - ) + testAllTypes { + optionalInt32 = 101 + optionalInt64 = 102 + optionalUint32 = 103 + optionalUint64 = 104 + optionalSint32 = 105 + optionalSint64 = 106 + optionalFixed32 = 107 + optionalFixed64 = 108 + optionalSfixed32 = 109 + optionalSfixed64 = 110 + optionalFloat = 111.0f + optionalDouble = 112.0 + optionalBool = true + optionalString = "115" + optionalBytes = toBytes("116") + optionalGroup = TestAllTypesKt.optionalGroup { a = 117 } + optionalNestedMessage = nestedMessage { bb = 118 } + optionalForeignMessage = foreignMessage { c = 119 } + optionalImportMessage = ImportMessage.newBuilder().setD(120).build() + optionalPublicImportMessage = PublicImportMessage.newBuilder().setE(126).build() + optionalLazyMessage = nestedMessage { bb = 127 } + optionalNestedEnum = NestedEnum.BAZ + optionalForeignEnum = ForeignEnum.FOREIGN_BAZ + optionalImportEnum = ImportEnum.IMPORT_BAZ + optionalStringPiece = "124" + optionalCord = "125" + repeatedInt32.add(201) + repeatedInt64.add(202) + repeatedUint32.add(203) + repeatedUint64.add(204) + repeatedSint32.add(205) + repeatedSint64.add(206) + repeatedFixed32.add(207) + repeatedFixed64.add(208) + repeatedSfixed32.add(209) + repeatedSfixed64.add(210) + repeatedFloat.add(211f) + repeatedDouble.add(212.0) + repeatedBool.add(true) + repeatedString.add("215") + repeatedBytes.add(toBytes("216")) + repeatedGroup.add(TestAllTypesKt.repeatedGroup { a = 217 }) + repeatedNestedMessage.add(nestedMessage { bb = 218 }) + repeatedForeignMessage.add(foreignMessage { c = 219 }) + repeatedImportMessage.add(ImportMessage.newBuilder().setD(220).build()) + repeatedLazyMessage.add(nestedMessage { bb = 227 }) + repeatedNestedEnum.add(NestedEnum.BAR) + repeatedForeignEnum.add(ForeignEnum.FOREIGN_BAR) + repeatedImportEnum.add(ImportEnum.IMPORT_BAR) + repeatedStringPiece.add("224") + repeatedCord.add("225") + repeatedInt32 += 301 + repeatedInt64 += 302 + repeatedUint32 += 303 + repeatedUint64 += 304 + repeatedSint32 += 305 + repeatedSint64 += 306 + repeatedFixed32 += 307 + repeatedFixed64 += 308 + repeatedSfixed32 += 309 + repeatedSfixed64 += 310 + repeatedFloat += 311f + repeatedDouble += 312.0 + repeatedBool += false + repeatedString += "315" + repeatedBytes += toBytes("316") + repeatedGroup += TestAllTypesKt.repeatedGroup { a = 317 } + repeatedNestedMessage += nestedMessage { bb = 318 } + repeatedForeignMessage += foreignMessage { c = 319 } + repeatedImportMessage += ImportMessage.newBuilder().setD(320).build() + repeatedLazyMessage += TestAllTypesKt.nestedMessage { bb = 327 } + repeatedNestedEnum += NestedEnum.BAZ + repeatedForeignEnum += ForeignEnum.FOREIGN_BAZ + repeatedImportEnum += ImportEnum.IMPORT_BAZ + repeatedStringPiece += "324" + repeatedCord += "325" + defaultInt32 = 401 + defaultInt64 = 402 + defaultUint32 = 403 + defaultUint64 = 404 + defaultSint32 = 405 + defaultSint64 = 406 + defaultFixed32 = 407 + defaultFixed64 = 408 + defaultSfixed32 = 409 + defaultSfixed64 = 410 + defaultFloat = 411f + defaultDouble = 412.0 + defaultBool = false + defaultString = "415" + defaultBytes = toBytes("416") + defaultNestedEnum = NestedEnum.FOO + defaultForeignEnum = ForeignEnum.FOREIGN_FOO + defaultImportEnum = ImportEnum.IMPORT_FOO + defaultStringPiece = "424" + defaultCord = "425" + oneofUint32 = 601 + oneofNestedMessage = TestAllTypesKt.nestedMessage { bb = 602 } + oneofString = "603" + oneofBytes = toBytes("604") + } + ) + .isEqualTo(TestUtil.getAllSetBuilder().build()) } @Test @@ -238,76 +229,66 @@ class Proto2Test { assertThat(repeatedString).isEqualTo(listOf("5", "2", "3", "4")) repeatedGroup.addAll( - listOf( - TestAllTypesKt.repeatedGroup { a = 1 }, - TestAllTypesKt.repeatedGroup { a = 2 } - ) + listOf(TestAllTypesKt.repeatedGroup { a = 1 }, TestAllTypesKt.repeatedGroup { a = 2 }) ) - assertThat(repeatedGroup).isEqualTo( - listOf( - TestAllTypesKt.repeatedGroup { a = 1 }, - TestAllTypesKt.repeatedGroup { a = 2 } + assertThat(repeatedGroup) + .isEqualTo( + listOf(TestAllTypesKt.repeatedGroup { a = 1 }, TestAllTypesKt.repeatedGroup { a = 2 }) ) - ) repeatedGroup += - listOf( - TestAllTypesKt.repeatedGroup { a = 3 }, - TestAllTypesKt.repeatedGroup { a = 4 } - ) - assertThat(repeatedGroup).isEqualTo( - listOf( - TestAllTypesKt.repeatedGroup { a = 1 }, - TestAllTypesKt.repeatedGroup { a = 2 }, - TestAllTypesKt.repeatedGroup { a = 3 }, - TestAllTypesKt.repeatedGroup { a = 4 } + listOf(TestAllTypesKt.repeatedGroup { a = 3 }, TestAllTypesKt.repeatedGroup { a = 4 }) + assertThat(repeatedGroup) + .isEqualTo( + listOf( + TestAllTypesKt.repeatedGroup { a = 1 }, + TestAllTypesKt.repeatedGroup { a = 2 }, + TestAllTypesKt.repeatedGroup { a = 3 }, + TestAllTypesKt.repeatedGroup { a = 4 } + ) ) - ) repeatedGroup[0] = TestAllTypesKt.repeatedGroup { a = 5 } - assertThat(repeatedGroup).isEqualTo( - listOf( - TestAllTypesKt.repeatedGroup { a = 5 }, - TestAllTypesKt.repeatedGroup { a = 2 }, - TestAllTypesKt.repeatedGroup { a = 3 }, - TestAllTypesKt.repeatedGroup { a = 4 } + assertThat(repeatedGroup) + .isEqualTo( + listOf( + TestAllTypesKt.repeatedGroup { a = 5 }, + TestAllTypesKt.repeatedGroup { a = 2 }, + TestAllTypesKt.repeatedGroup { a = 3 }, + TestAllTypesKt.repeatedGroup { a = 4 } + ) ) - ) repeatedNestedMessage.addAll(listOf(nestedMessage { bb = 1 }, nestedMessage { bb = 2 })) - assertThat(repeatedNestedMessage).isEqualTo( - listOf( - nestedMessage { bb = 1 }, - nestedMessage { bb = 2 } - ) - ) + assertThat(repeatedNestedMessage) + .isEqualTo(listOf(nestedMessage { bb = 1 }, nestedMessage { bb = 2 })) repeatedNestedMessage += listOf(nestedMessage { bb = 3 }, nestedMessage { bb = 4 }) - assertThat(repeatedNestedMessage).isEqualTo( - listOf( - nestedMessage { bb = 1 }, - nestedMessage { bb = 2 }, - nestedMessage { bb = 3 }, - nestedMessage { bb = 4 } + assertThat(repeatedNestedMessage) + .isEqualTo( + listOf( + nestedMessage { bb = 1 }, + nestedMessage { bb = 2 }, + nestedMessage { bb = 3 }, + nestedMessage { bb = 4 } + ) ) - ) repeatedNestedMessage[0] = nestedMessage { bb = 5 } - assertThat(repeatedNestedMessage).isEqualTo( - listOf( - nestedMessage { bb = 5 }, - nestedMessage { bb = 2 }, - nestedMessage { bb = 3 }, - nestedMessage { bb = 4 } + assertThat(repeatedNestedMessage) + .isEqualTo( + listOf( + nestedMessage { bb = 5 }, + nestedMessage { bb = 2 }, + nestedMessage { bb = 3 }, + nestedMessage { bb = 4 } + ) ) - ) repeatedNestedEnum.addAll(listOf(NestedEnum.FOO, NestedEnum.BAR)) assertThat(repeatedNestedEnum).isEqualTo(listOf(NestedEnum.FOO, NestedEnum.BAR)) repeatedNestedEnum += listOf(NestedEnum.BAZ, NestedEnum.FOO) - assertThat(repeatedNestedEnum).isEqualTo( - listOf(NestedEnum.FOO, NestedEnum.BAR, NestedEnum.BAZ, NestedEnum.FOO) - ) + assertThat(repeatedNestedEnum) + .isEqualTo(listOf(NestedEnum.FOO, NestedEnum.BAR, NestedEnum.BAZ, NestedEnum.FOO)) repeatedNestedEnum[0] = NestedEnum.BAR - assertThat(repeatedNestedEnum).isEqualTo( - listOf(NestedEnum.BAR, NestedEnum.BAR, NestedEnum.BAZ, NestedEnum.FOO) - ) + assertThat(repeatedNestedEnum) + .isEqualTo(listOf(NestedEnum.BAR, NestedEnum.BAR, NestedEnum.BAZ, NestedEnum.FOO)) } } @@ -380,160 +361,151 @@ class Proto2Test { optionalInt32 = 101 optionalString = "115" } - val modifiedMessage = message.copy { - optionalInt32 = 201 - } + val modifiedMessage = message.copy { optionalInt32 = 201 } - assertThat(message).isEqualTo( - TestAllTypes.newBuilder() - .setOptionalInt32(101) - .setOptionalString("115") - .build() - ) - assertThat(modifiedMessage).isEqualTo( - TestAllTypes.newBuilder() - .setOptionalInt32(201) - .setOptionalString("115") - .build() - ) + assertThat(message) + .isEqualTo(TestAllTypes.newBuilder().setOptionalInt32(101).setOptionalString("115").build()) + assertThat(modifiedMessage) + .isEqualTo(TestAllTypes.newBuilder().setOptionalInt32(201).setOptionalString("115").build()) } @Test fun testOneof() { val message = testAllTypes { oneofString = "foo" - assertThat(oneofFieldCase) - .isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_STRING) + assertThat(oneofFieldCase).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_STRING) assertThat(oneofString).isEqualTo("foo") clearOneofField() assertThat(hasOneofUint32()).isFalse() - assertThat(oneofFieldCase) - .isEqualTo(TestAllTypes.OneofFieldCase.ONEOFFIELD_NOT_SET) + assertThat(oneofFieldCase).isEqualTo(TestAllTypes.OneofFieldCase.ONEOFFIELD_NOT_SET) oneofUint32 = 5 } - assertThat(message.getOneofFieldCase()) - .isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_UINT32) + assertThat(message.getOneofFieldCase()).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_UINT32) assertThat(message.getOneofUint32()).isEqualTo(5) } @Test fun testExtensionsSet() { assertThat( - testAllExtensions { - this[UnittestProto.optionalInt32Extension] = 101 - this[UnittestProto.optionalInt64Extension] = 102L - this[UnittestProto.optionalUint32Extension] = 103 - this[UnittestProto.optionalUint64Extension] = 104L - this[UnittestProto.optionalSint32Extension] = 105 - this[UnittestProto.optionalSint64Extension] = 106L - this[UnittestProto.optionalFixed32Extension] = 107 - this[UnittestProto.optionalFixed64Extension] = 108L - this[UnittestProto.optionalSfixed32Extension] = 109 - this[UnittestProto.optionalSfixed64Extension] = 110L - this[UnittestProto.optionalFloatExtension] = 111F - this[UnittestProto.optionalDoubleExtension] = 112.0 - this[UnittestProto.optionalBoolExtension] = true - this[UnittestProto.optionalStringExtension] = "115" - this[UnittestProto.optionalBytesExtension] = toBytes("116") - this[UnittestProto.optionalGroupExtension] = optionalGroupExtension { a = 117 } - this[UnittestProto.optionalNestedMessageExtension] = - TestAllTypesKt.nestedMessage { bb = 118 } - this[UnittestProto.optionalForeignMessageExtension] = foreignMessage { c = 119 } - this[UnittestProto.optionalImportMessageExtension] = - ImportMessage.newBuilder().setD(120).build() - this[UnittestProto.optionalPublicImportMessageExtension] = - PublicImportMessage.newBuilder().setE(126).build() - this[UnittestProto.optionalLazyMessageExtension] = TestAllTypesKt.nestedMessage { bb = 127 } - this[UnittestProto.optionalNestedEnumExtension] = NestedEnum.BAZ - this[UnittestProto.optionalForeignEnumExtension] = ForeignEnum.FOREIGN_BAZ - this[UnittestProto.optionalImportEnumExtension] = ImportEnum.IMPORT_BAZ - this[UnittestProto.optionalStringPieceExtension] = "124" - this[UnittestProto.optionalCordExtension] = "125" - this[UnittestProto.repeatedInt32Extension].add(201) - this[UnittestProto.repeatedInt64Extension].add(202L) - this[UnittestProto.repeatedUint32Extension].add(203) - this[UnittestProto.repeatedUint64Extension].add(204L) - this[UnittestProto.repeatedSint32Extension].add(205) - this[UnittestProto.repeatedSint64Extension].add(206L) - this[UnittestProto.repeatedFixed32Extension].add(207) - this[UnittestProto.repeatedFixed64Extension].add(208L) - this[UnittestProto.repeatedSfixed32Extension].add(209) - this[UnittestProto.repeatedSfixed64Extension].add(210L) - this[UnittestProto.repeatedFloatExtension].add(211F) - this[UnittestProto.repeatedDoubleExtension].add(212.0) - this[UnittestProto.repeatedBoolExtension].add(true) - this[UnittestProto.repeatedStringExtension].add("215") - this[UnittestProto.repeatedBytesExtension].add(toBytes("216")) - this[UnittestProto.repeatedGroupExtension].add(repeatedGroupExtension { a = 217 }) - this[UnittestProto.repeatedNestedMessageExtension] - .add(TestAllTypesKt.nestedMessage { bb = 218 }) - this[UnittestProto.repeatedForeignMessageExtension].add(foreignMessage { c = 219 }) - this[UnittestProto.repeatedImportMessageExtension] - .add(ImportMessage.newBuilder().setD(220).build()) - this[UnittestProto.repeatedLazyMessageExtension] - .add(TestAllTypesKt.nestedMessage { bb = 227 }) - this[UnittestProto.repeatedNestedEnumExtension].add(NestedEnum.BAR) - this[UnittestProto.repeatedForeignEnumExtension].add(ForeignEnum.FOREIGN_BAR) - this[UnittestProto.repeatedImportEnumExtension].add(ImportEnum.IMPORT_BAR) - this[UnittestProto.repeatedStringPieceExtension].add("224") - this[UnittestProto.repeatedCordExtension].add("225") - this[UnittestProto.repeatedInt32Extension] += 301 - this[UnittestProto.repeatedInt64Extension] += 302L - this[UnittestProto.repeatedUint32Extension] += 303 - this[UnittestProto.repeatedUint64Extension] += 304L - this[UnittestProto.repeatedSint32Extension] += 305 - this[UnittestProto.repeatedSint64Extension] += 306L - this[UnittestProto.repeatedFixed32Extension] += 307 - this[UnittestProto.repeatedFixed64Extension] += 308L - this[UnittestProto.repeatedSfixed32Extension] += 309 - this[UnittestProto.repeatedSfixed64Extension] += 310L - this[UnittestProto.repeatedFloatExtension] += 311F - this[UnittestProto.repeatedDoubleExtension] += 312.0 - this[UnittestProto.repeatedBoolExtension] += false - this[UnittestProto.repeatedStringExtension] += "315" - this[UnittestProto.repeatedBytesExtension] += toBytes("316") - this[UnittestProto.repeatedGroupExtension] += repeatedGroupExtension { a = 317 } - this[UnittestProto.repeatedNestedMessageExtension] += - TestAllTypesKt.nestedMessage { bb = 318 } - this[UnittestProto.repeatedForeignMessageExtension] += foreignMessage { c = 319 } - this[UnittestProto.repeatedImportMessageExtension] += - ImportMessage.newBuilder().setD(320).build() - this[UnittestProto.repeatedLazyMessageExtension] += - TestAllTypesKt.nestedMessage { bb = 327 } - this[UnittestProto.repeatedNestedEnumExtension] += NestedEnum.BAZ - this[UnittestProto.repeatedForeignEnumExtension] += ForeignEnum.FOREIGN_BAZ - this[UnittestProto.repeatedImportEnumExtension] += ImportEnum.IMPORT_BAZ - this[UnittestProto.repeatedStringPieceExtension] += "324" - this[UnittestProto.repeatedCordExtension] += "325" - this[UnittestProto.defaultInt32Extension] = 401 - this[UnittestProto.defaultInt64Extension] = 402L - this[UnittestProto.defaultUint32Extension] = 403 - this[UnittestProto.defaultUint64Extension] = 404L - this[UnittestProto.defaultSint32Extension] = 405 - this[UnittestProto.defaultSint64Extension] = 406L - this[UnittestProto.defaultFixed32Extension] = 407 - this[UnittestProto.defaultFixed64Extension] = 408L - this[UnittestProto.defaultSfixed32Extension] = 409 - this[UnittestProto.defaultSfixed64Extension] = 410L - this[UnittestProto.defaultFloatExtension] = 411F - this[UnittestProto.defaultDoubleExtension] = 412.0 - this[UnittestProto.defaultBoolExtension] = false - this[UnittestProto.defaultStringExtension] = "415" - this[UnittestProto.defaultBytesExtension] = toBytes("416") - this[UnittestProto.defaultNestedEnumExtension] = NestedEnum.FOO - this[UnittestProto.defaultForeignEnumExtension] = ForeignEnum.FOREIGN_FOO - this[UnittestProto.defaultImportEnumExtension] = ImportEnum.IMPORT_FOO - this[UnittestProto.defaultStringPieceExtension] = "424" - this[UnittestProto.defaultCordExtension] = "425" - this[UnittestProto.oneofUint32Extension] = 601 - this[UnittestProto.oneofNestedMessageExtension] = TestAllTypesKt.nestedMessage { bb = 602 } - this[UnittestProto.oneofStringExtension] = "603" - this[UnittestProto.oneofBytesExtension] = toBytes("604") - } - ).isEqualTo( - TestUtil.getAllExtensionsSet() - ) + testAllExtensions { + this[UnittestProto.optionalInt32Extension] = 101 + this[UnittestProto.optionalInt64Extension] = 102L + this[UnittestProto.optionalUint32Extension] = 103 + this[UnittestProto.optionalUint64Extension] = 104L + this[UnittestProto.optionalSint32Extension] = 105 + this[UnittestProto.optionalSint64Extension] = 106L + this[UnittestProto.optionalFixed32Extension] = 107 + this[UnittestProto.optionalFixed64Extension] = 108L + this[UnittestProto.optionalSfixed32Extension] = 109 + this[UnittestProto.optionalSfixed64Extension] = 110L + this[UnittestProto.optionalFloatExtension] = 111F + this[UnittestProto.optionalDoubleExtension] = 112.0 + this[UnittestProto.optionalBoolExtension] = true + this[UnittestProto.optionalStringExtension] = "115" + this[UnittestProto.optionalBytesExtension] = toBytes("116") + this[UnittestProto.optionalGroupExtension] = optionalGroupExtension { a = 117 } + this[UnittestProto.optionalNestedMessageExtension] = + TestAllTypesKt.nestedMessage { bb = 118 } + this[UnittestProto.optionalForeignMessageExtension] = foreignMessage { c = 119 } + this[UnittestProto.optionalImportMessageExtension] = + ImportMessage.newBuilder().setD(120).build() + this[UnittestProto.optionalPublicImportMessageExtension] = + PublicImportMessage.newBuilder().setE(126).build() + this[UnittestProto.optionalLazyMessageExtension] = + TestAllTypesKt.nestedMessage { bb = 127 } + this[UnittestProto.optionalNestedEnumExtension] = NestedEnum.BAZ + this[UnittestProto.optionalForeignEnumExtension] = ForeignEnum.FOREIGN_BAZ + this[UnittestProto.optionalImportEnumExtension] = ImportEnum.IMPORT_BAZ + this[UnittestProto.optionalStringPieceExtension] = "124" + this[UnittestProto.optionalCordExtension] = "125" + this[UnittestProto.repeatedInt32Extension].add(201) + this[UnittestProto.repeatedInt64Extension].add(202L) + this[UnittestProto.repeatedUint32Extension].add(203) + this[UnittestProto.repeatedUint64Extension].add(204L) + this[UnittestProto.repeatedSint32Extension].add(205) + this[UnittestProto.repeatedSint64Extension].add(206L) + this[UnittestProto.repeatedFixed32Extension].add(207) + this[UnittestProto.repeatedFixed64Extension].add(208L) + this[UnittestProto.repeatedSfixed32Extension].add(209) + this[UnittestProto.repeatedSfixed64Extension].add(210L) + this[UnittestProto.repeatedFloatExtension].add(211F) + this[UnittestProto.repeatedDoubleExtension].add(212.0) + this[UnittestProto.repeatedBoolExtension].add(true) + this[UnittestProto.repeatedStringExtension].add("215") + this[UnittestProto.repeatedBytesExtension].add(toBytes("216")) + this[UnittestProto.repeatedGroupExtension].add(repeatedGroupExtension { a = 217 }) + this[UnittestProto.repeatedNestedMessageExtension].add( + TestAllTypesKt.nestedMessage { bb = 218 } + ) + this[UnittestProto.repeatedForeignMessageExtension].add(foreignMessage { c = 219 }) + this[UnittestProto.repeatedImportMessageExtension].add( + ImportMessage.newBuilder().setD(220).build() + ) + this[UnittestProto.repeatedLazyMessageExtension].add( + TestAllTypesKt.nestedMessage { bb = 227 } + ) + this[UnittestProto.repeatedNestedEnumExtension].add(NestedEnum.BAR) + this[UnittestProto.repeatedForeignEnumExtension].add(ForeignEnum.FOREIGN_BAR) + this[UnittestProto.repeatedImportEnumExtension].add(ImportEnum.IMPORT_BAR) + this[UnittestProto.repeatedStringPieceExtension].add("224") + this[UnittestProto.repeatedCordExtension].add("225") + this[UnittestProto.repeatedInt32Extension] += 301 + this[UnittestProto.repeatedInt64Extension] += 302L + this[UnittestProto.repeatedUint32Extension] += 303 + this[UnittestProto.repeatedUint64Extension] += 304L + this[UnittestProto.repeatedSint32Extension] += 305 + this[UnittestProto.repeatedSint64Extension] += 306L + this[UnittestProto.repeatedFixed32Extension] += 307 + this[UnittestProto.repeatedFixed64Extension] += 308L + this[UnittestProto.repeatedSfixed32Extension] += 309 + this[UnittestProto.repeatedSfixed64Extension] += 310L + this[UnittestProto.repeatedFloatExtension] += 311F + this[UnittestProto.repeatedDoubleExtension] += 312.0 + this[UnittestProto.repeatedBoolExtension] += false + this[UnittestProto.repeatedStringExtension] += "315" + this[UnittestProto.repeatedBytesExtension] += toBytes("316") + this[UnittestProto.repeatedGroupExtension] += repeatedGroupExtension { a = 317 } + this[UnittestProto.repeatedNestedMessageExtension] += + TestAllTypesKt.nestedMessage { bb = 318 } + this[UnittestProto.repeatedForeignMessageExtension] += foreignMessage { c = 319 } + this[UnittestProto.repeatedImportMessageExtension] += + ImportMessage.newBuilder().setD(320).build() + this[UnittestProto.repeatedLazyMessageExtension] += + TestAllTypesKt.nestedMessage { bb = 327 } + this[UnittestProto.repeatedNestedEnumExtension] += NestedEnum.BAZ + this[UnittestProto.repeatedForeignEnumExtension] += ForeignEnum.FOREIGN_BAZ + this[UnittestProto.repeatedImportEnumExtension] += ImportEnum.IMPORT_BAZ + this[UnittestProto.repeatedStringPieceExtension] += "324" + this[UnittestProto.repeatedCordExtension] += "325" + this[UnittestProto.defaultInt32Extension] = 401 + this[UnittestProto.defaultInt64Extension] = 402L + this[UnittestProto.defaultUint32Extension] = 403 + this[UnittestProto.defaultUint64Extension] = 404L + this[UnittestProto.defaultSint32Extension] = 405 + this[UnittestProto.defaultSint64Extension] = 406L + this[UnittestProto.defaultFixed32Extension] = 407 + this[UnittestProto.defaultFixed64Extension] = 408L + this[UnittestProto.defaultSfixed32Extension] = 409 + this[UnittestProto.defaultSfixed64Extension] = 410L + this[UnittestProto.defaultFloatExtension] = 411F + this[UnittestProto.defaultDoubleExtension] = 412.0 + this[UnittestProto.defaultBoolExtension] = false + this[UnittestProto.defaultStringExtension] = "415" + this[UnittestProto.defaultBytesExtension] = toBytes("416") + this[UnittestProto.defaultNestedEnumExtension] = NestedEnum.FOO + this[UnittestProto.defaultForeignEnumExtension] = ForeignEnum.FOREIGN_FOO + this[UnittestProto.defaultImportEnumExtension] = ImportEnum.IMPORT_FOO + this[UnittestProto.defaultStringPieceExtension] = "424" + this[UnittestProto.defaultCordExtension] = "425" + this[UnittestProto.oneofUint32Extension] = 601 + this[UnittestProto.oneofNestedMessageExtension] = + TestAllTypesKt.nestedMessage { bb = 602 } + this[UnittestProto.oneofStringExtension] = "603" + this[UnittestProto.oneofBytesExtension] = toBytes("604") + } + ) + .isEqualTo(TestUtil.getAllExtensionsSet()) } @Test @@ -546,8 +518,7 @@ class Proto2Test { this[UnittestProto.optionalGroupExtension] = optionalGroupExtension { a = 117 } assertThat(this[UnittestProto.optionalGroupExtension]) .isEqualTo(optionalGroupExtension { a = 117 }) - this[UnittestProto.optionalNestedMessageExtension] = - TestAllTypesKt.nestedMessage { bb = 118 } + this[UnittestProto.optionalNestedMessageExtension] = TestAllTypesKt.nestedMessage { bb = 118 } assertThat(this[UnittestProto.optionalNestedMessageExtension]) .isEqualTo(TestAllTypesKt.nestedMessage { bb = 118 }) this[UnittestProto.optionalNestedEnumExtension] = NestedEnum.BAZ @@ -577,74 +548,65 @@ class Proto2Test { assertThat(this[UnittestProto.repeatedStringExtension]).isEqualTo(listOf("5", "2", "3", "4")) this[UnittestProto.repeatedGroupExtension].addAll( - listOf( - repeatedGroupExtension { a = 1 }, - repeatedGroupExtension { a = 2 } - ) - ) - assertThat(this[UnittestProto.repeatedGroupExtension]).isEqualTo( - listOf( - repeatedGroupExtension { a = 1 }, - repeatedGroupExtension { a = 2 } - ) + listOf(repeatedGroupExtension { a = 1 }, repeatedGroupExtension { a = 2 }) ) + assertThat(this[UnittestProto.repeatedGroupExtension]) + .isEqualTo(listOf(repeatedGroupExtension { a = 1 }, repeatedGroupExtension { a = 2 })) this[UnittestProto.repeatedGroupExtension] += - listOf( - repeatedGroupExtension { a = 3 }, - repeatedGroupExtension { a = 4 } - ) - assertThat(this[UnittestProto.repeatedGroupExtension]).isEqualTo( - listOf( - repeatedGroupExtension { a = 1 }, - repeatedGroupExtension { a = 2 }, - repeatedGroupExtension { a = 3 }, - repeatedGroupExtension { a = 4 } + listOf(repeatedGroupExtension { a = 3 }, repeatedGroupExtension { a = 4 }) + assertThat(this[UnittestProto.repeatedGroupExtension]) + .isEqualTo( + listOf( + repeatedGroupExtension { a = 1 }, + repeatedGroupExtension { a = 2 }, + repeatedGroupExtension { a = 3 }, + repeatedGroupExtension { a = 4 } + ) ) - ) this[UnittestProto.repeatedGroupExtension][0] = repeatedGroupExtension { a = 5 } - assertThat(this[UnittestProto.repeatedGroupExtension]).isEqualTo( - listOf( - repeatedGroupExtension { a = 5 }, - repeatedGroupExtension { a = 2 }, - repeatedGroupExtension { a = 3 }, - repeatedGroupExtension { a = 4 } + assertThat(this[UnittestProto.repeatedGroupExtension]) + .isEqualTo( + listOf( + repeatedGroupExtension { a = 5 }, + repeatedGroupExtension { a = 2 }, + repeatedGroupExtension { a = 3 }, + repeatedGroupExtension { a = 4 } + ) ) - ) this[UnittestProto.repeatedNestedMessageExtension].addAll( listOf(nestedMessage { bb = 1 }, nestedMessage { bb = 2 }) ) - assertThat(this[UnittestProto.repeatedNestedMessageExtension]).isEqualTo( - listOf(nestedMessage { bb = 1 }, nestedMessage { bb = 2 }) - ) + assertThat(this[UnittestProto.repeatedNestedMessageExtension]) + .isEqualTo(listOf(nestedMessage { bb = 1 }, nestedMessage { bb = 2 })) this[UnittestProto.repeatedNestedMessageExtension] += listOf(nestedMessage { bb = 3 }, nestedMessage { bb = 4 }) - assertThat(this[UnittestProto.repeatedNestedMessageExtension]).isEqualTo( - listOf( - nestedMessage { bb = 1 }, - nestedMessage { bb = 2 }, - nestedMessage { bb = 3 }, - nestedMessage { bb = 4 } + assertThat(this[UnittestProto.repeatedNestedMessageExtension]) + .isEqualTo( + listOf( + nestedMessage { bb = 1 }, + nestedMessage { bb = 2 }, + nestedMessage { bb = 3 }, + nestedMessage { bb = 4 } + ) ) - ) this[UnittestProto.repeatedNestedMessageExtension][0] = nestedMessage { bb = 5 } - assertThat(this[UnittestProto.repeatedNestedMessageExtension]).isEqualTo( - listOf( - nestedMessage { bb = 5 }, - nestedMessage { bb = 2 }, - nestedMessage { bb = 3 }, - nestedMessage { bb = 4 } + assertThat(this[UnittestProto.repeatedNestedMessageExtension]) + .isEqualTo( + listOf( + nestedMessage { bb = 5 }, + nestedMessage { bb = 2 }, + nestedMessage { bb = 3 }, + nestedMessage { bb = 4 } + ) ) - ) - this[UnittestProto.repeatedNestedEnumExtension] - .addAll(listOf(NestedEnum.FOO, NestedEnum.BAR)) + this[UnittestProto.repeatedNestedEnumExtension].addAll(listOf(NestedEnum.FOO, NestedEnum.BAR)) assertThat(this[UnittestProto.repeatedNestedEnumExtension]) .isEqualTo(listOf(NestedEnum.FOO, NestedEnum.BAR)) this[UnittestProto.repeatedNestedEnumExtension] += listOf(NestedEnum.BAZ, NestedEnum.FOO) - assertThat(this[UnittestProto.repeatedNestedEnumExtension]).isEqualTo( - listOf(NestedEnum.FOO, NestedEnum.BAR, NestedEnum.BAZ, NestedEnum.FOO) - ) + assertThat(this[UnittestProto.repeatedNestedEnumExtension]) + .isEqualTo(listOf(NestedEnum.FOO, NestedEnum.BAR, NestedEnum.BAZ, NestedEnum.FOO)) } } @@ -669,8 +631,7 @@ class Proto2Test { this[UnittestProto.optionalStringExtension] = "115" assertThat(contains(UnittestProto.optionalStringExtension)).isTrue() assertThat(contains(UnittestProto.optionalGroupExtension)).isFalse() - this[UnittestProto.optionalNestedMessageExtension] = - TestAllTypesKt.nestedMessage { bb = 118 } + this[UnittestProto.optionalNestedMessageExtension] = TestAllTypesKt.nestedMessage { bb = 118 } assertThat(contains(UnittestProto.optionalNestedMessageExtension)).isTrue() assertThat(contains(UnittestProto.optionalNestedEnumExtension)).isFalse() this[UnittestProto.defaultInt32Extension] = 401 @@ -694,8 +655,7 @@ class Proto2Test { clear(UnittestProto.optionalGroupExtension) assertThat(contains(UnittestProto.optionalGroupExtension)).isFalse() - this[UnittestProto.optionalNestedMessageExtension] = - TestAllTypesKt.nestedMessage { bb = 118 } + this[UnittestProto.optionalNestedMessageExtension] = TestAllTypesKt.nestedMessage { bb = 118 } clear(UnittestProto.optionalNestedMessageExtension) assertThat(contains(UnittestProto.optionalNestedMessageExtension)).isFalse() @@ -711,80 +671,66 @@ class Proto2Test { @Test fun testEmptyMessages() { - assertThat( - testEmptyMessage {} - ).isEqualTo( - TestEmptyMessage.newBuilder().build() - ) + assertThat(testEmptyMessage {}).isEqualTo(TestEmptyMessage.newBuilder().build()) - assertThat( - testEmptyMessageWithExtensions {} - ).isEqualTo( - TestEmptyMessageWithExtensions.newBuilder().build() - ) + assertThat(testEmptyMessageWithExtensions {}) + .isEqualTo(TestEmptyMessageWithExtensions.newBuilder().build()) } @Test fun testMapSetters() { val intMap = testIntIntMap { m[1] = 2 } - assertThat(intMap).isEqualTo( - TestIntIntMap.newBuilder().putM(1, 2).build() - ) + assertThat(intMap).isEqualTo(TestIntIntMap.newBuilder().putM(1, 2).build()) assertThat( - testMaps { - mInt32[1] = intMap - mInt64[1L] = intMap - mUint32[1] = intMap - mUint64[1L] = intMap - mSint32[1] = intMap - mSint64[1L] = intMap - mFixed32[1] = intMap - mFixed64[1L] = intMap - mSfixed32[1] = intMap - mSfixed64[1] = intMap - mBool[true] = intMap - mString["1"] = intMap - } - ).isEqualTo( - TestMaps.newBuilder() - .putMInt32(1, intMap) - .putMInt64(1L, intMap) - .putMUint32(1, intMap) - .putMUint64(1L, intMap) - .putMSint32(1, intMap) - .putMSint64(1L, intMap) - .putMFixed32(1, intMap) - .putMFixed64(1L, intMap) - .putMSfixed32(1, intMap) - .putMSfixed64(1L, intMap) - .putMBool(true, intMap) - .putMString("1", intMap) - .build() - ) + testMaps { + mInt32[1] = intMap + mInt64[1L] = intMap + mUint32[1] = intMap + mUint64[1L] = intMap + mSint32[1] = intMap + mSint64[1L] = intMap + mFixed32[1] = intMap + mFixed64[1L] = intMap + mSfixed32[1] = intMap + mSfixed64[1] = intMap + mBool[true] = intMap + mString["1"] = intMap + } + ) + .isEqualTo( + TestMaps.newBuilder() + .putMInt32(1, intMap) + .putMInt64(1L, intMap) + .putMUint32(1, intMap) + .putMUint64(1L, intMap) + .putMSint32(1, intMap) + .putMSint64(1L, intMap) + .putMFixed32(1, intMap) + .putMFixed64(1L, intMap) + .putMSfixed32(1, intMap) + .putMSfixed64(1L, intMap) + .putMBool(true, intMap) + .putMString("1", intMap) + .build() + ) - assertThat( - testEnumMap { - knownMapField[1] = Proto2MapEnum.PROTO2_MAP_ENUM_FOO - } - ).isEqualTo( - TestEnumMap.newBuilder() - .putKnownMapField(1, Proto2MapEnum.PROTO2_MAP_ENUM_FOO) - .build() - ) + assertThat(testEnumMap { knownMapField[1] = Proto2MapEnum.PROTO2_MAP_ENUM_FOO }) + .isEqualTo( + TestEnumMap.newBuilder().putKnownMapField(1, Proto2MapEnum.PROTO2_MAP_ENUM_FOO).build() + ) } @Test fun testMapGettersAndSetters() { - val intMap = - testIntIntMap { - m.put(1, 2) - assertThat(m).isEqualTo(mapOf(1 to 2)) - m[3] = 4 - assertThat(m).isEqualTo(mapOf(1 to 2, 3 to 4)) - m.putAll(mapOf(5 to 6, 7 to 8)) - assertThat(m).isEqualTo(mapOf(1 to 2, 3 to 4, 5 to 6, 7 to 8)) - } + val intMap = testIntIntMap { + m.put(1, 2) + assertThat(m).isEqualTo(mapOf(1 to 2)) + m[3] = 4 + assertThat(m).isEqualTo(mapOf(1 to 2, 3 to 4)) + m.putAll(mapOf(5 to 6, 7 to 8)) + assertThat(m).isEqualTo(mapOf(1 to 2, 3 to 4, 5 to 6, 7 to 8)) + } testMaps { mInt32.put(1, intMap) @@ -799,40 +745,40 @@ class Proto2Test { mString["2"] = intMap assertThat(mString).isEqualTo(mapOf("1" to intMap, "2" to intMap)) mString.putAll(mapOf("3" to intMap, "4" to intMap)) - assertThat(mString).isEqualTo( - mapOf("1" to intMap, "2" to intMap, "3" to intMap, "4" to intMap) - ) + assertThat(mString) + .isEqualTo(mapOf("1" to intMap, "2" to intMap, "3" to intMap, "4" to intMap)) } testEnumMap { knownMapField.put(1, Proto2MapEnum.PROTO2_MAP_ENUM_FOO) assertThat(knownMapField).isEqualTo(mapOf(1 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO)) knownMapField[2] = Proto2MapEnum.PROTO2_MAP_ENUM_BAR - assertThat(knownMapField).isEqualTo( - mapOf(1 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO, 2 to Proto2MapEnum.PROTO2_MAP_ENUM_BAR) - ) + assertThat(knownMapField) + .isEqualTo( + mapOf(1 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO, 2 to Proto2MapEnum.PROTO2_MAP_ENUM_BAR) + ) knownMapField.putAll( mapOf(3 to Proto2MapEnum.PROTO2_MAP_ENUM_BAZ, 4 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO) ) - assertThat(knownMapField).isEqualTo( - mapOf( - 1 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO, - 2 to Proto2MapEnum.PROTO2_MAP_ENUM_BAR, - 3 to Proto2MapEnum.PROTO2_MAP_ENUM_BAZ, - 4 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO + assertThat(knownMapField) + .isEqualTo( + mapOf( + 1 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO, + 2 to Proto2MapEnum.PROTO2_MAP_ENUM_BAR, + 3 to Proto2MapEnum.PROTO2_MAP_ENUM_BAZ, + 4 to Proto2MapEnum.PROTO2_MAP_ENUM_FOO + ) ) - ) } } @Test fun testMapRemove() { - val intMap = - testIntIntMap { - m.putAll(mapOf(1 to 2, 3 to 4)) - m.remove(1) - assertThat(m).isEqualTo(mapOf(3 to 4)) - } + val intMap = testIntIntMap { + m.putAll(mapOf(1 to 2, 3 to 4)) + m.remove(1) + assertThat(m).isEqualTo(mapOf(3 to 4)) + } testMaps { mInt32.putAll(mapOf(1 to intMap, 2 to intMap)) @@ -855,12 +801,11 @@ class Proto2Test { @Test fun testMapClear() { - val intMap = - testIntIntMap { - m.putAll(mapOf(1 to 2, 3 to 4)) - m.clear() - assertThat(m.isEmpty()).isTrue() - } + val intMap = testIntIntMap { + m.putAll(mapOf(1 to 2, 3 to 4)) + m.clear() + assertThat(m.isEmpty()).isTrue() + } testMaps { mInt32.putAll(mapOf(1 to intMap, 2 to intMap)) @@ -884,56 +829,57 @@ class Proto2Test { @Test fun testEvilNames() { assertThat( - evilNamesProto2 { - initialized = true - hasFoo = true - bar = "foo" - isInitialized = true - fooBar = "foo" - aLLCAPS += "foo" - aLLCAPSMAP[1] = true - hasUnderbarPrecedingNumeric1Foo = true - hasUnderbarPrecedingNumeric42Bar = true - hasUnderbarPrecedingNumeric123Foo42BarBaz = true - extension += "foo" - class_ += 1 - int = 1.0 - long = true - boolean = 1L - sealed = "foo" - interface_ = 1F - in_ = 1 - object_ = "foo" - cachedSize_ = "foo" - serializedSize_ = true - by = "foo" - } - ).isEqualTo( - EvilNamesProto2.newBuilder() - .setInitialized(true) - .setHasFoo(true) - .setBar("foo") - .setIsInitialized(true) - .setFooBar("foo") - .addALLCAPS("foo") - .putALLCAPSMAP(1, true) - .setHasUnderbarPrecedingNumeric1Foo(true) - .setHasUnderbarPrecedingNumeric42Bar(true) - .setHasUnderbarPrecedingNumeric123Foo42BarBaz(true) - .addExtension("foo") - .addClass_(1) - .setInt(1.0) - .setLong(true) - .setBoolean(1L) - .setSealed("foo") - .setInterface(1F) - .setIn(1) - .setObject("foo") - .setCachedSize_("foo") - .setSerializedSize_(true) - .setBy("foo") - .build() - ) + evilNamesProto2 { + initialized = true + hasFoo = true + bar = "foo" + isInitialized = true + fooBar = "foo" + aLLCAPS += "foo" + aLLCAPSMAP[1] = true + hasUnderbarPrecedingNumeric1Foo = true + hasUnderbarPrecedingNumeric42Bar = true + hasUnderbarPrecedingNumeric123Foo42BarBaz = true + extension += "foo" + class_ += 1 + int = 1.0 + long = true + boolean = 1L + sealed = "foo" + interface_ = 1F + in_ = 1 + object_ = "foo" + cachedSize_ = "foo" + serializedSize_ = true + by = "foo" + } + ) + .isEqualTo( + EvilNamesProto2.newBuilder() + .setInitialized(true) + .setHasFoo(true) + .setBar("foo") + .setIsInitialized(true) + .setFooBar("foo") + .addALLCAPS("foo") + .putALLCAPSMAP(1, true) + .setHasUnderbarPrecedingNumeric1Foo(true) + .setHasUnderbarPrecedingNumeric42Bar(true) + .setHasUnderbarPrecedingNumeric123Foo42BarBaz(true) + .addExtension("foo") + .addClass_(1) + .setInt(1.0) + .setLong(true) + .setBoolean(1L) + .setSealed("foo") + .setInterface(1F) + .setIn(1) + .setObject("foo") + .setCachedSize_("foo") + .setSerializedSize_(true) + .setBy("foo") + .build() + ) assertThat(interface_ {}).isEqualTo(Interface.newBuilder().build()) } diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java index 2de2bd1aa2f81..a6cdcb995765c 100644 --- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java +++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java @@ -400,19 +400,12 @@ public static void merge(FieldMask mask, Message source, Message.Builder destina } /** - * Returns the result of merging the given proto with the given mask and a default instance. - */ - public static

P trim(FieldMask mask, P source) { - return trim(mask, source, new MergeOptions()); - } - - /** - * Returns the result of merging the given proto with the given mask and a default instance. + * Returns the result of keeping only the masked fields of the given proto. */ @SuppressWarnings("unchecked") - public static

P trim(FieldMask mask, P source, MergeOptions options) { - Message.Builder destination = source.newBuilderForType(); - merge(mask, source, destination, options); + public static

P trim(FieldMask mask, P source) { + Message.Builder destination = source.newBuilderForType(); + merge(mask, source, destination); return (P) destination.build(); } } diff --git a/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java b/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java index 367fe52f846a0..79fa37611044d 100644 --- a/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java +++ b/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java @@ -288,4 +288,28 @@ public void testMerge() throws Exception { FieldMaskUtil.merge(FieldMaskUtil.fromString("payload"), source, builder); assertThat(builder.getPayload().getOptionalInt32()).isEqualTo(1234); } + + @Test + public void testTrim() throws Exception { + NestedTestAllTypes source = + NestedTestAllTypes.newBuilder() + .setPayload( + TestAllTypes.newBuilder() + .setOptionalInt32(1234) + .setOptionalString("1234") + .setOptionalBool(true)) + .build(); + FieldMask mask = + FieldMaskUtil.fromStringList( + ImmutableList.of("payload.optional_int32", "payload.optional_string")); + + NestedTestAllTypes actual = FieldMaskUtil.trim(mask, source); + + assertThat(actual) + .isEqualTo( + NestedTestAllTypes.newBuilder() + .setPayload( + TestAllTypes.newBuilder().setOptionalInt32(1234).setOptionalString("1234")) + .build()); + } } diff --git a/js/gulpfile.js b/js/gulpfile.js index dea5f410c78bc..00a6d64f98b2c 100644 --- a/js/gulpfile.js +++ b/js/gulpfile.js @@ -145,55 +145,50 @@ function getClosureCompilerCommand(exportsFile, outputFile) { return [ 'node_modules/.bin/google-closure-compiler', `--js=${closureLib}/closure/goog/**.js`, - `--js=${closureLib}/third_party/closure/goog/**.js`, - '--js=map.js', - '--js=message.js', - '--js=binary/arith.js', - '--js=binary/constants.js', - '--js=binary/decoder.js', - '--js=binary/encoder.js', - '--js=binary/reader.js', - '--js=binary/utils.js', - '--js=binary/writer.js', - `--js=${exportsFile}`, - `--entry_point=${exportsFile}`, - `> ${outputFile}` + `--js=${closureLib}/third_party/closure/goog/**.js`, '--js=map.js', + '--js=message.js', '--js=binary/arith.js', '--js=binary/constants.js', + '--js=binary/decoder.js', '--js=binary/encoder.js', '--js=binary/reader.js', + '--js=binary/utils.js', '--js=binary/writer.js', `--js=${exportsFile}`, + `--entry_point=${exportsFile}`, `> ${outputFile}` ].join(' '); } gulp.task('dist', gulp.series(['genproto_wellknowntypes'], function(cb) { // TODO(haberman): minify this more aggressively. // Will require proper externs/exports. - exec(getClosureCompilerCommand('commonjs/export.js', 'google-protobuf.js'), - function (err, stdout, stderr) { - console.log(stdout); - console.log(stderr); - cb(err); - }); + exec( + getClosureCompilerCommand('commonjs/export.js', 'google-protobuf.js'), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); })); -gulp.task('commonjs_asserts', function (cb) { - exec('mkdir -p commonjs_out/test_node_modules && ' + - getClosureCompilerCommand( - 'commonjs/export_asserts.js', - 'commonjs_out/test_node_modules/closure_asserts_commonjs.js'), - function (err, stdout, stderr) { - console.log(stdout); - console.log(stderr); - cb(err); - }); +gulp.task('commonjs_asserts', function(cb) { + exec( + 'mkdir -p commonjs_out/test_node_modules && ' + + getClosureCompilerCommand( + 'commonjs/export_asserts.js', + 'commonjs_out/test_node_modules/closure_asserts_commonjs.js'), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); }); -gulp.task('commonjs_testdeps', function (cb) { - exec('mkdir -p commonjs_out/test_node_modules && ' + - getClosureCompilerCommand( - 'commonjs/export_testdeps.js', - 'commonjs_out/test_node_modules/testdeps_commonjs.js'), - function (err, stdout, stderr) { - console.log(stdout); - console.log(stderr); - cb(err); - }); +gulp.task('commonjs_testdeps', function(cb) { + exec( + 'mkdir -p commonjs_out/test_node_modules && ' + + getClosureCompilerCommand( + 'commonjs/export_testdeps.js', + 'commonjs_out/test_node_modules/testdeps_commonjs.js'), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); }); gulp.task( diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py index 672a9b424d934..0f2727e9caaa3 100755 --- a/python/google/protobuf/internal/json_format_test.py +++ b/python/google/protobuf/internal/json_format_test.py @@ -1124,24 +1124,24 @@ def testTimestampInvalidStringValue(self): text = '{"value": {"foo": 123}}' self.assertRaisesRegexp( json_format.ParseError, - r"Timestamp JSON value not a string: {u?'foo': 123}", - json_format.Parse, text, message) + r"Timestamp JSON value not a string: {u?'foo': 123}", json_format.Parse, + text, message) def testDurationInvalidStringValue(self): message = json_format_proto3_pb2.TestDuration() text = '{"value": {"foo": 123}}' self.assertRaisesRegexp( json_format.ParseError, - r"Duration JSON value not a string: {u?'foo': 123}", - json_format.Parse, text, message) + r"Duration JSON value not a string: {u?'foo': 123}", json_format.Parse, + text, message) def testFieldMaskInvalidStringValue(self): message = json_format_proto3_pb2.TestFieldMask() text = '{"value": {"foo": 123}}' self.assertRaisesRegexp( json_format.ParseError, - r"FieldMask JSON value not a string: {u?'foo': 123}", - json_format.Parse, text, message) + r"FieldMask JSON value not a string: {u?'foo': 123}", json_format.Parse, + text, message) def testInvalidAny(self): message = any_pb2.Any() diff --git a/python/google/protobuf/internal/python_protobuf.cc b/python/google/protobuf/internal/python_protobuf.cc new file mode 100644 index 0000000000000..e823bf228ca23 --- /dev/null +++ b/python/google/protobuf/internal/python_protobuf.cc @@ -0,0 +1,59 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: qrczak@google.com (Marcin Kowalczyk) + +#include + +namespace google { +namespace protobuf { +namespace python { + +static const Message* GetCProtoInsidePyProtoStub(PyObject* msg) { return NULL; } +static Message* MutableCProtoInsidePyProtoStub(PyObject* msg) { return NULL; } + +// This is initialized with a default, stub implementation. +// If python-google.protobuf.cc is loaded, the function pointer is overridden +// with a full implementation. +const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg) = + GetCProtoInsidePyProtoStub; +Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg) = + MutableCProtoInsidePyProtoStub; + +const Message* GetCProtoInsidePyProto(PyObject* msg) { + return GetCProtoInsidePyProtoPtr(msg); +} +Message* MutableCProtoInsidePyProto(PyObject* msg) { + return MutableCProtoInsidePyProtoPtr(msg); +} + +} // namespace python +} // namespace protobuf +} // namespace google diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py index 56659ac7e9721..58d734a0d195f 100644 --- a/python/google/protobuf/internal/well_known_types.py +++ b/python/google/protobuf/internal/well_known_types.py @@ -144,8 +144,7 @@ def FromJsonString(self, value): ValueError: On parsing problems. """ if not isinstance(value, six.string_types): - raise ValueError( - 'Timestamp JSON value not a string: {!r}'.format(value)) + raise ValueError('Timestamp JSON value not a string: {!r}'.format(value)) timezone_offset = value.find('Z') if timezone_offset == -1: timezone_offset = value.find('+') @@ -307,8 +306,7 @@ def FromJsonString(self, value): ValueError: On parsing problems. """ if not isinstance(value, six.string_types): - raise ValueError( - 'Duration JSON value not a string: {!r}'.format(value)) + raise ValueError('Duration JSON value not a string: {!r}'.format(value)) if len(value) < 1 or value[-1] != 's': raise ValueError( 'Duration must end with letter "s": {0}.'.format(value)) @@ -435,8 +433,7 @@ def ToJsonString(self): def FromJsonString(self, value): """Converts string to FieldMask according to proto3 JSON spec.""" if not isinstance(value, six.string_types): - raise ValueError( - 'FieldMask JSON value not a string: {!r}'.format(value)) + raise ValueError('FieldMask JSON value not a string: {!r}'.format(value)) self.Clear() if value: for path in value.split(','): diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc index 34816eee32b59..8773417053515 100644 --- a/python/google/protobuf/pyext/message.cc +++ b/python/google/protobuf/pyext/message.cc @@ -110,9 +110,10 @@ class MessageReflectionFriend { const std::vector& fields) { lhs->GetReflection()->UnsafeShallowSwapFields(lhs, rhs, fields); } - static bool IsLazyField(const Reflection* reflection, + static bool IsLazyField(const Reflection* reflection, const Message& message, const FieldDescriptor* field) { - return reflection->IsLazyField(field); + return reflection->IsLazyField(field) || + reflection->IsLazyExtension(message, field); } }; @@ -2305,7 +2306,8 @@ CMessage* InternalGetSubMessage( cmsg->parent_field_descriptor = field_descriptor; if (reflection->HasField(*self->message, field_descriptor)) { // Force triggering MutableMessage to set the lazy message 'Dirty' - if (MessageReflectionFriend::IsLazyField(reflection, field_descriptor)) { + if (MessageReflectionFriend::IsLazyField(reflection, *self->message, + field_descriptor)) { Message* sub_message = reflection->MutableMessage( self->message, field_descriptor, factory->message_factory); cmsg->read_only = false; diff --git a/python/google/protobuf/python_protobuf.h b/python/google/protobuf/python_protobuf.h new file mode 100644 index 0000000000000..8db1ffb7503b4 --- /dev/null +++ b/python/google/protobuf/python_protobuf.h @@ -0,0 +1,57 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: qrczak@google.com (Marcin Kowalczyk) +// +// This module exposes the C proto inside the given Python proto, in +// case the Python proto is implemented with a C proto. + +#ifndef GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__ +#define GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__ + +#include + +namespace google { +namespace protobuf { + +class Message; + +namespace python { + +// Return the pointer to the C proto inside the given Python proto, +// or NULL when this is not a Python proto implemented with a C proto. +const Message* GetCProtoInsidePyProto(PyObject* msg); +Message* MutableCProtoInsidePyProto(PyObject* msg); + +} // namespace python +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__ diff --git a/python/setup.py b/python/setup.py index 696bde2aedf3f..aab240a0e55ac 100755 --- a/python/setup.py +++ b/python/setup.py @@ -18,7 +18,6 @@ from distutils.command.build_py import build_py as _build_py from distutils.command.clean import clean as _clean -from distutils.command.build_ext import build_ext as _build_ext from distutils.spawn import find_executable # Find the Protocol Compiler. @@ -158,22 +157,6 @@ def find_package_modules(self, package, package_dir): if not any(fnmatch.fnmatchcase(fil, pat=pat) for pat in exclude)] -class build_ext(_build_ext): - def get_ext_filename(self, ext_name): - # since python3.5, python extensions' shared libraries use a suffix that corresponds to the value - # of sysconfig.get_config_var('EXT_SUFFIX') and contains info about the architecture the library targets. - # E.g. on x64 linux the suffix is ".cpython-XYZ-x86_64-linux-gnu.so" - # When crosscompiling python wheels, we need to be able to override this suffix - # so that the resulting file name matches the target architecture and we end up with a well-formed - # wheel. - filename = _build_ext.get_ext_filename(self, ext_name) - orig_ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") - new_ext_suffix = os.getenv("PROTOCOL_BUFFERS_OVERRIDE_EXT_SUFFIX") - if new_ext_suffix and filename.endswith(orig_ext_suffix): - filename = filename[:-len(orig_ext_suffix)] + new_ext_suffix - return filename - - class test_conformance(_build_py): target = 'test_python' def run(self): @@ -308,7 +291,6 @@ def get_option_from_sys_argv(option_str): cmdclass={ 'clean': clean, 'build_py': build_py, - 'build_ext': build_ext, 'test_conformance': test_conformance, }, install_requires=install_requires, diff --git a/src/google/protobuf/any.cc b/src/google/protobuf/any.cc index 955dd80b5beca..73c002f60409f 100644 --- a/src/google/protobuf/any.cc +++ b/src/google/protobuf/any.cc @@ -45,13 +45,11 @@ bool AnyMetadata::PackFrom(Arena* arena, const Message& message) { return PackFrom(arena, message, kTypeGoogleApisComPrefix); } -bool AnyMetadata::PackFrom(Arena* arena, - const Message& message, +bool AnyMetadata::PackFrom(Arena* arena, const Message& message, StringPiece type_url_prefix) { type_url_->Set( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString(), - GetTypeUrl(message.GetDescriptor()->full_name(), type_url_prefix), - arena); + GetTypeUrl(message.GetDescriptor()->full_name(), type_url_prefix), arena); return message.SerializeToString( value_->Mutable(ArenaStringPtr::EmptyDefault{}, arena)); } @@ -72,9 +70,9 @@ bool GetAnyFieldDescriptors(const Message& message, } *type_url_field = descriptor->FindFieldByNumber(1); *value_field = descriptor->FindFieldByNumber(2); - return (*type_url_field != NULL && + return (*type_url_field != nullptr && (*type_url_field)->type() == FieldDescriptor::TYPE_STRING && - *value_field != NULL && + *value_field != nullptr && (*value_field)->type() == FieldDescriptor::TYPE_BYTES); } diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h index 3ec8294e2e20a..e8336fa14a37c 100644 --- a/src/google/protobuf/any.h +++ b/src/google/protobuf/any.h @@ -82,11 +82,14 @@ class PROTOBUF_EXPORT AnyMetadata { // URL: "type.googleapis.com/". // Returns false if serializing the message failed. template - bool PackFrom(Arena* arena, const T& message, StringPiece type_url_prefix) { - return InternalPackFrom(arena, message, type_url_prefix, T::FullMessageName()); + bool PackFrom(Arena* arena, const T& message, + StringPiece type_url_prefix) { + return InternalPackFrom(arena, message, type_url_prefix, + T::FullMessageName()); } - bool PackFrom(Arena* arena, const Message& message, StringPiece type_url_prefix); + bool PackFrom(Arena* arena, const Message& message, + StringPiece type_url_prefix); // Unpacks the payload into the given message. Returns false if the message's // type doesn't match the type specified in the type URL (i.e., the full @@ -108,8 +111,7 @@ class PROTOBUF_EXPORT AnyMetadata { } private: - bool InternalPackFrom(Arena* arena, - const MessageLite& message, + bool InternalPackFrom(Arena* arena, const MessageLite& message, StringPiece type_url_prefix, StringPiece type_name); bool InternalUnpackTo(StringPiece type_name, diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc index a32c3e7f1a8a4..d3b1b4c226c2e 100644 --- a/src/google/protobuf/any.pb.cc +++ b/src/google/protobuf/any.pb.cc @@ -124,7 +124,7 @@ Any::Any(const Any& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Any) } -void Any::SharedCtor() { +inline void Any::SharedCtor() { type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 5c6d92e99c1ae..b1b70f5079304 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -153,7 +153,12 @@ class PROTOBUF_EXPORT Any final : } inline void Swap(Any* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/any_lite.cc b/src/google/protobuf/any_lite.cc index 1fa06c732d35e..a98559da140ca 100644 --- a/src/google/protobuf/any_lite.cc +++ b/src/google/protobuf/any_lite.cc @@ -53,8 +53,7 @@ const char kAnyFullTypeName[] = "google.protobuf.Any"; const char kTypeGoogleApisComPrefix[] = "type.googleapis.com/"; const char kTypeGoogleProdComPrefix[] = "type.googleprod.com/"; -bool AnyMetadata::InternalPackFrom(Arena* arena, - const MessageLite& message, +bool AnyMetadata::InternalPackFrom(Arena* arena, const MessageLite& message, StringPiece type_url_prefix, StringPiece type_name) { type_url_->Set(&::google::protobuf::internal::GetEmptyString(), diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc index 5cca2f161d2c0..d3fb1dd52ddf8 100644 --- a/src/google/protobuf/api.pb.cc +++ b/src/google/protobuf/api.pb.cc @@ -218,7 +218,7 @@ Api::Api(const Api& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Api) } -void Api::SharedCtor() { +inline void Api::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast(this) + static_cast( @@ -631,7 +631,7 @@ Method::Method(const Method& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Method) } -void Method::SharedCtor() { +inline void Method::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); request_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); response_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -1022,7 +1022,7 @@ Mixin::Mixin(const Mixin& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin) } -void Mixin::SharedCtor() { +inline void Mixin::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); root_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index d0e1bb7335f47..01c670b2b78b0 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -130,7 +130,12 @@ class PROTOBUF_EXPORT Api final : } inline void Swap(Api* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -385,7 +390,12 @@ class PROTOBUF_EXPORT Method final : } inline void Swap(Method* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -618,7 +628,12 @@ class PROTOBUF_EXPORT Mixin final : } inline void Swap(Mixin* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc index b6fbd1f21bea3..ba00fbdb6d293 100644 --- a/src/google/protobuf/arena_unittest.cc +++ b/src/google/protobuf/arena_unittest.cc @@ -1151,7 +1151,7 @@ TEST(ArenaTest, RepeatedFieldOnArena) { // Fill some repeated fields on the arena to test for leaks. Also verify no // memory allocations. - RepeatedField repeated_int32(&arena); + RepeatedField repeated_int32(&arena); RepeatedPtrField repeated_message(&arena); for (int i = 0; i < 100; i++) { repeated_int32.Add(42); diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h index 247736966427a..df11af668c3d5 100644 --- a/src/google/protobuf/arenastring.h +++ b/src/google/protobuf/arenastring.h @@ -142,7 +142,7 @@ static_assert(std::is_trivial>::value, // free()/destructor-call list) as appropriate. // // - Pointer set to 'DonatedString' tag (LSB is 1): points to a std::string -// instance with a buffer on the arena (arena != NULL, always, in this case). +// instance with a buffer on the arena (arena is never nullptr in this case). // // For fields with a non-empty string default value, there are three distinct // states: @@ -158,7 +158,7 @@ static_assert(std::is_trivial>::value, // free()/destructor-call list) as appropriate. // // - Pointer set to 'DonatedString' tag (LSB is 1): points to a std::string -// instance with a buffer on the arena (arena != NULL, always, in this case). +// instance with a buffer on the arena (arena is never nullptr in this case). // // Generated code and reflection code both ensure that ptr_ is never null for // fields with an empty default. @@ -240,8 +240,8 @@ struct PROTOBUF_EXPORT ArenaStringPtr { std::string* Mutable(const LazyString& default_value, ::google::protobuf::Arena* arena); // Release returns a std::string* instance that is heap-allocated and is not - // Own()'d by any arena. If the field is not set, this returns NULL. The - // caller retains ownership. Clears this field back to NULL state. Used to + // Own()'d by any arena. If the field is not set, this returns nullptr. The + // caller retains ownership. Clears this field back to nullptr state. Used to // implement release_() methods on generated classes. PROTOBUF_MUST_USE_RESULT std::string* Release( const std::string* default_value, ::google::protobuf::Arena* arena); @@ -276,9 +276,9 @@ struct PROTOBUF_EXPORT ArenaStringPtr { // string default. void ClearNonDefaultToEmpty(); - // Clears content, but keeps allocated std::string if arena != NULL, to avoid - // the overhead of heap operations. After this returns, the content (as seen - // by the user) will always be equal to |default_value|. + // Clears content, but keeps allocated std::string if arena != nullptr, to + // avoid the overhead of heap operations. After this returns, the content + // (as seen by the user) will always be equal to |default_value|. void ClearToDefault(const LazyString& default_value, ::google::protobuf::Arena* arena); // Called from generated code / reflection runtime only. Resets value to point diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index a68a60411d3a6..c56716fced43d 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc @@ -402,8 +402,8 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { // implements GeneratorContext -------------------------------------- io::ZeroCopyOutputStream* Open(const std::string& filename) override; io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename) override; - io::ZeroCopyOutputStream* OpenForInsert(const std::string& filename, - const std::string& insertion_point) override; + io::ZeroCopyOutputStream* OpenForInsert( + const std::string& filename, const std::string& insertion_point) override; io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo( const std::string& filename, const std::string& insertion_point, const google::protobuf::GeneratedCodeInfo& info) override; diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc index 937a42a4df22a..d4d6a589c6d6a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc @@ -777,8 +777,10 @@ std::string SafeFunctionName(const Descriptor* descriptor, return function_name; } -bool IsStringInlined(const FieldDescriptor* /* descriptor */, - const Options& /* options */) { +bool IsStringInlined(const FieldDescriptor* descriptor, + const Options& options) { + (void)descriptor; + (void)options; return false; } @@ -939,15 +941,19 @@ bool HasEnumDefinitions(const FileDescriptor* file) { return false; } -bool ShouldVerify(const Descriptor* /* descriptor */, - const Options& /* options */, - MessageSCCAnalyzer* /* scc_analyzer */) { +bool ShouldVerify(const Descriptor* descriptor, const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + (void)descriptor; + (void)options; + (void)scc_analyzer; return false; } -bool ShouldVerify(const FileDescriptor* /* file */, - const Options& /* options */, - MessageSCCAnalyzer* /* scc_analyzer */) { +bool ShouldVerify(const FileDescriptor* file, const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + (void)file; + (void)options; + (void)scc_analyzer; return false; } @@ -1470,7 +1476,8 @@ FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file, return FileOptions::SPEED; } -bool EnableMessageOwnedArena(const Descriptor* /* desc */) { +bool EnableMessageOwnedArena(const Descriptor* desc) { + (void)desc; return false; } diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc index c29be76c07392..d4c020b4ac207 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.cc +++ b/src/google/protobuf/compiler/cpp/cpp_message.cc @@ -1565,7 +1565,8 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { "bool PackFrom(const ::$proto_ns$::Message& message,\n" " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " "type_url_prefix) {\n" - " return _any_metadata_.PackFrom(GetArena(), message, type_url_prefix);\n" + " return _any_metadata_.PackFrom(GetArena(), message, " + "type_url_prefix);\n" "}\n" "bool UnpackTo(::$proto_ns$::Message* message) const {\n" " return _any_metadata_.UnpackTo(message);\n" @@ -1586,7 +1587,8 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { "bool PackFrom(const T& message,\n" " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " "type_url_prefix) {\n" - " return _any_metadata_.PackFrom(GetArena(), message, type_url_prefix);" + " return _any_metadata_.PackFrom(GetArena(), message, " + "type_url_prefix);" "}\n" "template " @@ -1598,13 +1600,14 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { format( "template \n" "bool PackFrom(const T& message) {\n" - " return _any_metadata_.PackFrom(message);\n" + " return _any_metadata_.PackFrom(GetArena(), message);\n" "}\n" "template \n" "bool PackFrom(const T& message,\n" " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " "type_url_prefix) {\n" - " return _any_metadata_.PackFrom(message, type_url_prefix);\n" + " return _any_metadata_.PackFrom(GetArena(), message, " + "type_url_prefix);\n" "}\n" "template \n" "bool UnpackTo(T* message) const {\n" @@ -1626,12 +1629,12 @@ void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { "}\n" "inline void Swap($classname$* other) {\n" " if (other == this) return;\n" -#ifdef PROTOBUF_FORCE_COPY_IN_SWAP + "#ifdef PROTOBUF_FORCE_COPY_IN_SWAP\n" " if (GetOwningArena() != nullptr &&\n" - " GetOwningArena() == other->GetOwningArena()) {\n" -#else // PROTOBUF_FORCE_COPY_IN_SWAP + " GetOwningArena() == other->GetOwningArena()) {\n " + "#else // PROTOBUF_FORCE_COPY_IN_SWAP\n" " if (GetOwningArena() == other->GetOwningArena()) {\n" -#endif // !PROTOBUF_FORCE_COPY_IN_SWAP + "#endif // !PROTOBUF_FORCE_COPY_IN_SWAP\n" " InternalSwap(other);\n" " } else {\n" " ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);\n" @@ -2796,7 +2799,7 @@ void MessageGenerator::GenerateSharedConstructorCode(io::Printer* printer) { if (HasSimpleBaseClass(descriptor_, options_)) return; Formatter format(printer, variables_); - format("void $classname$::SharedCtor() {\n"); + format("inline void $classname$::SharedCtor() {\n"); std::vector processed(optimized_order_.size(), false); GenerateConstructorBody(printer, processed, false); diff --git a/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc b/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc index 1a8468dacfc63..0f198e77318ee 100644 --- a/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc +++ b/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc @@ -1146,9 +1146,8 @@ std::string FieldParseFunctionName(const FieldDescriptor* field, type_format = TypeFormat::kStringValidateOnly; break; default: - GOOGLE_LOG(DFATAL) - << "Mode not handled: " - << static_cast(GetUtf8CheckMode(field, options)); + GOOGLE_LOG(DFATAL) << "Mode not handled: " + << static_cast(GetUtf8CheckMode(field, options)); return ""; } break; diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h index ce0f97d93031e..ff7c208ff2941 100644 --- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h @@ -59,7 +59,8 @@ class PrimitiveFieldGenerator : public FieldGenerator { void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override; void GenerateCopyConstructorCode(io::Printer* printer) const override; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateConstinitInitializer(io::Printer* printer) const override; @@ -98,7 +99,8 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator { void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override; void GenerateCopyConstructorCode(io::Printer* printer) const override; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateConstinitInitializer(io::Printer* printer) const override; diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h index 85689bbec8940..3f05443f58285 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h @@ -55,7 +55,8 @@ class StringFieldGenerator : public FieldGenerator { void GenerateStaticMembers(io::Printer* printer) const override; void GenerateAccessorDeclarations(io::Printer* printer) const override; void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; - void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateNonInlineAccessorDefinitions( + io::Printer* printer) const override; void GenerateClearingCode(io::Printer* printer) const override; void GenerateMessageClearingCode(io::Printer* printer) const override; void GenerateMergingCode(io::Printer* printer) const override; @@ -63,7 +64,8 @@ class StringFieldGenerator : public FieldGenerator { void GenerateConstructorCode(io::Printer* printer) const override; void GenerateCopyConstructorCode(io::Printer* printer) const override; void GenerateDestructorCode(io::Printer* printer) const override; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateConstinitInitializer(io::Printer* printer) const override; bool IsInlined() const override { return inlined_; } @@ -108,7 +110,8 @@ class RepeatedStringFieldGenerator : public FieldGenerator { void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override; void GenerateCopyConstructorCode(io::Printer* printer) const override; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateConstinitInitializer(io::Printer* printer) const override; diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc index bfdbfd102e9cf..782d2263beb5b 100644 --- a/src/google/protobuf/compiler/cpp/cpp_unittest.inc +++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc @@ -1159,10 +1159,8 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test { // implements TestService ---------------------------------------- - void Foo(RpcController* controller, - const UNITTEST::FooRequest* request, - UNITTEST::FooResponse* response, - Closure* done) override { + void Foo(RpcController* controller, const UNITTEST::FooRequest* request, + UNITTEST::FooResponse* response, Closure* done) override { ASSERT_FALSE(called_); called_ = true; method_ = "Foo"; @@ -1172,10 +1170,8 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test { done_ = done; } - void Bar(RpcController* controller, - const UNITTEST::BarRequest* request, - UNITTEST::BarResponse* response, - Closure* done) override { + void Bar(RpcController* controller, const UNITTEST::BarRequest* request, + UNITTEST::BarResponse* response, Closure* done) override { ASSERT_FALSE(called_); called_ = true; method_ = "Bar"; @@ -1214,10 +1210,8 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test { // implements TestService ---------------------------------------- - void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, + void CallMethod(const MethodDescriptor* method, RpcController* controller, + const Message* request, Message* response, Closure* done) override { ASSERT_FALSE(called_); called_ = true; @@ -1274,7 +1268,7 @@ class GENERATED_SERVICE_TEST_NAME : public testing::Test { stub_(&mock_channel_), done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {} - virtual void SetUp() override { + void SetUp() override { ASSERT_TRUE(foo_ != NULL); ASSERT_TRUE(bar_ != NULL); } @@ -1437,8 +1431,7 @@ TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) { class OneofTest : public testing::Test { protected: - virtual void SetUp() override { - } + void SetUp() override {} void ExpectEnumCasesWork(const UNITTEST::TestOneof2 &message) { switch (message.foo_case()) { diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc index d0b3f4c3200cb..3bcb0c90c2ab3 100644 --- a/src/google/protobuf/compiler/importer.cc +++ b/src/google/protobuf/compiler/importer.cc @@ -467,7 +467,7 @@ io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile( for (const auto& mapping : mappings_) { std::string temp_disk_file; if (ApplyMapping(virtual_file, mapping.virtual_path, mapping.disk_path, - &temp_disk_file)) { + &temp_disk_file)) { io::ZeroCopyInputStream* stream = OpenDiskFile(temp_disk_file); if (stream != NULL) { if (disk_file != NULL) { diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc index e68eb776e2054..a9216b7163e7c 100644 --- a/src/google/protobuf/compiler/java/java_enum_field.cc +++ b/src/google/protobuf/compiler/java/java_enum_field.cc @@ -1110,6 +1110,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" @@ -1133,6 +1134,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/java_enum_field_lite.cc index f154f95fbb992..a6037a12afe55 100644 --- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc @@ -852,6 +852,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" @@ -875,6 +876,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" diff --git a/src/google/protobuf/compiler/java/java_extension.h b/src/google/protobuf/compiler/java/java_extension.h index 164edfb2d6453..f928a783725d4 100644 --- a/src/google/protobuf/compiler/java/java_extension.h +++ b/src/google/protobuf/compiler/java/java_extension.h @@ -94,9 +94,9 @@ class ImmutableExtensionGenerator : public ExtensionGenerator { Context* context); virtual ~ImmutableExtensionGenerator(); - virtual void Generate(io::Printer* printer) override; - virtual int GenerateNonNestedInitializationCode(io::Printer* printer) override; - virtual int GenerateRegistrationCode(io::Printer* printer) override; + void Generate(io::Printer* printer) override; + int GenerateNonNestedInitializationCode(io::Printer* printer) override; + int GenerateRegistrationCode(io::Printer* printer) override; protected: const FieldDescriptor* descriptor_; diff --git a/src/google/protobuf/compiler/java/java_extension_lite.h b/src/google/protobuf/compiler/java/java_extension_lite.h index beda4f90c7a4d..76961563a9201 100644 --- a/src/google/protobuf/compiler/java/java_extension_lite.h +++ b/src/google/protobuf/compiler/java/java_extension_lite.h @@ -51,14 +51,13 @@ class ImmutableExtensionLiteGenerator : public ExtensionGenerator { Context* context); virtual ~ImmutableExtensionLiteGenerator(); - virtual void Generate(io::Printer* printer) override; + void Generate(io::Printer* printer) override; // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateNonNestedInitializationCode( - io::Printer* printer) override; + int GenerateNonNestedInitializationCode(io::Printer* printer) override; // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateRegistrationCode(io::Printer* printer) override; + int GenerateRegistrationCode(io::Printer* printer) override; private: const FieldDescriptor* descriptor_; diff --git a/src/google/protobuf/compiler/java/java_generator_factory.h b/src/google/protobuf/compiler/java/java_generator_factory.h index e64a45dd4969f..831d9dd857112 100644 --- a/src/google/protobuf/compiler/java/java_generator_factory.h +++ b/src/google/protobuf/compiler/java/java_generator_factory.h @@ -80,13 +80,13 @@ class ImmutableGeneratorFactory : public GeneratorFactory { ImmutableGeneratorFactory(Context* context); virtual ~ImmutableGeneratorFactory(); - virtual MessageGenerator* NewMessageGenerator( + MessageGenerator* NewMessageGenerator( const Descriptor* descriptor) const override; - virtual ExtensionGenerator* NewExtensionGenerator( + ExtensionGenerator* NewExtensionGenerator( const FieldDescriptor* descriptor) const override; - virtual ServiceGenerator* NewServiceGenerator( + ServiceGenerator* NewServiceGenerator( const ServiceDescriptor* descriptor) const override; private: diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/java_helpers.h index 5dc25d6c937ef..28cac6af9ae78 100644 --- a/src/google/protobuf/compiler/java/java_helpers.h +++ b/src/google/protobuf/compiler/java/java_helpers.h @@ -155,7 +155,7 @@ std::string GetOneofStoredType(const FieldDescriptor* field); // Whether we should generate multiple java files for messages. inline bool MultipleJavaFiles(const FileDescriptor* descriptor, bool immutable) { - (void) immutable; + (void)immutable; return descriptor->options().java_multiple_files(); } diff --git a/src/google/protobuf/compiler/java/java_map_field.cc b/src/google/protobuf/compiler/java/java_map_field.cc index a4ec2ffad78a0..29c7109124550 100644 --- a/src/google/protobuf/compiler/java/java_map_field.cc +++ b/src/google/protobuf/compiler/java/java_map_field.cc @@ -709,6 +709,7 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"set$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .set(key: $kt_key_type$, value: $kt_value_type$) {\n" diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.cc b/src/google/protobuf/compiler/java/java_map_field_lite.cc index 023b4fcccb063..e8ba20fcfe8c6 100644 --- a/src/google/protobuf/compiler/java/java_map_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc @@ -852,6 +852,7 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"set$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .set(key: $kt_key_type$, value: $kt_value_type$) {\n" diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc index e30e9f99cfbbd..99e2aa2e32ebc 100644 --- a/src/google/protobuf/compiler/java/java_message.cc +++ b/src/google/protobuf/compiler/java/java_message.cc @@ -1555,6 +1555,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun > set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" @@ -1565,6 +1566,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, " "com.google.protobuf.ByteString>,\n" @@ -1576,6 +1578,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" @@ -1594,6 +1597,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.ExtensionList.plusAssign" "(value: E) {\n" @@ -1613,6 +1617,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.ExtensionList.plusAssign(values: " "Iterable) {\n" @@ -1631,6 +1636,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline fun com.google.protobuf.kotlin.ExtensionList<*, " "$message$>.clear() {\n" " clear(extension)\n" diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/java_message_field.cc index a6d5dfe60b74f..137e3e203f110 100644 --- a/src/google/protobuf/compiler/java/java_message_field.cc +++ b/src/google/protobuf/compiler/java/java_message_field.cc @@ -1432,6 +1432,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" @@ -1455,6 +1456,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" diff --git a/src/google/protobuf/compiler/java/java_message_field.h b/src/google/protobuf/compiler/java/java_message_field.h index 60acb19593e65..8588100b6b969 100644 --- a/src/google/protobuf/compiler/java/java_message_field.h +++ b/src/google/protobuf/compiler/java/java_message_field.h @@ -78,7 +78,8 @@ class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator { void GenerateParsingDoneCode(io::Printer* printer) const override; void GenerateSerializationCode(io::Printer* printer) const override; void GenerateSerializedSizeCode(io::Printer* printer) const override; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const override; + void GenerateFieldBuilderInitializationCode( + io::Printer* printer) const override; void GenerateEqualsCode(io::Printer* printer) const override; void GenerateHashCode(io::Printer* printer) const override; void GenerateKotlinDslMembers(io::Printer* printer) const override; diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.cc b/src/google/protobuf/compiler/java/java_message_field_lite.cc index adb91a3616b56..d9e44c92dc4bd 100644 --- a/src/google/protobuf/compiler/java/java_message_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc @@ -822,6 +822,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" @@ -845,6 +846,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc index 8f934995046d0..7e67349a50438 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_lite.cc @@ -877,6 +877,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun > set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" @@ -887,6 +888,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, " "com.google.protobuf.ByteString>,\n" @@ -898,6 +900,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" @@ -916,6 +919,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.ExtensionList.plusAssign" "(value: E) {\n" @@ -935,6 +939,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.ExtensionList.plusAssign(values: " "Iterable) {\n" @@ -953,6 +958,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline fun com.google.protobuf.kotlin.ExtensionList<*, " "$message$>.clear() {\n" " clear(extension)\n" diff --git a/src/google/protobuf/compiler/java/java_message_lite.h b/src/google/protobuf/compiler/java/java_message_lite.h index 0af0cb8ad2e7b..adb0df7cc77a1 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.h +++ b/src/google/protobuf/compiler/java/java_message_lite.h @@ -50,12 +50,12 @@ class ImmutableMessageLiteGenerator : public MessageGenerator { ImmutableMessageLiteGenerator(const Descriptor* descriptor, Context* context); virtual ~ImmutableMessageLiteGenerator(); - virtual void Generate(io::Printer* printer) override; - virtual void GenerateInterface(io::Printer* printer) override; - virtual void GenerateExtensionRegistrationCode(io::Printer* printer) override; - virtual void GenerateStaticVariables(io::Printer* printer, - int* bytecode_estimate) override; - virtual int GenerateStaticVariableInitializers(io::Printer* printer) override; + void Generate(io::Printer* printer) override; + void GenerateInterface(io::Printer* printer) override; + void GenerateExtensionRegistrationCode(io::Printer* printer) override; + void GenerateStaticVariables(io::Printer* printer, + int* bytecode_estimate) override; + int GenerateStaticVariableInitializers(io::Printer* printer) override; void GenerateKotlinDsl(io::Printer* printer) const override; void GenerateKotlinMembers(io::Printer* printer) const override; void GenerateTopLevelKotlinMembers(io::Printer* printer) const override; diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc index dfd7188085314..8cf8c3b38adae 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field.cc +++ b/src/google/protobuf/compiler/java/java_primitive_field.cc @@ -864,6 +864,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" @@ -887,6 +888,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc index cc589f33ea382..4ff7152dfae2f 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc @@ -687,6 +687,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" @@ -710,6 +711,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" diff --git a/src/google/protobuf/compiler/java/java_service.h b/src/google/protobuf/compiler/java/java_service.h index fa9c92cf59f04..81db519481341 100644 --- a/src/google/protobuf/compiler/java/java_service.h +++ b/src/google/protobuf/compiler/java/java_service.h @@ -80,7 +80,7 @@ class ImmutableServiceGenerator : public ServiceGenerator { Context* context); virtual ~ImmutableServiceGenerator(); - virtual void Generate(io::Printer* printer) override; + void Generate(io::Printer* printer) override; private: // Generate the getDescriptorForType() method. diff --git a/src/google/protobuf/compiler/java/java_string_field.cc b/src/google/protobuf/compiler/java/java_string_field.cc index 9ebb77184e785..248e98ccb7a4d 100644 --- a/src/google/protobuf/compiler/java/java_string_field.cc +++ b/src/google/protobuf/compiler/java/java_string_field.cc @@ -81,7 +81,8 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, " throw new NullPointerException();\n" " }\n"; (*variables)["isStringEmpty"] = "com.google.protobuf.GeneratedMessage" + - GeneratedCodeVersionSuffix() + ".isStringEmpty"; + GeneratedCodeVersionSuffix() + + ".isStringEmpty"; (*variables)["writeString"] = "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() + ".writeString"; (*variables)["computeStringSize"] = "com.google.protobuf.GeneratedMessage" + @@ -119,7 +120,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, (*variables)["clear_has_field_bit_builder"] = ""; (*variables)["is_field_present_message"] = - "!" + (*variables)["isStringEmpty"] + "(" + (*variables)["name"] + "_)"; + "!" + (*variables)["isStringEmpty"] + "(" + (*variables)["name"] + "_)"; } // For repeated builders, one bit is used for whether the array is immutable. diff --git a/src/google/protobuf/compiler/java/java_string_field.h b/src/google/protobuf/compiler/java/java_string_field.h index 369dcdadfdcad..efab5fee4add5 100644 --- a/src/google/protobuf/compiler/java/java_string_field.h +++ b/src/google/protobuf/compiler/java/java_string_field.h @@ -78,7 +78,8 @@ class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { void GenerateParsingDoneCode(io::Printer* printer) const override; void GenerateSerializationCode(io::Printer* printer) const override; void GenerateSerializedSizeCode(io::Printer* printer) const override; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const override; + void GenerateFieldBuilderInitializationCode( + io::Printer* printer) const override; void GenerateEqualsCode(io::Printer* printer) const override; void GenerateHashCode(io::Printer* printer) const override; void GenerateKotlinDslMembers(io::Printer* printer) const override; diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.cc b/src/google/protobuf/compiler/java/java_string_field_lite.cc index f22fc4b5fd4ac..a0408f1866a43 100644 --- a/src/google/protobuf/compiler/java/java_string_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc @@ -781,6 +781,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "." "plusAssign(value: kotlin.String) {\n" @@ -807,6 +808,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" + "@Suppress(\"NOTHING_TO_INLINE\")\n" "inline operator fun com.google.protobuf.kotlin.DslList" "." "plusAssign(values: kotlin.collections.Iterable) {\n" diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index b8659b7c78812..afe9d4ff082f0 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -1518,6 +1518,13 @@ bool Parser::ParseOption(Message* options, AddError("Unexpected end of stream while parsing option value."); return false; + case io::Tokenizer::TYPE_WHITESPACE: + case io::Tokenizer::TYPE_NEWLINE: + GOOGLE_CHECK(!input_->report_whitespace() && !input_->report_newlines()) + << "Whitespace tokens were not requested."; + GOOGLE_LOG(FATAL) << "Tokenizer reported whitespace."; + return false; + case io::Tokenizer::TYPE_IDENTIFIER: { value_location.AddPath( UninterpretedOption::kIdentifierValueFieldNumber); diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index c942393d07e03..6973bc993dd51 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -2588,7 +2588,7 @@ class SourceInfoTest : public ParserTest { return true; } - virtual void TearDown() override { + void TearDown() override { EXPECT_TRUE(spans_.empty()) << "Forgot to call HasSpan() for:\n" << spans_.begin()->second->DebugString(); } diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc index a8e40cd08bdbf..780996866295f 100644 --- a/src/google/protobuf/compiler/plugin.cc +++ b/src/google/protobuf/compiler/plugin.cc @@ -72,21 +72,22 @@ class GeneratorResponseContext : public GeneratorContext { // implements GeneratorContext -------------------------------------- - virtual io::ZeroCopyOutputStream* Open(const std::string& filename) override { + io::ZeroCopyOutputStream* Open(const std::string& filename) override { CodeGeneratorResponse::File* file = response_->add_file(); file->set_name(filename); return new io::StringOutputStream(file->mutable_content()); } - virtual io::ZeroCopyOutputStream* OpenForInsert( - const std::string& filename, const std::string& insertion_point) override { + io::ZeroCopyOutputStream* OpenForInsert( + const std::string& filename, + const std::string& insertion_point) override { CodeGeneratorResponse::File* file = response_->add_file(); file->set_name(filename); file->set_insertion_point(insertion_point); return new io::StringOutputStream(file->mutable_content()); } - virtual io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo( + io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo( const std::string& filename, const std::string& insertion_point, const google::protobuf::GeneratedCodeInfo& info) override { CodeGeneratorResponse::File* file = response_->add_file(); diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc index d7f4aea2e6ddb..c11b3f8423fc2 100644 --- a/src/google/protobuf/compiler/plugin.pb.cc +++ b/src/google/protobuf/compiler/plugin.pb.cc @@ -258,7 +258,7 @@ Version::Version(const Version& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.Version) } -void Version::SharedCtor() { +inline void Version::SharedCtor() { suffix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&major_) - reinterpret_cast(this)), @@ -581,7 +581,7 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorRequest) } -void CodeGeneratorRequest::SharedCtor() { +inline void CodeGeneratorRequest::SharedCtor() { parameter_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); compiler_version_ = nullptr; } @@ -937,7 +937,7 @@ CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorRespon // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } -void CodeGeneratorResponse_File::SharedCtor() { +inline void CodeGeneratorResponse_File::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); insertion_point_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); content_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -1280,7 +1280,7 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse) } -void CodeGeneratorResponse::SharedCtor() { +inline void CodeGeneratorResponse::SharedCtor() { error_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); supported_features_ = uint64_t{0u}; } diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index 2e582265510b9..39c4884080955 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -173,7 +173,12 @@ class PROTOC_EXPORT Version final : } inline void Swap(Version* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -378,7 +383,12 @@ class PROTOC_EXPORT CodeGeneratorRequest final : } inline void Swap(CodeGeneratorRequest* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -604,7 +614,12 @@ class PROTOC_EXPORT CodeGeneratorResponse_File final : } inline void Swap(CodeGeneratorResponse_File* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -824,7 +839,12 @@ class PROTOC_EXPORT CodeGeneratorResponse final : } inline void Swap(CodeGeneratorResponse* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index b6c31fd2aef22..bd257d28557b3 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -993,12 +993,12 @@ class TableArena { to_relocate->PrependTo(full_blocks_); } - static constexpr std::array kSmallSizes = {{ - // Sizes for pointer arrays. - 8, 16, 24, 32, - // Sizes for string arrays (for descriptor names). - // The most common array sizes are 2 and 3. - 2 * sizeof(std::string), 3 * sizeof(std::string)}}; + static constexpr std::array kSmallSizes = { + {// Sizes for pointer arrays. + 8, 16, 24, 32, + // Sizes for string arrays (for descriptor names). + // The most common array sizes are 2 and 3. + 2 * sizeof(std::string), 3 * sizeof(std::string)}}; // Helper function to iterate all lists. std::array GetLists() const { @@ -2826,7 +2826,12 @@ bool RetrieveOptions(int depth, const Message& options, DynamicMessageFactory factory; std::unique_ptr dynamic_options( factory.GetPrototype(option_descriptor)->New()); - if (dynamic_options->ParseFromString(options.SerializeAsString())) { + std::string serialized = options.SerializeAsString(); + io::CodedInputStream input( + reinterpret_cast(serialized.c_str()), + serialized.size()); + input.SetExtensionRegistry(pool, &factory); + if (dynamic_options->ParseFromCodedStream(&input)) { return RetrieveOptionsAssumingRightPool(depth, *dynamic_options, option_entries); } else { @@ -5942,11 +5947,23 @@ void DescriptorBuilder::CrossLinkMessage(Descriptor* message, } // Must go through oneof_decls_ array to get a non-const version of the // OneofDescriptor. - ++message->oneof_decls_[oneof_decl->index()].field_count_; + auto& out_oneof_decl = message->oneof_decls_[oneof_decl->index()]; + if (out_oneof_decl.field_count_ == 0) { + out_oneof_decl.fields_ = message->field(i); + } + + if (!had_errors_) { + // Verify that they are contiguous. + // This is assumed by OneofDescriptor::field(i). + // But only if there are no errors. + GOOGLE_CHECK_EQ(out_oneof_decl.fields_ + out_oneof_decl.field_count_, + message->field(i)); + } + ++out_oneof_decl.field_count_; } } - // Then allocate the arrays. + // Then verify the sizes. for (int i = 0; i < message->oneof_decl_count(); i++) { OneofDescriptor* oneof_decl = &message->oneof_decls_[i]; @@ -5956,27 +5973,11 @@ void DescriptorBuilder::CrossLinkMessage(Descriptor* message, "Oneof must have at least one field."); } - oneof_decl->fields_ = tables_->AllocateArray( - oneof_decl->field_count_); - oneof_decl->field_count_ = 0; - if (oneof_decl->options_ == nullptr) { oneof_decl->options_ = &OneofOptions::default_instance(); } } - // Then fill them in. - for (int i = 0; i < message->field_count(); i++) { - const OneofDescriptor* oneof_decl = message->field(i)->containing_oneof(); - if (oneof_decl != nullptr) { - OneofDescriptor* mutable_oneof_decl = - &message->oneof_decls_[oneof_decl->index()]; - message->fields_[i].index_in_oneof_ = mutable_oneof_decl->field_count_; - mutable_oneof_decl->fields_[mutable_oneof_decl->field_count_++] = - message->field(i); - } - } - for (int i = 0; i < message->field_count(); i++) { const FieldDescriptor* field = message->field(i); if (field->proto3_optional_) { @@ -6529,7 +6530,7 @@ void DescriptorBuilder::ValidateMessageOptions(Descriptor* message, const int64_t max_extension_range = static_cast(message->options().message_set_wire_format() - ? kint32max + ? std::numeric_limits::max() : FieldDescriptor::kMaxNumber); for (int i = 0; i < message->extension_range_count(); ++i) { if (message->extension_range(i)->end > max_extension_range + 1) { @@ -7319,7 +7320,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( case FieldDescriptor::CPPTYPE_INT32: if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > - static_cast(kint32max)) { + static_cast(std::numeric_limits::max())) { return AddValueError("Value out of range for int32 option \"" + option_field->full_name() + "\"."); } else { @@ -7329,7 +7330,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( } } else if (uninterpreted_option_->has_negative_int_value()) { if (uninterpreted_option_->negative_int_value() < - static_cast(kint32min)) { + static_cast(std::numeric_limits::min())) { return AddValueError("Value out of range for int32 option \"" + option_field->full_name() + "\"."); } else { @@ -7346,7 +7347,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( case FieldDescriptor::CPPTYPE_INT64: if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > - static_cast(kint64max)) { + static_cast(std::numeric_limits::max())) { return AddValueError("Value out of range for int64 option \"" + option_field->full_name() + "\"."); } else { @@ -7366,7 +7367,8 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( case FieldDescriptor::CPPTYPE_UINT32: if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > kuint32max) { + if (uninterpreted_option_->positive_int_value() > + std::numeric_limits::max()) { return AddValueError("Value out of range for uint32 option \"" + option_field->name() + "\"."); } else { diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h index 67c3f69214d93..a23f19d38e648 100644 --- a/src/google/protobuf/descriptor.h +++ b/src/google/protobuf/descriptor.h @@ -905,19 +905,19 @@ class PROTOBUF_EXPORT FieldDescriptor : private internal::SymbolBase { // Returns true if this is a map message type. bool is_map_message_type() const; - bool has_default_value_; - bool proto3_optional_; + bool has_default_value_ : 1; + bool proto3_optional_ : 1; // Whether the user has specified the json_name field option in the .proto // file. - bool has_json_name_; - bool is_extension_; + bool has_json_name_ : 1; + bool is_extension_ : 1; + bool is_oneof_ : 1; - // Actually a `Type`, but stored as uint8_t to save space. - mutable uint8_t type_; // Actually a `Label` but stored as uint8_t to save space. - uint8_t label_; + uint8_t label_ : 2; - bool is_oneof_ : 1; + // Actually a `Type`, but stored as uint8_t to save space. + mutable uint8_t type_; // Logically: // all_names_ = [name, full_name, lower, camel, json] @@ -929,14 +929,15 @@ class PROTOBUF_EXPORT FieldDescriptor : private internal::SymbolBase { uint8_t lowercase_name_index_ : 2; uint8_t camelcase_name_index_ : 2; uint8_t json_name_index_ : 3; + // Sadly, `number_` located here to reduce padding. Unrelated to all_names_ + // and its indices above. + int number_; const std::string* all_names_; const FileDescriptor* file_; internal::LazyInitData* type_once_; static void TypeOnceInit(const FieldDescriptor* to_init); void InternalTypeOnceInit() const; - int number_; - int index_in_oneof_; const Descriptor* containing_type_; union { const OneofDescriptor* containing_oneof; @@ -1048,8 +1049,8 @@ class PROTOBUF_EXPORT OneofDescriptor : private internal::SymbolBase { // all_names_ = [name, full_name] const std::string* all_names_; const Descriptor* containing_type_; - const FieldDescriptor** fields_; const OneofOptions* options_; + const FieldDescriptor* fields_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() @@ -2096,7 +2097,6 @@ PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, index_in_oneof, int) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool) @@ -2112,6 +2112,7 @@ PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string) PROTOBUF_DEFINE_NAME_ACCESSOR(OneofDescriptor) PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, containing_type, const Descriptor*) PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, field_count, int) +PROTOBUF_DEFINE_ARRAY_ACCESSOR(OneofDescriptor, field, const FieldDescriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(OneofDescriptor, OneofOptions) PROTOBUF_DEFINE_NAME_ACCESSOR(EnumDescriptor) @@ -2233,6 +2234,11 @@ inline const OneofDescriptor* FieldDescriptor::containing_oneof() const { return is_oneof_ ? scope_.containing_oneof : nullptr; } +inline int FieldDescriptor::index_in_oneof() const { + GOOGLE_DCHECK(is_oneof_); + return static_cast(this - scope_.containing_oneof->field(0)); +} + inline const Descriptor* FieldDescriptor::extension_scope() const { GOOGLE_CHECK(is_extension_); return scope_.extension_scope; @@ -2390,12 +2396,6 @@ inline FileDescriptor::Syntax FileDescriptor::syntax() const { return static_cast(syntax_); } -// Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because fields_ is actually an array -// of pointers rather than the usual array of objects. -inline const FieldDescriptor* OneofDescriptor::field(int index) const { - return fields_[index]; -} - } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc index ef674945731de..7aa60e80fd05f 100644 --- a/src/google/protobuf/descriptor.pb.cc +++ b/src/google/protobuf/descriptor.pb.cc @@ -1282,7 +1282,7 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet) } -void FileDescriptorSet::SharedCtor() { +inline void FileDescriptorSet::SharedCtor() { } FileDescriptorSet::~FileDescriptorSet() { @@ -1532,7 +1532,7 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorProto) } -void FileDescriptorProto::SharedCtor() { +inline void FileDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); syntax_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -2159,7 +2159,7 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ExtensionRange) } -void DescriptorProto_ExtensionRange::SharedCtor() { +inline void DescriptorProto_ExtensionRange::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&options_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&end_) - @@ -2430,7 +2430,7 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorPro // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ReservedRange) } -void DescriptorProto_ReservedRange::SharedCtor() { +inline void DescriptorProto_ReservedRange::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&start_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&end_) - @@ -2695,7 +2695,7 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto) } -void DescriptorProto::SharedCtor() { +inline void DescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); options_ = nullptr; } @@ -3206,7 +3206,7 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.ExtensionRangeOptions) } -void ExtensionRangeOptions::SharedCtor() { +inline void ExtensionRangeOptions::SharedCtor() { } ExtensionRangeOptions::~ExtensionRangeOptions() { @@ -3481,7 +3481,7 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldDescriptorProto) } -void FieldDescriptorProto::SharedCtor() { +inline void FieldDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); extendee_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); type_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -4073,7 +4073,7 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.OneofDescriptorProto) } -void OneofDescriptorProto::SharedCtor() { +inline void OneofDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); options_ = nullptr; } @@ -4330,7 +4330,7 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(con // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } -void EnumDescriptorProto_EnumReservedRange::SharedCtor() { +inline void EnumDescriptorProto_EnumReservedRange::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&start_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&end_) - @@ -4585,7 +4585,7 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto) } -void EnumDescriptorProto::SharedCtor() { +inline void EnumDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); options_ = nullptr; } @@ -4959,7 +4959,7 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueDescriptorProto) } -void EnumValueDescriptorProto::SharedCtor() { +inline void EnumValueDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&options_) - reinterpret_cast(this)), @@ -5263,7 +5263,7 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro // @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceDescriptorProto) } -void ServiceDescriptorProto::SharedCtor() { +inline void ServiceDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); options_ = nullptr; } @@ -5589,7 +5589,7 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.MethodDescriptorProto) } -void MethodDescriptorProto::SharedCtor() { +inline void MethodDescriptorProto::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); input_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); output_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -6096,7 +6096,7 @@ FileOptions::FileOptions(const FileOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions) } -void FileOptions::SharedCtor() { +inline void FileOptions::SharedCtor() { java_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); java_outer_classname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); go_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -7029,7 +7029,7 @@ MessageOptions::MessageOptions(const MessageOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.MessageOptions) } -void MessageOptions::SharedCtor() { +inline void MessageOptions::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&message_set_wire_format_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&map_entry_) - @@ -7375,7 +7375,7 @@ FieldOptions::FieldOptions(const FieldOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldOptions) } -void FieldOptions::SharedCtor() { +inline void FieldOptions::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&ctype_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&jstype_) - @@ -7759,7 +7759,7 @@ OneofOptions::OneofOptions(const OneofOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.OneofOptions) } -void OneofOptions::SharedCtor() { +inline void OneofOptions::SharedCtor() { } OneofOptions::~OneofOptions() { @@ -7976,7 +7976,7 @@ EnumOptions::EnumOptions(const EnumOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumOptions) } -void EnumOptions::SharedCtor() { +inline void EnumOptions::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&allow_alias_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&deprecated_) - @@ -8259,7 +8259,7 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueOptions) } -void EnumValueOptions::SharedCtor() { +inline void EnumValueOptions::SharedCtor() { deprecated_ = false; } @@ -8503,7 +8503,7 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceOptions) } -void ServiceOptions::SharedCtor() { +inline void ServiceOptions::SharedCtor() { deprecated_ = false; } @@ -8752,7 +8752,7 @@ MethodOptions::MethodOptions(const MethodOptions& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.MethodOptions) } -void MethodOptions::SharedCtor() { +inline void MethodOptions::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&deprecated_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&idempotency_level_) - @@ -9051,7 +9051,7 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp // @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption.NamePart) } -void UninterpretedOption_NamePart::SharedCtor() { +inline void UninterpretedOption_NamePart::SharedCtor() { name_part_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); is_extension_ = false; } @@ -9342,7 +9342,7 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption) } -void UninterpretedOption::SharedCtor() { +inline void UninterpretedOption::SharedCtor() { identifier_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); aggregate_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -9770,7 +9770,7 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo.Location) } -void SourceCodeInfo_Location::SharedCtor() { +inline void SourceCodeInfo_Location::SharedCtor() { leading_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); trailing_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } @@ -10138,7 +10138,7 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo) } -void SourceCodeInfo::SharedCtor() { +inline void SourceCodeInfo::SharedCtor() { } SourceCodeInfo::~SourceCodeInfo() { @@ -10342,7 +10342,7 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn // @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo.Annotation) } -void GeneratedCodeInfo_Annotation::SharedCtor() { +inline void GeneratedCodeInfo_Annotation::SharedCtor() { source_file_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&begin_) - reinterpret_cast(this)), @@ -10652,7 +10652,7 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo) } -void GeneratedCodeInfo::SharedCtor() { +inline void GeneratedCodeInfo::SharedCtor() { } GeneratedCodeInfo::~GeneratedCodeInfo() { diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 94113970575e8..65af9edb81251 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -391,7 +391,12 @@ class PROTOBUF_EXPORT FileDescriptorSet final : } inline void Swap(FileDescriptorSet* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -550,7 +555,12 @@ class PROTOBUF_EXPORT FileDescriptorProto final : } inline void Swap(FileDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -944,7 +954,12 @@ class PROTOBUF_EXPORT DescriptorProto_ExtensionRange final : } inline void Swap(DescriptorProto_ExtensionRange* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1134,7 +1149,12 @@ class PROTOBUF_EXPORT DescriptorProto_ReservedRange final : } inline void Swap(DescriptorProto_ReservedRange* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1304,7 +1324,12 @@ class PROTOBUF_EXPORT DescriptorProto final : } inline void Swap(DescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1653,7 +1678,12 @@ class PROTOBUF_EXPORT ExtensionRangeOptions final : } inline void Swap(ExtensionRangeOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -2004,7 +2034,12 @@ class PROTOBUF_EXPORT FieldDescriptorProto final : } inline void Swap(FieldDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -2433,7 +2468,12 @@ class PROTOBUF_EXPORT OneofDescriptorProto final : } inline void Swap(OneofDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -2613,7 +2653,12 @@ class PROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange final : } inline void Swap(EnumDescriptorProto_EnumReservedRange* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -2783,7 +2828,12 @@ class PROTOBUF_EXPORT EnumDescriptorProto final : } inline void Swap(EnumDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -3031,7 +3081,12 @@ class PROTOBUF_EXPORT EnumValueDescriptorProto final : } inline void Swap(EnumValueDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -3226,7 +3281,12 @@ class PROTOBUF_EXPORT ServiceDescriptorProto final : } inline void Swap(ServiceDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -3426,7 +3486,12 @@ class PROTOBUF_EXPORT MethodDescriptorProto final : } inline void Swap(MethodDescriptorProto* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -3676,7 +3741,12 @@ class PROTOBUF_EXPORT FileOptions final : } inline void Swap(FileOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -4410,7 +4480,12 @@ class PROTOBUF_EXPORT MessageOptions final : } inline void Swap(MessageOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -4822,7 +4897,12 @@ class PROTOBUF_EXPORT FieldOptions final : } inline void Swap(FieldOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -5328,7 +5408,12 @@ class PROTOBUF_EXPORT OneofOptions final : } inline void Swap(OneofOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -5679,7 +5764,12 @@ class PROTOBUF_EXPORT EnumOptions final : } inline void Swap(EnumOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -6061,7 +6151,12 @@ class PROTOBUF_EXPORT EnumValueOptions final : } inline void Swap(EnumValueOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -6428,7 +6523,12 @@ class PROTOBUF_EXPORT ServiceOptions final : } inline void Swap(ServiceOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -6795,7 +6895,12 @@ class PROTOBUF_EXPORT MethodOptions final : } inline void Swap(MethodOptions* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -7209,7 +7314,12 @@ class PROTOBUF_EXPORT UninterpretedOption_NamePart final : } inline void Swap(UninterpretedOption_NamePart* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -7387,7 +7497,12 @@ class PROTOBUF_EXPORT UninterpretedOption final : } inline void Swap(UninterpretedOption* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -7654,7 +7769,12 @@ class PROTOBUF_EXPORT SourceCodeInfo_Location final : } inline void Swap(SourceCodeInfo_Location* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -7910,7 +8030,12 @@ class PROTOBUF_EXPORT SourceCodeInfo final : } inline void Swap(SourceCodeInfo* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -8071,7 +8196,12 @@ class PROTOBUF_EXPORT GeneratedCodeInfo_Annotation final : } inline void Swap(GeneratedCodeInfo_Annotation* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -8286,7 +8416,12 @@ class PROTOBUF_EXPORT GeneratedCodeInfo final : } inline void Swap(GeneratedCodeInfo* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/descriptor_database.cc b/src/google/protobuf/descriptor_database.cc index b101dd2228380..be1afcb57c264 100644 --- a/src/google/protobuf/descriptor_database.cc +++ b/src/google/protobuf/descriptor_database.cc @@ -381,7 +381,7 @@ bool SimpleDescriptorDatabase::FindAllFileNames( bool SimpleDescriptorDatabase::MaybeCopy(const FileDescriptorProto* file, FileDescriptorProto* output) { - if (file == NULL) return false; + if (file == nullptr) return false; output->CopyFrom(*file); return true; } @@ -583,7 +583,7 @@ bool EncodedDescriptorDatabase::FindFileContainingSymbol( bool EncodedDescriptorDatabase::FindNameOfFileContainingSymbol( const std::string& symbol_name, std::string* output) { auto encoded_file = index_->FindSymbol(symbol_name); - if (encoded_file.first == NULL) return false; + if (encoded_file.first == nullptr) return false; // Optimization: The name should be the first field in the encoded message. // Try to just read it directly. @@ -871,7 +871,7 @@ bool EncodedDescriptorDatabase::FindAllFileNames( bool EncodedDescriptorDatabase::MaybeParse( std::pair encoded_file, FileDescriptorProto* output) { - if (encoded_file.first == NULL) return false; + if (encoded_file.first == nullptr) return false; return output->ParseFromArray(encoded_file.first, encoded_file.second); } @@ -893,7 +893,7 @@ DescriptorPoolDatabase::~DescriptorPoolDatabase() {} bool DescriptorPoolDatabase::FindFileByName(const std::string& filename, FileDescriptorProto* output) { const FileDescriptor* file = pool_.FindFileByName(filename); - if (file == NULL) return false; + if (file == nullptr) return false; output->Clear(); file->CopyTo(output); return true; @@ -902,7 +902,7 @@ bool DescriptorPoolDatabase::FindFileByName(const std::string& filename, bool DescriptorPoolDatabase::FindFileContainingSymbol( const std::string& symbol_name, FileDescriptorProto* output) { const FileDescriptor* file = pool_.FindFileContainingSymbol(symbol_name); - if (file == NULL) return false; + if (file == nullptr) return false; output->Clear(); file->CopyTo(output); return true; @@ -912,11 +912,11 @@ bool DescriptorPoolDatabase::FindFileContainingExtension( const std::string& containing_type, int field_number, FileDescriptorProto* output) { const Descriptor* extendee = pool_.FindMessageTypeByName(containing_type); - if (extendee == NULL) return false; + if (extendee == nullptr) return false; const FieldDescriptor* extension = pool_.FindExtensionByNumber(extendee, field_number); - if (extension == NULL) return false; + if (extension == nullptr) return false; output->Clear(); extension->file()->CopyTo(output); @@ -926,7 +926,7 @@ bool DescriptorPoolDatabase::FindFileContainingExtension( bool DescriptorPoolDatabase::FindAllExtensionNumbers( const std::string& extendee_type, std::vector* output) { const Descriptor* extendee = pool_.FindMessageTypeByName(extendee_type); - if (extendee == NULL) return false; + if (extendee == nullptr) return false; std::vector extensions; pool_.FindAllExtensions(extendee, &extensions); diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h index 5fb593efc65c2..f2d144da5ddbf 100644 --- a/src/google/protobuf/descriptor_database.h +++ b/src/google/protobuf/descriptor_database.h @@ -268,7 +268,7 @@ class PROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { DescriptorIndex index_; std::vector> files_to_delete_; - // If file is non-NULL, copy it into *output and return true, otherwise + // If file is non-nullptr, copy it into *output and return true, otherwise // return false. bool MaybeCopy(const FileDescriptorProto* file, FileDescriptorProto* output); @@ -320,8 +320,8 @@ class PROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { std::unique_ptr index_; std::vector files_to_delete_; - // If encoded_file.first is non-NULL, parse the data into *output and return - // true, otherwise return false. + // If encoded_file.first is non-nullptr, parse the data into *output and + // return true, otherwise return false. bool MaybeParse(std::pair encoded_file, FileDescriptorProto* output); diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index b98e7f714a128..634aa993f7c22 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -299,7 +299,7 @@ class MockErrorCollector : public DescriptorPool::ErrorCollector { // Test simple files. class FileDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // // in "foo.proto" @@ -614,7 +614,7 @@ TEST_F(FileDescriptorTest, DebugStringRoundTrip) { // Test simple flat messages and fields. class DescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // // in "foo.proto" @@ -1101,7 +1101,7 @@ TEST_F(DescriptorTest, FieldEnumType) { // Test simple flat messages and fields. class OneofDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // package garply; @@ -1361,7 +1361,7 @@ TEST_F(StylizedFieldNamesTest, FindByCamelcaseName) { // Test enum descriptors. class EnumDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // // in "foo.proto" @@ -1512,7 +1512,7 @@ TEST_F(EnumDescriptorTest, ValueType) { // Test service descriptors. class ServiceDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following messages and service: // // in "foo.proto" // message FooRequest {} @@ -1673,7 +1673,7 @@ TEST_F(ServiceDescriptorTest, MethodOutputType) { // Test nested types. class NestedDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // // in "foo.proto" @@ -1887,7 +1887,7 @@ TEST_F(NestedDescriptorTest, FindEnumValueByName) { // Test extensions. class ExtensionDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // enum Baz {} @@ -2210,7 +2210,7 @@ TEST(OverlappingExtensionRangeTest, ExtensionRangeBefore) { // Test reserved fields. class ReservedDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // message Foo { @@ -2288,7 +2288,7 @@ TEST_F(ReservedDescriptorTest, IsReservedName) { // Test reserved enum fields. class ReservedEnumDescriptorTest : public testing::Test { protected: - virtual void SetUp() override { + void SetUp() override { // Build descriptors for the following definitions: // // enum Foo { @@ -2814,7 +2814,7 @@ class AllowUnknownDependenciesTest DescriptorPoolMode mode() { return std::get<0>(GetParam()); } const char* syntax() { return std::get<1>(GetParam()); } - virtual void SetUp() override { + void SetUp() override { FileDescriptorProto foo_proto, bar_proto; switch (mode()) { @@ -3173,6 +3173,13 @@ TEST(CustomOptions, OptionLocations) { TEST(CustomOptions, OptionTypes) { const MessageOptions* options = nullptr; + constexpr int32_t kint32min = std::numeric_limits::min(); + constexpr int32_t kint32max = std::numeric_limits::max(); + constexpr uint32_t kuint32max = std::numeric_limits::max(); + constexpr int64_t kint64min = std::numeric_limits::min(); + constexpr int64_t kint64max = std::numeric_limits::max(); + constexpr uint64_t kuint64max = std::numeric_limits::max(); + options = &protobuf_unittest::CustomOptionMinIntegerValues::descriptor()->options(); EXPECT_EQ(false, options->GetExtension(protobuf_unittest::bool_opt)); @@ -6792,7 +6799,7 @@ class DatabaseBackedPoolTest : public testing::Test { SimpleDescriptorDatabase database_; - virtual void SetUp() override { + void SetUp() override { AddToDatabase( &database_, "name: 'foo.proto' " @@ -7289,10 +7296,9 @@ class AbortingErrorCollector : public DescriptorPool::ErrorCollector { public: AbortingErrorCollector() {} - virtual void AddError(const std::string& filename, - const std::string& element_name, const Message* message, - ErrorLocation location, - const std::string& error_message) override { + void AddError(const std::string& filename, const std::string& element_name, + const Message* message, ErrorLocation location, + const std::string& error_message) override { GOOGLE_LOG(FATAL) << "AddError() called unexpectedly: " << filename << " [" << element_name << "]: " << error_message; } @@ -7307,7 +7313,7 @@ class SingletonSourceTree : public compiler::SourceTree { SingletonSourceTree(const std::string& filename, const std::string& contents) : filename_(filename), contents_(contents) {} - virtual io::ZeroCopyInputStream* Open(const std::string& filename) override { + io::ZeroCopyInputStream* Open(const std::string& filename) override { return filename == filename_ ? new io::ArrayInputStream(contents_.data(), contents_.size()) : nullptr; diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc index 2326c68ef29fd..edf91fb24f583 100644 --- a/src/google/protobuf/duration.pb.cc +++ b/src/google/protobuf/duration.pb.cc @@ -100,7 +100,7 @@ Duration::Duration(const Duration& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Duration) } -void Duration::SharedCtor() { +inline void Duration::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&seconds_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&nanos_) - diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 943e40c19500d..bc5a31aa2d994 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -120,7 +120,12 @@ class PROTOBUF_EXPORT Duration final : } inline void Swap(Duration* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc index f6781f252f5c9..22a92d83d7d93 100644 --- a/src/google/protobuf/dynamic_message.cc +++ b/src/google/protobuf/dynamic_message.cc @@ -450,7 +450,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) { case FieldDescriptor::CPPTYPE_MESSAGE: { if (!field->is_repeated()) { - new (field_ptr) Message*(NULL); + new (field_ptr) Message*(nullptr); } else { if (IsMapFieldInApi(field)) { // We need to lock in most cases to avoid data racing. Only not lock @@ -499,7 +499,7 @@ void DynamicMessage::SharedCtor(bool lock_factory) { bool DynamicMessage::is_prototype() const { return type_info_->prototype == this || - // If type_info_->prototype is NULL, then we must be constructing + // If type_info_->prototype is nullptr, then we must be constructing // the prototype now, which means we must be the prototype. type_info_->prototype == nullptr; } @@ -546,7 +546,7 @@ DynamicMessage::~DynamicMessage() { // from reflection. const std::string* default_value = nullptr; reinterpret_cast(field_ptr)->Destroy( - default_value, NULL); + default_value, nullptr); break; } } @@ -606,14 +606,14 @@ DynamicMessage::~DynamicMessage() { type_info_->offsets[i])) ->GetPointer(); reinterpret_cast(field_ptr)->Destroy(default_value, - NULL); + nullptr); break; } } } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (!is_prototype()) { Message* message = *reinterpret_cast(field_ptr); - if (message != NULL) { + if (message != nullptr) { delete message; } } @@ -645,10 +645,10 @@ void DynamicMessage::CrossLinkPrototypes() { } } -Message* DynamicMessage::New() const { return New(NULL); } +Message* DynamicMessage::New() const { return New(nullptr); } Message* DynamicMessage::New(Arena* arena) const { - if (arena != NULL) { + if (arena != nullptr) { void* new_base = Arena::CreateArray(arena, type_info_->size); memset(new_base, 0, type_info_->size); return new (new_base) DynamicMessage(type_info_, arena); @@ -701,7 +701,7 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( } const TypeInfo** target = &prototypes_[type]; - if (*target != NULL) { + if (*target != nullptr) { // Already exists. return (*target)->prototype; } @@ -710,7 +710,7 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock( *target = type_info; type_info->type = type; - type_info->pool = (pool_ == NULL) ? type->file()->pool() : pool_; + type_info->pool = (pool_ == nullptr) ? type->file()->pool() : pool_; type_info->factory = this; // We need to construct all the structures passed to Reflection's constructor. diff --git a/src/google/protobuf/dynamic_message_unittest.cc b/src/google/protobuf/dynamic_message_unittest.cc index e22926e292128..9391c8ec83ce2 100644 --- a/src/google/protobuf/dynamic_message_unittest.cc +++ b/src/google/protobuf/dynamic_message_unittest.cc @@ -74,7 +74,7 @@ class DynamicMessageTest : public ::testing::TestWithParam { DynamicMessageTest() : factory_(&pool_) {} - virtual void SetUp() override { + void SetUp() override { // We want to make sure that DynamicMessage works (particularly with // extensions) even if we use descriptors that are *not* from compiled-in // types, so we make copies of the descriptors for unittest.proto and @@ -92,33 +92,33 @@ class DynamicMessageTest : public ::testing::TestWithParam { proto2_nofieldpresence_unittest::TestAllTypes::descriptor()->file()->CopyTo( &unittest_no_field_presence_file); - ASSERT_TRUE(pool_.BuildFile(unittest_import_public_file) != NULL); - ASSERT_TRUE(pool_.BuildFile(unittest_import_file) != NULL); - ASSERT_TRUE(pool_.BuildFile(unittest_file) != NULL); - ASSERT_TRUE(pool_.BuildFile(unittest_no_field_presence_file) != NULL); + ASSERT_TRUE(pool_.BuildFile(unittest_import_public_file) != nullptr); + ASSERT_TRUE(pool_.BuildFile(unittest_import_file) != nullptr); + ASSERT_TRUE(pool_.BuildFile(unittest_file) != nullptr); + ASSERT_TRUE(pool_.BuildFile(unittest_no_field_presence_file) != nullptr); descriptor_ = pool_.FindMessageTypeByName("protobuf_unittest.TestAllTypes"); - ASSERT_TRUE(descriptor_ != NULL); + ASSERT_TRUE(descriptor_ != nullptr); prototype_ = factory_.GetPrototype(descriptor_); extensions_descriptor_ = pool_.FindMessageTypeByName("protobuf_unittest.TestAllExtensions"); - ASSERT_TRUE(extensions_descriptor_ != NULL); + ASSERT_TRUE(extensions_descriptor_ != nullptr); extensions_prototype_ = factory_.GetPrototype(extensions_descriptor_); packed_descriptor_ = pool_.FindMessageTypeByName("protobuf_unittest.TestPackedTypes"); - ASSERT_TRUE(packed_descriptor_ != NULL); + ASSERT_TRUE(packed_descriptor_ != nullptr); packed_prototype_ = factory_.GetPrototype(packed_descriptor_); oneof_descriptor_ = pool_.FindMessageTypeByName("protobuf_unittest.TestOneof2"); - ASSERT_TRUE(oneof_descriptor_ != NULL); + ASSERT_TRUE(oneof_descriptor_ != nullptr); oneof_prototype_ = factory_.GetPrototype(oneof_descriptor_); proto3_descriptor_ = pool_.FindMessageTypeByName( "proto2_nofieldpresence_unittest.TestAllTypes"); - ASSERT_TRUE(proto3_descriptor_ != NULL); + ASSERT_TRUE(proto3_descriptor_ != nullptr); proto3_prototype_ = factory_.GetPrototype(proto3_descriptor_); } }; @@ -145,7 +145,7 @@ TEST_P(DynamicMessageTest, IndependentOffsets) { // one to a unique value then checking that they all still have those // unique values (i.e. they don't stomp each other). Arena arena; - Message* message = prototype_->New(GetParam() ? &arena : NULL); + Message* message = prototype_->New(GetParam() ? &arena : nullptr); TestUtil::ReflectionTester reflection_tester(descriptor_); reflection_tester.SetAllFieldsViaReflection(message); @@ -159,7 +159,7 @@ TEST_P(DynamicMessageTest, IndependentOffsets) { TEST_P(DynamicMessageTest, Extensions) { // Check that extensions work. Arena arena; - Message* message = extensions_prototype_->New(GetParam() ? &arena : NULL); + Message* message = extensions_prototype_->New(GetParam() ? &arena : nullptr); TestUtil::ReflectionTester reflection_tester(extensions_descriptor_); reflection_tester.SetAllFieldsViaReflection(message); @@ -173,7 +173,7 @@ TEST_P(DynamicMessageTest, Extensions) { TEST_P(DynamicMessageTest, PackedFields) { // Check that packed fields work properly. Arena arena; - Message* message = packed_prototype_->New(GetParam() ? &arena : NULL); + Message* message = packed_prototype_->New(GetParam() ? &arena : nullptr); TestUtil::ReflectionTester reflection_tester(packed_descriptor_); reflection_tester.SetPackedFieldsViaReflection(message); @@ -187,7 +187,7 @@ TEST_P(DynamicMessageTest, PackedFields) { TEST_P(DynamicMessageTest, Oneof) { // Check that oneof fields work properly. Arena arena; - Message* message = oneof_prototype_->New(GetParam() ? &arena : NULL); + Message* message = oneof_prototype_->New(GetParam() ? &arena : nullptr); // Check default values. const Descriptor* descriptor = message->GetDescriptor(); @@ -258,7 +258,7 @@ TEST_P(DynamicMessageTest, SpaceUsed) { // to test very much here. Just make sure it appears to be working. Arena arena; - Message* message = prototype_->New(GetParam() ? &arena : NULL); + Message* message = prototype_->New(GetParam() ? &arena : nullptr); TestUtil::ReflectionTester reflection_tester(descriptor_); size_t initial_space_used = message->SpaceUsedLong(); @@ -300,8 +300,8 @@ TEST_F(DynamicMessageTest, Proto3) { desc->FindFieldByName("optional_int32"); const FieldDescriptor* optional_msg = desc->FindFieldByName("optional_nested_message"); - EXPECT_TRUE(optional_int32 != NULL); - EXPECT_TRUE(optional_msg != NULL); + EXPECT_TRUE(optional_int32 != nullptr); + EXPECT_TRUE(optional_msg != nullptr); EXPECT_EQ(false, refl->HasField(*message, optional_int32)); refl->SetInt32(message, optional_int32, 42); diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index dd137e8cd7862..a813ddc16e3e8 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -120,7 +120,12 @@ class PROTOBUF_EXPORT Empty final : } inline void Swap(Empty* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc index d1d5aa5a2a15d..7a0ae5f1fb422 100644 --- a/src/google/protobuf/extension_set.cc +++ b/src/google/protobuf/extension_set.cc @@ -142,7 +142,7 @@ ExtensionFinder::~ExtensionFinder() {} bool GeneratedExtensionFinder::Find(int number, ExtensionInfo* output) { const ExtensionInfo* extension = FindRegisteredExtension(extendee_, number); - if (extension == NULL) { + if (extension == nullptr) { return false; } else { *output = *extension; @@ -204,12 +204,12 @@ ExtensionSet::ExtensionSet(Arena* arena) flat_capacity_(0), flat_size_(0), map_{flat_capacity_ == 0 - ? NULL + ? nullptr : Arena::CreateArray(arena_, flat_capacity_)} {} ExtensionSet::~ExtensionSet() { // Deletes all allocated extensions. - if (arena_ == NULL) { + if (arena_ == nullptr) { ForEach([](int /* number */, Extension& ext) { ext.Free(); }); if (PROTOBUF_PREDICT_FALSE(is_large())) { delete map_.large; @@ -242,11 +242,15 @@ void ExtensionSet::DeleteFlatMap(const ExtensionSet::KeyValue* flat, bool ExtensionSet::Has(int number) const { const Extension* ext = FindOrNull(number); - if (ext == NULL) return false; + if (ext == nullptr) return false; GOOGLE_DCHECK(!ext->is_repeated); return !ext->is_cleared; } +bool ExtensionSet::HasLazy(int number) const { + return Has(number) && FindOrNull(number)->is_lazy; +} + int ExtensionSet::NumExtensions() const { int result = 0; ForEach([&result](int /* number */, const Extension& ext) { @@ -259,12 +263,12 @@ int ExtensionSet::NumExtensions() const { int ExtensionSet::ExtensionSize(int number) const { const Extension* ext = FindOrNull(number); - return ext == NULL ? 0 : ext->GetSize(); + return ext == nullptr ? 0 : ext->GetSize(); } FieldType ExtensionSet::ExtensionType(int number) const { const Extension* ext = FindOrNull(number); - if (ext == NULL) { + if (ext == nullptr) { GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (1). "; return 0; } @@ -276,7 +280,7 @@ FieldType ExtensionSet::ExtensionType(int number) const { void ExtensionSet::ClearExtension(int number) { Extension* ext = FindOrNull(number); - if (ext == NULL) return; + if (ext == nullptr) return; ext->Clear(); } @@ -301,7 +305,7 @@ enum { REPEATED_FIELD, OPTIONAL_FIELD }; LOWERCASE ExtensionSet::Get##CAMELCASE(int number, LOWERCASE default_value) \ const { \ const Extension* extension = FindOrNull(number); \ - if (extension == NULL || extension->is_cleared) { \ + if (extension == nullptr || extension->is_cleared) { \ return default_value; \ } else { \ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, UPPERCASE); \ @@ -312,7 +316,7 @@ enum { REPEATED_FIELD, OPTIONAL_FIELD }; const LOWERCASE& ExtensionSet::GetRef##CAMELCASE( \ int number, const LOWERCASE& default_value) const { \ const Extension* extension = FindOrNull(number); \ - if (extension == NULL || extension->is_cleared) { \ + if (extension == nullptr || extension->is_cleared) { \ return default_value; \ } else { \ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, UPPERCASE); \ @@ -339,7 +343,7 @@ enum { REPEATED_FIELD, OPTIONAL_FIELD }; LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) \ const { \ const Extension* extension = FindOrNull(number); \ - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; \ GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, UPPERCASE); \ return extension->repeated_##LOWERCASE##_value->Get(index); \ } \ @@ -347,7 +351,7 @@ enum { REPEATED_FIELD, OPTIONAL_FIELD }; const LOWERCASE& ExtensionSet::GetRefRepeated##CAMELCASE(int number, \ int index) const { \ const Extension* extension = FindOrNull(number); \ - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; \ GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, UPPERCASE); \ return extension->repeated_##LOWERCASE##_value->Get(index); \ } \ @@ -355,7 +359,7 @@ enum { REPEATED_FIELD, OPTIONAL_FIELD }; void ExtensionSet::SetRepeated##CAMELCASE(int number, int index, \ LOWERCASE value) { \ Extension* extension = FindOrNull(number); \ - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; \ GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, UPPERCASE); \ extension->repeated_##LOWERCASE##_value->Set(index, value); \ } \ @@ -392,7 +396,7 @@ PRIMITIVE_ACCESSORS(BOOL, bool, Bool) const void* ExtensionSet::GetRawRepeatedField(int number, const void* default_value) const { const Extension* extension = FindOrNull(number); - if (extension == NULL) { + if (extension == nullptr) { return default_value; } // We assume that all the RepeatedField<>* pointers have the same @@ -466,7 +470,7 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, // the don't already exist; instead, just GOOGLE_CHECK-fails. void* ExtensionSet::MutableRawRepeatedField(int number) { Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Extension not found."; + GOOGLE_CHECK(extension != nullptr) << "Extension not found."; // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. return extension->repeated_int32_t_value; @@ -477,7 +481,7 @@ void* ExtensionSet::MutableRawRepeatedField(int number) { int ExtensionSet::GetEnum(int number, int default_value) const { const Extension* extension = FindOrNull(number); - if (extension == NULL || extension->is_cleared) { + if (extension == nullptr || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { @@ -556,7 +560,7 @@ void ExtensionSet::AddEnum(int number, FieldType type, bool packed, int value, const std::string& ExtensionSet::GetString( int number, const std::string& default_value) const { const Extension* extension = FindOrNull(number); - if (extension == NULL || extension->is_cleared) { + if (extension == nullptr || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { @@ -583,14 +587,14 @@ std::string* ExtensionSet::MutableString(int number, FieldType type, const std::string& ExtensionSet::GetRepeatedString(int number, int index) const { const Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, STRING); return extension->repeated_string_value->Get(index); } std::string* ExtensionSet::MutableRepeatedString(int number, int index) { Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, STRING); return extension->repeated_string_value->Mutable(index); } @@ -617,13 +621,13 @@ std::string* ExtensionSet::AddString(int number, FieldType type, const MessageLite& ExtensionSet::GetMessage( int number, const MessageLite& default_value) const { const Extension* extension = FindOrNull(number); - if (extension == NULL) { + if (extension == nullptr) { // Not present. Return the default value. return default_value; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); if (extension->is_lazy) { - return extension->lazymessage_value->GetMessage(default_value); + return extension->lazymessage_value->GetMessage(default_value, arena_); } else { return *extension->message_value; } @@ -666,7 +670,7 @@ MessageLite* ExtensionSet::MutableMessage(int number, FieldType type, void ExtensionSet::SetAllocatedMessage(int number, FieldType type, const FieldDescriptor* descriptor, MessageLite* message) { - if (message == NULL) { + if (message == nullptr) { ClearExtension(number); return; } @@ -681,9 +685,9 @@ void ExtensionSet::SetAllocatedMessage(int number, FieldType type, extension->is_lazy = false; if (message_arena == arena_) { extension->message_value = message; - } else if (message_arena == NULL) { + } else if (message_arena == nullptr) { extension->message_value = message; - arena_->Own(message); // not NULL because not equal to message_arena + arena_->Own(message); // not nullptr because not equal to message_arena } else { extension->message_value = message->New(arena_); extension->message_value->CheckTypeAndMergeFrom(*message); @@ -693,14 +697,14 @@ void ExtensionSet::SetAllocatedMessage(int number, FieldType type, if (extension->is_lazy) { extension->lazymessage_value->SetAllocatedMessage(message); } else { - if (arena_ == NULL) { + if (arena_ == nullptr) { delete extension->message_value; } if (message_arena == arena_) { extension->message_value = message; - } else if (message_arena == NULL) { + } else if (message_arena == nullptr) { extension->message_value = message; - arena_->Own(message); // not NULL because not equal to message_arena + arena_->Own(message); // not nullptr because not equal to message_arena } else { extension->message_value = message->New(arena_); extension->message_value->CheckTypeAndMergeFrom(*message); @@ -713,7 +717,7 @@ void ExtensionSet::SetAllocatedMessage(int number, FieldType type, void ExtensionSet::UnsafeArenaSetAllocatedMessage( int number, FieldType type, const FieldDescriptor* descriptor, MessageLite* message) { - if (message == NULL) { + if (message == nullptr) { ClearExtension(number); return; } @@ -729,7 +733,7 @@ void ExtensionSet::UnsafeArenaSetAllocatedMessage( if (extension->is_lazy) { extension->lazymessage_value->UnsafeArenaSetAllocatedMessage(message); } else { - if (arena_ == NULL) { + if (arena_ == nullptr) { delete extension->message_value; } extension->message_value = message; @@ -741,19 +745,19 @@ void ExtensionSet::UnsafeArenaSetAllocatedMessage( MessageLite* ExtensionSet::ReleaseMessage(int number, const MessageLite& prototype) { Extension* extension = FindOrNull(number); - if (extension == NULL) { - // Not present. Return NULL. - return NULL; + if (extension == nullptr) { + // Not present. Return nullptr. + return nullptr; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); - MessageLite* ret = NULL; + MessageLite* ret = nullptr; if (extension->is_lazy) { - ret = extension->lazymessage_value->ReleaseMessage(prototype); - if (arena_ == NULL) { + ret = extension->lazymessage_value->ReleaseMessage(prototype, arena_); + if (arena_ == nullptr) { delete extension->lazymessage_value; } } else { - if (arena_ == NULL) { + if (arena_ == nullptr) { ret = extension->message_value; } else { // ReleaseMessage() always returns a heap-allocated message, and we are @@ -770,15 +774,16 @@ MessageLite* ExtensionSet::ReleaseMessage(int number, MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( int number, const MessageLite& prototype) { Extension* extension = FindOrNull(number); - if (extension == NULL) { - // Not present. Return NULL. - return NULL; + if (extension == nullptr) { + // Not present. Return nullptr. + return nullptr; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL_FIELD, MESSAGE); - MessageLite* ret = NULL; + MessageLite* ret = nullptr; if (extension->is_lazy) { - ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(prototype); - if (arena_ == NULL) { + ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(prototype, + arena_); + if (arena_ == nullptr) { delete extension->lazymessage_value; } } else { @@ -796,14 +801,14 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( const MessageLite& ExtensionSet::GetRepeatedMessage(int number, int index) const { const Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, MESSAGE); return extension->repeated_message_value->Get(index); } MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) { Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK_TYPE(*extension, REPEATED_FIELD, MESSAGE); return extension->repeated_message_value->Mutable(index); } @@ -827,7 +832,7 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, MessageLite* result = reinterpret_cast( extension->repeated_message_value) ->AddFromCleared>(); - if (result == NULL) { + if (result == nullptr) { result = prototype.New(arena_); extension->repeated_message_value->AddAllocated(result); } @@ -843,7 +848,7 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, void ExtensionSet::RemoveLast(int number) { Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); switch (cpp_type(extension->type)) { @@ -882,7 +887,7 @@ void ExtensionSet::RemoveLast(int number) { MessageLite* ExtensionSet::ReleaseLast(int number) { Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); GOOGLE_DCHECK(cpp_type(extension->type) == WireFormatLite::CPPTYPE_MESSAGE); return extension->repeated_message_value->ReleaseLast(); @@ -898,7 +903,7 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseLast(int number) { void ExtensionSet::SwapElements(int number, int index1, int index2) { Extension* extension = FindOrNull(number); - GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); switch (cpp_type(extension->type)) { @@ -974,13 +979,14 @@ void ExtensionSet::MergeFrom(const ExtensionSet& other) { other.map_.large->end())); } } - other.ForEach([this](int number, const Extension& ext) { - this->InternalExtensionMergeFrom(number, ext); + other.ForEach([this, &other](int number, const Extension& ext) { + this->InternalExtensionMergeFrom(number, ext, other.arena_); }); } -void ExtensionSet::InternalExtensionMergeFrom( - int number, const Extension& other_extension) { +void ExtensionSet::InternalExtensionMergeFrom(int number, + const Extension& other_extension, + Arena* other_arena) { if (other_extension.is_repeated) { Extension* extension; bool is_new = @@ -1033,7 +1039,7 @@ void ExtensionSet::InternalExtensionMergeFrom( reinterpret_cast( extension->repeated_message_value) ->AddFromCleared>(); - if (target == NULL) { + if (target == nullptr) { target = other_message.New(arena_); extension->repeated_message_value->AddAllocated(target); } @@ -1096,7 +1102,7 @@ void ExtensionSet::InternalExtensionMergeFrom( } else { extension->message_value->CheckTypeAndMergeFrom( other_extension.lazymessage_value->GetMessage( - *extension->message_value)); + *extension->message_value, other_arena)); } } else { if (extension->is_lazy) { @@ -1165,18 +1171,19 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, int number) { // We do it this way to reuse the copy-across-arenas logic already // implemented in ExtensionSet's MergeFrom. ExtensionSet temp; - temp.InternalExtensionMergeFrom(number, *other_ext); + temp.InternalExtensionMergeFrom(number, *other_ext, other->GetArena()); Extension* temp_ext = temp.FindOrNull(number); + other_ext->Clear(); - other->InternalExtensionMergeFrom(number, *this_ext); + other->InternalExtensionMergeFrom(number, *this_ext, this->GetArena()); this_ext->Clear(); - InternalExtensionMergeFrom(number, *temp_ext); + InternalExtensionMergeFrom(number, *temp_ext, temp.GetArena()); } else if (this_ext == nullptr) { - InternalExtensionMergeFrom(number, *other_ext); + InternalExtensionMergeFrom(number, *other_ext, other->GetArena()); if (other->GetArena() == nullptr) other_ext->Free(); other->Erase(number); } else { - other->InternalExtensionMergeFrom(number, *this_ext); + other->InternalExtensionMergeFrom(number, *this_ext, this->GetArena()); if (GetArena() == nullptr) this_ext->Free(); Erase(number); } @@ -1888,7 +1895,7 @@ const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap( if (it != map_.large->end()) { return &it->second; } - return NULL; + return nullptr; } ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) { diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h index fdeed2e15db7a..6f1d2b65ab96e 100644 --- a/src/google/protobuf/extension_set.h +++ b/src/google/protobuf/extension_set.h @@ -70,6 +70,7 @@ class DescriptorPool; // descriptor.h class MessageLite; // message_lite.h class Message; // message.h class MessageFactory; // message.h +class Reflection; // message.h class UnknownFieldSet; // unknown_field_set.h namespace internal { class FieldSkipper; // wire_format_lite.h @@ -108,7 +109,7 @@ struct ExtensionInfo { type(type_param), is_repeated(isrepeated), is_packed(ispacked), - descriptor(NULL) {} + descriptor(nullptr) {} const MessageLite* message; int number; @@ -132,7 +133,7 @@ struct ExtensionInfo { }; // The descriptor for this extension, if one exists and is known. May be - // NULL. Must not be NULL if the descriptor for the extension does not + // nullptr. Must not be nullptr if the descriptor for the extension does not // live in the same pool as the descriptor for the containing type. const FieldDescriptor* descriptor; }; @@ -261,7 +262,7 @@ class PROTOBUF_EXPORT ExtensionSet { const MessageLite& GetMessage(int number, const Descriptor* message_type, MessageFactory* factory) const; - // |descriptor| may be NULL so long as it is known that the descriptor for + // |descriptor| may be nullptr so long as it is known that the descriptor for // the extension lives in the same pool as the descriptor for the containing // type. #define desc const FieldDescriptor* descriptor // avoid line wrapping @@ -281,7 +282,7 @@ class PROTOBUF_EXPORT ExtensionSet { MessageFactory* factory); // Adds the given message to the ExtensionSet, taking ownership of the // message object. Existing message with the same number will be deleted. - // If "message" is NULL, this is equivalent to "ClearExtension(number)". + // If "message" is nullptr, this is equivalent to "ClearExtension(number)". void SetAllocatedMessage(int number, FieldType type, const FieldDescriptor* descriptor, MessageLite* message); @@ -544,6 +545,8 @@ class PROTOBUF_EXPORT ExtensionSet { template friend class RepeatedEnumTypeTraits; + friend class google::protobuf::Reflection; + const int32_t& GetRefInt32(int number, const int32_t& default_value) const; const int64_t& GetRefInt64(int number, const int64_t& default_value) const; const uint32_t& GetRefUInt32(int number, const uint32_t& default_value) const; @@ -573,16 +576,16 @@ class PROTOBUF_EXPORT ExtensionSet { virtual ~LazyMessageExtension() {} virtual LazyMessageExtension* New(Arena* arena) const = 0; - virtual const MessageLite& GetMessage( - const MessageLite& prototype) const = 0; + virtual const MessageLite& GetMessage(const MessageLite& prototype, + Arena* arena) const = 0; virtual MessageLite* MutableMessage(const MessageLite& prototype, Arena* arena) = 0; virtual void SetAllocatedMessage(MessageLite* message) = 0; virtual void UnsafeArenaSetAllocatedMessage(MessageLite* message) = 0; virtual PROTOBUF_MUST_USE_RESULT MessageLite* ReleaseMessage( - const MessageLite& prototype) = 0; - virtual MessageLite* UnsafeArenaReleaseMessage( - const MessageLite& prototype) = 0; + const MessageLite& prototype, Arena* arena) = 0; + virtual MessageLite* UnsafeArenaReleaseMessage(const MessageLite& prototype, + Arena* arena) = 0; virtual bool IsInitialized() const = 0; @@ -664,8 +667,8 @@ class PROTOBUF_EXPORT ExtensionSet { mutable int cached_size; // The descriptor for this extension, if one exists and is known. May be - // NULL. Must not be NULL if the descriptor for the extension does not - // live in the same pool as the descriptor for the containing type. + // nullptr. Must not be nullptr if the descriptor for the extension does + // not live in the same pool as the descriptor for the containing type. const FieldDescriptor* descriptor; // Some helper methods for operations on a single Extension. @@ -766,7 +769,8 @@ class PROTOBUF_EXPORT ExtensionSet { } // Merges existing Extension from other_extension - void InternalExtensionMergeFrom(int number, const Extension& other_extension); + void InternalExtensionMergeFrom(int number, const Extension& other_extension, + Arena* other_arena); // Returns true and fills field_number and extension if extension is found. // Note to support packed repeated field compatibility, it also fills whether @@ -806,6 +810,9 @@ class PROTOBUF_EXPORT ExtensionSet { ExtensionFinder* extension_finder, MessageSetFieldSkipper* field_skipper); + // Returns true if extension is present and lazy. + bool HasLazy(int number) const; + // Gets the extension with the given number, creating it if it does not // already exist. Returns true if the extension did not already exist. bool MaybeNewExtension(int number, const FieldDescriptor* descriptor, @@ -1078,7 +1085,7 @@ class PROTOBUF_EXPORT RepeatedPrimitiveDefaults { template <> \ inline void PrimitiveTypeTraits::Set(int number, FieldType field_type, \ TYPE value, ExtensionSet* set) { \ - set->Set##METHOD(number, field_type, value, NULL); \ + set->Set##METHOD(number, field_type, value, nullptr); \ } \ \ template <> \ @@ -1100,7 +1107,7 @@ class PROTOBUF_EXPORT RepeatedPrimitiveDefaults { inline void RepeatedPrimitiveTypeTraits::Add( \ int number, FieldType field_type, bool is_packed, TYPE value, \ ExtensionSet* set) { \ - set->Add##METHOD(number, field_type, is_packed, value, NULL); \ + set->Add##METHOD(number, field_type, is_packed, value, nullptr); \ } \ template <> \ inline const RepeatedField* \ @@ -1126,7 +1133,7 @@ class PROTOBUF_EXPORT RepeatedPrimitiveDefaults { RepeatedPrimitiveTypeTraits::MutableRepeated( \ int number, FieldType field_type, bool is_packed, ExtensionSet* set) { \ return reinterpret_cast*>( \ - set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); \ + set->MutableRawRepeatedField(number, field_type, is_packed, nullptr)); \ } PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32_t, Int32) @@ -1159,11 +1166,11 @@ class PROTOBUF_EXPORT StringTypeTraits { } static inline void Set(int number, FieldType field_type, const std::string& value, ExtensionSet* set) { - set->SetString(number, field_type, value, NULL); + set->SetString(number, field_type, value, nullptr); } static inline std::string* Mutable(int number, FieldType field_type, ExtensionSet* set) { - return set->MutableString(number, field_type, NULL); + return set->MutableString(number, field_type, nullptr); } template static void Register(int number, FieldType type, bool is_packed) { @@ -1201,11 +1208,11 @@ class PROTOBUF_EXPORT RepeatedStringTypeTraits { } static inline void Add(int number, FieldType field_type, bool /*is_packed*/, const std::string& value, ExtensionSet* set) { - set->AddString(number, field_type, value, NULL); + set->AddString(number, field_type, value, nullptr); } static inline std::string* Add(int number, FieldType field_type, ExtensionSet* set) { - return set->AddString(number, field_type, NULL); + return set->AddString(number, field_type, nullptr); } static inline const RepeatedPtrField& GetRepeated( int number, const ExtensionSet& set) { @@ -1216,7 +1223,7 @@ class PROTOBUF_EXPORT RepeatedStringTypeTraits { static inline RepeatedPtrField* MutableRepeated( int number, FieldType field_type, bool is_packed, ExtensionSet* set) { return reinterpret_cast*>( - set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); + set->MutableRawRepeatedField(number, field_type, is_packed, nullptr)); } static const RepeatedFieldType* GetDefaultRepeatedField(); @@ -1256,7 +1263,7 @@ class EnumTypeTraits { static inline void Set(int number, FieldType field_type, ConstType value, ExtensionSet* set) { GOOGLE_DCHECK(IsValid(value)); - set->SetEnum(number, field_type, value, NULL); + set->SetEnum(number, field_type, value, nullptr); } template static void Register(int number, FieldType type, bool is_packed) { @@ -1290,7 +1297,7 @@ class RepeatedEnumTypeTraits { static inline void Add(int number, FieldType field_type, bool is_packed, ConstType value, ExtensionSet* set) { GOOGLE_DCHECK(IsValid(value)); - set->AddEnum(number, field_type, is_packed, value, NULL); + set->AddEnum(number, field_type, is_packed, value, nullptr); } static inline const RepeatedField& GetRepeated( int number, const ExtensionSet& set) { @@ -1310,7 +1317,7 @@ class RepeatedEnumTypeTraits { bool is_packed, ExtensionSet* set) { return reinterpret_cast*>( - set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); + set->MutableRawRepeatedField(number, field_type, is_packed, nullptr)); } static const RepeatedFieldType* GetDefaultRepeatedField() { @@ -1355,16 +1362,16 @@ class MessageTypeTraits { static inline MutableType Mutable(int number, FieldType field_type, ExtensionSet* set) { return static_cast(set->MutableMessage( - number, field_type, Type::default_instance(), NULL)); + number, field_type, Type::default_instance(), nullptr)); } static inline void SetAllocated(int number, FieldType field_type, MutableType message, ExtensionSet* set) { - set->SetAllocatedMessage(number, field_type, NULL, message); + set->SetAllocatedMessage(number, field_type, nullptr, message); } static inline void UnsafeArenaSetAllocated(int number, FieldType field_type, MutableType message, ExtensionSet* set) { - set->UnsafeArenaSetAllocatedMessage(number, field_type, NULL, message); + set->UnsafeArenaSetAllocatedMessage(number, field_type, nullptr, message); } static inline PROTOBUF_MUST_USE_RESULT MutableType Release(int number, FieldType /* field_type */, ExtensionSet* set) { @@ -1416,7 +1423,7 @@ class RepeatedMessageTypeTraits { static inline MutableType Add(int number, FieldType field_type, ExtensionSet* set) { return static_cast( - set->AddMessage(number, field_type, Type::default_instance(), NULL)); + set->AddMessage(number, field_type, Type::default_instance(), nullptr)); } static inline const RepeatedPtrField& GetRepeated( int number, const ExtensionSet& set) { @@ -1433,7 +1440,7 @@ class RepeatedMessageTypeTraits { bool is_packed, ExtensionSet* set) { return reinterpret_cast*>( - set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); + set->MutableRawRepeatedField(number, field_type, is_packed, nullptr)); } static const RepeatedFieldType* GetDefaultRepeatedField(); diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc index feb6dfbf91115..91187af276117 100644 --- a/src/google/protobuf/extension_set_heavy.cc +++ b/src/google/protobuf/extension_set_heavy.cc @@ -157,7 +157,7 @@ const MessageLite& ExtensionSet::GetMessage(int number, GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); if (extension->is_lazy) { return extension->lazymessage_value->GetMessage( - *factory->GetPrototype(message_type)); + *factory->GetPrototype(message_type), arena_); } else { return *extension->message_value; } @@ -194,14 +194,14 @@ MessageLite* ExtensionSet::ReleaseMessage(const FieldDescriptor* descriptor, MessageFactory* factory) { Extension* extension = FindOrNull(descriptor->number()); if (extension == nullptr) { - // Not present. Return NULL. + // Not present. Return nullptr. return nullptr; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = nullptr; if (extension->is_lazy) { ret = extension->lazymessage_value->ReleaseMessage( - *factory->GetPrototype(descriptor->message_type())); + *factory->GetPrototype(descriptor->message_type()), arena_); if (arena_ == nullptr) { delete extension->lazymessage_value; } @@ -222,14 +222,14 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( const FieldDescriptor* descriptor, MessageFactory* factory) { Extension* extension = FindOrNull(descriptor->number()); if (extension == nullptr) { - // Not present. Return NULL. + // Not present. Return nullptr. return nullptr; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = nullptr; if (extension->is_lazy) { ret = extension->lazymessage_value->UnsafeArenaReleaseMessage( - *factory->GetPrototype(descriptor->message_type())); + *factory->GetPrototype(descriptor->message_type()), arena_); if (arena_ == nullptr) { delete extension->lazymessage_value; } @@ -313,7 +313,7 @@ bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) { output->message_info.prototype = factory_->GetPrototype(extension->message_type()); GOOGLE_CHECK(output->message_info.prototype != nullptr) - << "Extension factory's GetPrototype() returned NULL for extension: " + << "Extension factory's GetPrototype() returned nullptr; extension: " << extension->full_name(); } else if (extension->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { output->enum_validity_check.func = ValidateEnumUsingDescriptor; diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc index 870f313dddab0..debdd6670c522 100644 --- a/src/google/protobuf/extension_set_unittest.cc +++ b/src/google/protobuf/extension_set_unittest.cc @@ -170,9 +170,9 @@ TEST(ExtensionSetTest, SetAllocatedExtension) { message.SetAllocatedExtension(unittest::optional_foreign_message_extension, new unittest::ForeignMessage()); - // SetAllocatedExtension with a NULL parameter is equivalent to ClearExtenion. + // SetAllocatedExtension with nullptr is equivalent to ClearExtenion. message.SetAllocatedExtension(unittest::optional_foreign_message_extension, - NULL); + nullptr); EXPECT_FALSE( message.HasExtension(unittest::optional_foreign_message_extension)); } @@ -204,7 +204,7 @@ TEST(ExtensionSetTest, ReleaseExtension) { unittest::TestMessageSetExtension1::message_set_extension); released_extension = message.ReleaseExtension( unittest::TestMessageSetExtension1::message_set_extension); - EXPECT_TRUE(released_extension != NULL); + EXPECT_TRUE(released_extension != nullptr); delete released_extension; } @@ -457,7 +457,7 @@ TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) { message2->SetExtension(unittest::optional_int32_extension, 101); TestUtil::ExpectAllExtensionsSet(*message1); TestUtil::ExpectAllExtensionsSet(*message2); - arena2.reset(NULL); + arena2.reset(nullptr); TestUtil::ExpectAllExtensionsSet(*message1); // Test corner cases, when one is empty and other is not. Arena arena3, arena4; @@ -1205,7 +1205,7 @@ TEST(ExtensionSetTest, DynamicExtensions) { // Now build the file, using the generated pool as an underlay. DescriptorPool dynamic_pool(DescriptorPool::generated_pool()); const FileDescriptor* file = dynamic_pool.BuildFile(dynamic_proto); - ASSERT_TRUE(file != NULL); + ASSERT_TRUE(file != nullptr); DynamicMessageFactory dynamic_factory(&dynamic_pool); dynamic_factory.SetDelegateToGeneratedFactory(true); @@ -1292,7 +1292,7 @@ TEST(ExtensionSetTest, DynamicExtensions) { { const FieldDescriptor* message_extension = file->FindExtensionByName("message_extension"); - ASSERT_TRUE(message_extension != NULL); + ASSERT_TRUE(message_extension != nullptr); const Message& sub_message = message.GetReflection()->GetMessage(message, message_extension); const unittest::ForeignMessage* typed_sub_message = @@ -1301,7 +1301,7 @@ TEST(ExtensionSetTest, DynamicExtensions) { #else static_cast(&sub_message); #endif - ASSERT_TRUE(typed_sub_message != NULL); + ASSERT_TRUE(typed_sub_message != nullptr); EXPECT_EQ(456, typed_sub_message->c()); } @@ -1310,7 +1310,7 @@ TEST(ExtensionSetTest, DynamicExtensions) { { const FieldDescriptor* dynamic_message_extension = file->FindExtensionByName("dynamic_message_extension"); - ASSERT_TRUE(dynamic_message_extension != NULL); + ASSERT_TRUE(dynamic_message_extension != nullptr); const Message& parent = unittest::TestAllExtensions::default_instance(); const Message& sub_message = parent.GetReflection()->GetMessage( parent, dynamic_message_extension, &dynamic_factory); diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc index fbb4f129488db..1bc0f8b9c46d1 100644 --- a/src/google/protobuf/field_mask.pb.cc +++ b/src/google/protobuf/field_mask.pb.cc @@ -97,7 +97,7 @@ FieldMask::FieldMask(const FieldMask& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask) } -void FieldMask::SharedCtor() { +inline void FieldMask::SharedCtor() { } FieldMask::~FieldMask() { diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index 06307494ccfe2..6189ddd0daf10 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -120,7 +120,12 @@ class PROTOBUF_EXPORT FieldMask final : } inline void Swap(FieldMask* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc index 7962327c0fc23..cfae9ee806063 100644 --- a/src/google/protobuf/generated_message_reflection.cc +++ b/src/google/protobuf/generated_message_reflection.cc @@ -248,6 +248,12 @@ UnknownFieldSet* Reflection::MutableUnknownFields(Message* message) const { ->mutable_unknown_fields(); } +bool Reflection::IsLazyExtension(const Message& message, + const FieldDescriptor* field) const { + return field->is_extension() && + GetExtensionSet(message).HasLazy(field->number()); +} + bool Reflection::IsLazilyVerifiedLazyField(const FieldDescriptor* field) const { return field->options().lazy(); } @@ -2620,19 +2626,19 @@ void Reflection::ClearOneof(Message* message, } } -#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \ - template <> \ - const RepeatedField& Reflection::GetRepeatedFieldInternal( \ - const Message& message, const FieldDescriptor* field) const { \ - return *static_cast*>(MutableRawRepeatedField( \ - const_cast(&message), field, CPPTYPE, CTYPE, NULL)); \ - } \ - \ - template <> \ - RepeatedField* Reflection::MutableRepeatedFieldInternal( \ - Message * message, const FieldDescriptor* field) const { \ - return static_cast*>( \ - MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \ +#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \ + template <> \ + const RepeatedField& Reflection::GetRepeatedFieldInternal( \ + const Message& message, const FieldDescriptor* field) const { \ + return *static_cast*>(MutableRawRepeatedField( \ + const_cast(&message), field, CPPTYPE, CTYPE, nullptr)); \ + } \ + \ + template <> \ + RepeatedField* Reflection::MutableRepeatedFieldInternal( \ + Message * message, const FieldDescriptor* field) const { \ + return static_cast*>( \ + MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, nullptr)); \ } HANDLE_TYPE(int32_t, FieldDescriptor::CPPTYPE_INT32, -1); @@ -2651,7 +2657,7 @@ void* Reflection::MutableRawRepeatedString(Message* message, bool is_string) const { return MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_STRING, - FieldOptions::STRING, NULL); + FieldOptions::STRING, nullptr); } // Template implementations of basic accessors. Inline because each diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc index a0c4ea521303a..8607d09d1362a 100644 --- a/src/google/protobuf/generated_message_reflection_unittest.cc +++ b/src/google/protobuf/generated_message_reflection_unittest.cc @@ -52,6 +52,8 @@ #include #include #include +#include +#include #include #include #include @@ -70,6 +72,9 @@ class GeneratedMessageReflectionTestHelper { const std::vector& fields) { lhs->GetReflection()->UnsafeShallowSwapFields(lhs, rhs, fields); } + static bool IsLazyExtension(const Message& msg, const FieldDescriptor* ext) { + return msg.GetReflection()->IsLazyExtension(msg, ext); + } }; namespace { @@ -78,7 +83,7 @@ namespace { const FieldDescriptor* F(const std::string& name) { const FieldDescriptor* result = unittest::TestAllTypes::descriptor()->FindFieldByName(name); - GOOGLE_CHECK(result != NULL); + GOOGLE_CHECK(result != nullptr); return result; } @@ -705,13 +710,14 @@ TEST(GeneratedMessageReflectionTest, FindExtensionTypeByNumber) { reflection->FindKnownExtensionByNumber(extension2->number())); // Non-existent extension. - EXPECT_TRUE(reflection->FindKnownExtensionByNumber(62341) == NULL); + EXPECT_TRUE(reflection->FindKnownExtensionByNumber(62341) == nullptr); // Extensions of TestAllExtensions should not show up as extensions of // other types. EXPECT_TRUE(unittest::TestAllTypes::default_instance() .GetReflection() - ->FindKnownExtensionByNumber(extension1->number()) == NULL); + ->FindKnownExtensionByNumber(extension1->number()) == + nullptr); } TEST(GeneratedMessageReflectionTest, FindKnownExtensionByName) { @@ -731,13 +737,14 @@ TEST(GeneratedMessageReflectionTest, FindKnownExtensionByName) { reflection->FindKnownExtensionByName(extension2->full_name())); // Non-existent extension. - EXPECT_TRUE(reflection->FindKnownExtensionByName("no_such_ext") == NULL); + EXPECT_TRUE(reflection->FindKnownExtensionByName("no_such_ext") == nullptr); // Extensions of TestAllExtensions should not show up as extensions of // other types. EXPECT_TRUE(unittest::TestAllTypes::default_instance() .GetReflection() - ->FindKnownExtensionByName(extension1->full_name()) == NULL); + ->FindKnownExtensionByName(extension1->full_name()) == + nullptr); } @@ -750,11 +757,11 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) { reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); - // Before moving fields, we expect the nested messages to be NULL. + // Before moving fields, we expect the nested messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( &to_message, TestUtil::ReflectionTester::IS_NULL); - // After fields are moved we should get non-NULL releases. + // After fields are moved we should get non-nullptr releases. reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection( &from_message1, &to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -767,7 +774,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) { &to_message, TestUtil::ReflectionTester::NOT_NULL); // After SetAllocatedOptionalMessageFieldsToNullViaReflection() we expect the - // releases to be NULL again. + // releases to be nullptr again. reflection_tester.SetAllocatedOptionalMessageFieldsToNullViaReflection( &to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -785,11 +792,11 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageOnArenaTest) { reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); - // Before moving fields, we expect the nested messages to be NULL. + // Before moving fields, we expect the nested messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( to_message, TestUtil::ReflectionTester::IS_NULL); - // After fields are moved we should get non-NULL releases. + // After fields are moved we should get non-nullptr releases. reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection( &from_message1, to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -802,7 +809,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageOnArenaTest) { to_message, TestUtil::ReflectionTester::NOT_NULL); // After SetAllocatedOptionalMessageFieldsToNullViaReflection() we expect the - // releases to be NULL again. + // releases to be nullptr again. reflection_tester.SetAllocatedOptionalMessageFieldsToNullViaReflection( to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -818,11 +825,11 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) { reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); - // Before moving fields, we expect the nested messages to be NULL. + // Before moving fields, we expect the nested messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( &to_message, TestUtil::ReflectionTester::IS_NULL); - // After fields are moved we should get non-NULL releases. + // After fields are moved we should get non-nullptr releases. reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection( &from_message1, &to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -835,7 +842,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) { &to_message, TestUtil::ReflectionTester::NOT_NULL); // After SetAllocatedOptionalMessageFieldsToNullViaReflection() we expect the - // releases to be NULL again. + // releases to be nullptr again. reflection_tester.SetAllocatedOptionalMessageFieldsToNullViaReflection( &to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -853,11 +860,11 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageOnArenaTest) { reflection_tester.SetAllFieldsViaReflection(&from_message1); reflection_tester.SetAllFieldsViaReflection(&from_message2); - // Before moving fields, we expect the nested messages to be NULL. + // Before moving fields, we expect the nested messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( to_message, TestUtil::ReflectionTester::IS_NULL); - // After fields are moved we should get non-NULL releases. + // After fields are moved we should get non-nullptr releases. reflection_tester.SetAllocatedOptionalMessageFieldsToMessageViaReflection( &from_message1, to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -870,7 +877,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageOnArenaTest) { to_message, TestUtil::ReflectionTester::NOT_NULL); // After SetAllocatedOptionalMessageFieldsToNullViaReflection() we expect the - // releases to be NULL again. + // releases to be nullptr again. reflection_tester.SetAllocatedOptionalMessageFieldsToNullViaReflection( to_message); reflection_tester.ExpectMessagesReleasedViaReflection( @@ -1022,10 +1029,10 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { Message* released = reflection->ReleaseMessage( &to_message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released == NULL); + EXPECT_TRUE(released == nullptr); released = reflection->ReleaseMessage( &to_message, descriptor->FindFieldByName("foo_message")); - EXPECT_TRUE(released == NULL); + EXPECT_TRUE(released == nullptr); TestUtil::ReflectionTester::SetOneofViaReflection(&from_message1); TestUtil::ReflectionTester::ExpectOneofSetViaReflection(from_message1); @@ -1038,7 +1045,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { (void)sub_message; // unused in somce configurations released = reflection->ReleaseMessage( &to_message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released != NULL); + EXPECT_TRUE(released != nullptr); EXPECT_EQ(&sub_message, released); delete released; @@ -1056,7 +1063,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { (void)sub_message2; // unused in somce configurations released = reflection->ReleaseMessage( &to_message, descriptor->FindFieldByName("foo_message")); - EXPECT_TRUE(released != NULL); + EXPECT_TRUE(released != nullptr); EXPECT_EQ(&sub_message2, released); delete released; } @@ -1072,10 +1079,10 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { Message* released = reflection->ReleaseMessage( to_message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released == NULL); + EXPECT_TRUE(released == nullptr); released = reflection->ReleaseMessage( to_message, descriptor->FindFieldByName("foo_message")); - EXPECT_TRUE(released == NULL); + EXPECT_TRUE(released == nullptr); TestUtil::ReflectionTester::SetOneofViaReflection(&from_message1); TestUtil::ReflectionTester::ExpectOneofSetViaReflection(from_message1); @@ -1087,7 +1094,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { *to_message, descriptor->FindFieldByName("foo_lazy_message")); released = reflection->ReleaseMessage( to_message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released != NULL); + EXPECT_TRUE(released != nullptr); // Since sub_message is arena allocated, releasing it results in copying it // into new heap-allocated memory. EXPECT_NE(&sub_message, released); @@ -1106,7 +1113,7 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) { *to_message, descriptor->FindFieldByName("foo_message")); released = reflection->ReleaseMessage( to_message, descriptor->FindFieldByName("foo_message")); - EXPECT_TRUE(released != NULL); + EXPECT_TRUE(released != nullptr); // Since sub_message2 is arena allocated, releasing it results in copying it // into new heap-allocated memory. EXPECT_NE(&sub_message2, released); @@ -1118,11 +1125,11 @@ TEST(GeneratedMessageReflectionTest, ReleaseMessageTest) { TestUtil::ReflectionTester reflection_tester( unittest::TestAllTypes::descriptor()); - // When nothing is set, we expect all released messages to be NULL. + // When nothing is set, we expect all released messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( &message, TestUtil::ReflectionTester::IS_NULL); - // After fields are set we should get non-NULL releases. + // After fields are set we should get non-nullptr releases. reflection_tester.SetAllFieldsViaReflection(&message); reflection_tester.ExpectMessagesReleasedViaReflection( &message, TestUtil::ReflectionTester::NOT_NULL); @@ -1144,11 +1151,11 @@ TEST(GeneratedMessageReflectionTest, ReleaseExtensionMessageTest) { TestUtil::ReflectionTester reflection_tester( unittest::TestAllExtensions::descriptor()); - // When nothing is set, we expect all released messages to be NULL. + // When nothing is set, we expect all released messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( &message, TestUtil::ReflectionTester::IS_NULL); - // After fields are set we should get non-NULL releases. + // After fields are set we should get non-nullptr releases. reflection_tester.SetAllFieldsViaReflection(&message); reflection_tester.ExpectMessagesReleasedViaReflection( &message, TestUtil::ReflectionTester::NOT_NULL); @@ -1177,13 +1184,13 @@ TEST(GeneratedMessageReflectionTest, ReleaseOneofMessageTest) { Message* released = reflection->ReleaseMessage( &message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released != NULL); + EXPECT_TRUE(released != nullptr); EXPECT_EQ(&sub_message, released); delete released; released = reflection->ReleaseMessage( &message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released == NULL); + EXPECT_TRUE(released == nullptr); } TEST(GeneratedMessageReflectionTest, ArenaReleaseMessageTest) { @@ -1193,11 +1200,11 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseMessageTest) { TestUtil::ReflectionTester reflection_tester( unittest::TestAllTypes::descriptor()); - // When nothing is set, we expect all released messages to be NULL. + // When nothing is set, we expect all released messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( message, TestUtil::ReflectionTester::IS_NULL); - // After fields are set we should get non-NULL releases. + // After fields are set we should get non-nullptr releases. reflection_tester.SetAllFieldsViaReflection(message); reflection_tester.ExpectMessagesReleasedViaReflection( message, TestUtil::ReflectionTester::NOT_NULL); @@ -1217,11 +1224,11 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseExtensionMessageTest) { TestUtil::ReflectionTester reflection_tester( unittest::TestAllExtensions::descriptor()); - // When nothing is set, we expect all released messages to be NULL. + // When nothing is set, we expect all released messages to be nullptr. reflection_tester.ExpectMessagesReleasedViaReflection( message, TestUtil::ReflectionTester::IS_NULL); - // After fields are set we should get non-NULL releases. + // After fields are set we should get non-nullptr releases. reflection_tester.SetAllFieldsViaReflection(message); reflection_tester.ExpectMessagesReleasedViaReflection( message, TestUtil::ReflectionTester::NOT_NULL); @@ -1245,12 +1252,12 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseOneofMessageTest) { Message* released = reflection->ReleaseMessage( message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released != NULL); + EXPECT_TRUE(released != nullptr); delete released; released = reflection->ReleaseMessage( message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_TRUE(released == NULL); + EXPECT_TRUE(released == nullptr); } #ifdef PROTOBUF_HAS_DEATH_TEST diff --git a/src/google/protobuf/generated_message_table_driven.cc b/src/google/protobuf/generated_message_table_driven.cc index 71ee647565a2e..f963d906f0df5 100644 --- a/src/google/protobuf/generated_message_table_driven.cc +++ b/src/google/protobuf/generated_message_table_driven.cc @@ -74,14 +74,14 @@ struct UnknownFieldHandler { static bool ParseExtension(MessageLite* msg, const ParseTable& table, io::CodedInputStream* input, int tag) { ExtensionSet* extensions = GetExtensionSet(msg, table.extension_offset); - if (extensions == NULL) { + if (extensions == nullptr) { return false; } const Message* prototype = down_cast(table.default_instance()); - GOOGLE_DCHECK(prototype != NULL); + GOOGLE_DCHECK(prototype != nullptr); GOOGLE_DCHECK(table.unknown_field_set); UnknownFieldSet* unknown_fields = MutableUnknownFields(msg, table.arena_offset); diff --git a/src/google/protobuf/generated_message_table_driven.h b/src/google/protobuf/generated_message_table_driven.h index 178a0c1c6ae14..15eebcbf871c7 100644 --- a/src/google/protobuf/generated_message_table_driven.h +++ b/src/google/protobuf/generated_message_table_driven.h @@ -267,9 +267,10 @@ inline void TableSerialize(const MessageLite& msg, } PROTOBUF_EXPORT uint8_t* SerializeInternalToArray(const uint8_t* base, - const FieldMetadata* table, - int32_t num_fields, bool is_deterministic, - uint8_t* buffer); + const FieldMetadata* table, + int32_t num_fields, + bool is_deterministic, + uint8_t* buffer); inline uint8_t* TableSerializeToArray(const MessageLite& msg, const SerializationTable* table, diff --git a/src/google/protobuf/generated_message_table_driven_lite.cc b/src/google/protobuf/generated_message_table_driven_lite.cc index 42c3475f3863b..596f356738852 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.cc +++ b/src/google/protobuf/generated_message_table_driven_lite.cc @@ -78,7 +78,7 @@ struct UnknownFieldHandlerLite { static bool ParseExtension(MessageLite* msg, const ParseTable& table, io::CodedInputStream* input, int tag) { ExtensionSet* extensions = GetExtensionSet(msg, table.extension_offset); - if (extensions == NULL) { + if (extensions == nullptr) { return false; } diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h index 032dd0e50e117..780753b40be51 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.h +++ b/src/google/protobuf/generated_message_table_driven_lite.h @@ -83,7 +83,7 @@ inline const Type* Raw(const MessageLite* msg, int64_t offset) { inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64_t extension_offset) { if (extension_offset == -1) { - return NULL; + return nullptr; } return Raw(msg, extension_offset); @@ -148,7 +148,7 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena, MessageLite* msg) { switch (field.processing_type & kTypeMask) { case WireFormatLite::TYPE_MESSAGE: - if (arena == NULL) { + if (arena == nullptr) { delete *Raw(msg, field.offset); } break; @@ -161,7 +161,7 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena, case TYPE_STRING_INLINED: case TYPE_BYTES_INLINED: - Raw(msg, field.offset)->DestroyNoArena(NULL); + Raw(msg, field.offset)->DestroyNoArena(nullptr); break; default: @@ -347,11 +347,11 @@ class RepeatedMessageTypeHandler { return t->GetMaybeArenaPointer(); } static inline Type* NewFromPrototype(const Type* prototype, - Arena* arena = NULL) { + Arena* arena = nullptr) { return prototype->New(arena); } - static void Delete(Type* t, Arena* arena = NULL) { - if (arena == NULL) { + static void Delete(Type* t, Arena* arena = nullptr) { + if (arena == nullptr) { delete t; } } @@ -376,7 +376,7 @@ bool MergePartialFromCodedStreamInlined(MessageLite* msg, // TODO(ckennelly): Make this a compile-time parameter with templates. GOOGLE_DCHECK_GE(table.has_bits_offset, 0); uint32_t* has_bits = Raw(msg, table.has_bits_offset); - GOOGLE_DCHECK(has_bits != NULL); + GOOGLE_DCHECK(has_bits != nullptr); while (true) { uint32_t tag = input->ReadTagWithCutoffNoLastTag(kMaxTag).first; @@ -623,7 +623,7 @@ bool MergePartialFromCodedStreamInlined(MessageLite* msg, MutableField(msg, has_bits, presence_index, offset); MessageLite* submsg = *submsg_holder; - if (submsg == NULL) { + if (submsg == nullptr) { Arena* const arena = msg->GetArena(); const MessageLite* prototype = table.aux[field_number].messages.default_message(); @@ -642,7 +642,7 @@ bool MergePartialFromCodedStreamInlined(MessageLite* msg, RepeatedPtrFieldBase* field = Raw(msg, offset); const MessageLite* prototype = table.aux[field_number].messages.default_message(); - GOOGLE_DCHECK(prototype != NULL); + GOOGLE_DCHECK(prototype != nullptr); MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); @@ -659,11 +659,11 @@ bool MergePartialFromCodedStreamInlined(MessageLite* msg, MutableField(msg, has_bits, presence_index, offset); MessageLite* submsg = *submsg_holder; - if (submsg == NULL) { + if (submsg == nullptr) { Arena* const arena = msg->GetArena(); const MessageLite* prototype = table.aux[field_number].messages.default_message(); - if (prototype == NULL) { + if (prototype == nullptr) { prototype = ImplicitWeakMessage::default_instance(); } submsg = prototype->New(arena); @@ -683,7 +683,7 @@ bool MergePartialFromCodedStreamInlined(MessageLite* msg, RepeatedPtrFieldBase* field = Raw(msg, offset); const MessageLite* prototype = table.aux[field_number].messages.default_message(); - if (prototype == NULL) { + if (prototype == nullptr) { prototype = ImplicitWeakMessage::default_instance(); } @@ -703,7 +703,7 @@ bool MergePartialFromCodedStreamInlined(MessageLite* msg, MessageLite** submsg_holder = Raw(msg, offset); ResetOneofField( table, field_number, arena, msg, oneof_case + presence_index, - offset, NULL); + offset, nullptr); MessageLite* submsg = *submsg_holder; if (PROTOBUF_PREDICT_FALSE( diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc index cbe771e535d88..acda7de4b6adf 100644 --- a/src/google/protobuf/generated_message_util.cc +++ b/src/google/protobuf/generated_message_util.cc @@ -591,12 +591,12 @@ bool IsNull(const void* ptr) { template <> bool IsNull(const void* ptr) { - return Get(ptr) == NULL; + return Get(ptr) == nullptr; } template <> bool IsNull(const void* ptr) { - return Get(ptr) == NULL; + return Get(ptr) == nullptr; } @@ -739,7 +739,7 @@ MessageLite* DuplicateIfNonNullInternal(MessageLite* message) { ret->CheckTypeAndMergeFrom(*message); return ret; } else { - return NULL; + return nullptr; } } @@ -761,7 +761,7 @@ MessageLite* GetOwnedMessageInternal(Arena* message_arena, submessage_arena); GOOGLE_DCHECK(message_arena != submessage_arena); GOOGLE_DCHECK_EQ(submessage_arena, nullptr); - if (message_arena != NULL && submessage_arena == NULL) { + if (message_arena != nullptr && submessage_arena == nullptr) { message_arena->Own(submessage); return submessage; } else { diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h index 561e4725121f2..5456c5293863f 100644 --- a/src/google/protobuf/implicit_weak_message.h +++ b/src/google/protobuf/implicit_weak_message.h @@ -103,12 +103,12 @@ class ImplicitWeakTypeHandler { static constexpr bool Moveable = false; static inline MessageLite* NewFromPrototype(const MessageLite* prototype, - Arena* arena = NULL) { + Arena* arena = nullptr) { return prototype->New(arena); } static inline void Delete(MessageLite* value, Arena* arena) { - if (arena == NULL) { + if (arena == nullptr) { delete value; } } diff --git a/src/google/protobuf/inlined_string_field.h b/src/google/protobuf/inlined_string_field.h index 17373f5118adb..759ae26afeb15 100644 --- a/src/google/protobuf/inlined_string_field.h +++ b/src/google/protobuf/inlined_string_field.h @@ -199,8 +199,8 @@ class PROTOBUF_EXPORT InlinedStringField { uint32_t* donating_states, uint32_t mask); // Release returns a std::string* instance that is heap-allocated and is not - // Own()'d by any arena. If the field is not set, this returns NULL. The - // caller retains ownership. Clears this field back to NULL state. Used to + // Own()'d by any arena. If the field is not set, this returns nullptr. The + // caller retains ownership. Clears this field back to nullptr state. Used to // implement release_() methods on generated classes. PROTOBUF_MUST_USE_RESULT std::string* Release( const std::string* default_value, Arena* arena, bool donated); @@ -248,9 +248,9 @@ class PROTOBUF_EXPORT InlinedStringField { get_mutable()->clear(); } - // Clears content, but keeps allocated std::string if arena != NULL, to avoid - // the overhead of heap operations. After this returns, the content (as seen - // by the user) will always be equal to |default_value|. + // Clears content, but keeps allocated std::string if arena != nullptr, to + // avoid the overhead of heap operations. After this returns, the content (as + // seen by the user) will always be equal to |default_value|. void ClearToDefault(const LazyString& default_value, Arena* arena, bool donated); diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc index 1b80068d0a1a1..20977b762f552 100644 --- a/src/google/protobuf/io/coded_stream.cc +++ b/src/google/protobuf/io/coded_stream.cc @@ -946,7 +946,7 @@ CodedOutputStream::~CodedOutputStream() { Trim(); } uint8_t* CodedOutputStream::WriteStringWithSizeToArray(const std::string& str, uint8_t* target) { - GOOGLE_DCHECK_LE(str.size(), kuint32max); + GOOGLE_DCHECK_LE(str.size(), std::numeric_limits::max()); target = WriteVarint32ToArray(str.size(), target); return WriteStringToArray(str, target); } diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index 40896e7b19041..13674e4f61cb4 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -116,6 +116,7 @@ #include #include #include +#include #include #include #include @@ -1551,7 +1552,7 @@ inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input) last_tag_(0), legitimate_message_end_(false), aliasing_enabled_(false), - current_limit_(kint32max), + current_limit_(std::numeric_limits::max()), buffer_size_after_limit_(0), total_bytes_limit_(kDefaultTotalBytesLimit), recursion_budget_(default_recursion_limit_), diff --git a/src/google/protobuf/io/printer.h b/src/google/protobuf/io/printer.h index d4051e2d2b722..e857cf08a8284 100644 --- a/src/google/protobuf/io/printer.h +++ b/src/google/protobuf/io/printer.h @@ -82,9 +82,9 @@ class AnnotationProtoCollector : public AnnotationCollector { : annotation_proto_(annotation_proto) {} // Override for AnnotationCollector::AddAnnotation. - virtual void AddAnnotation(size_t begin_offset, size_t end_offset, - const std::string& file_path, - const std::vector& path) override { + void AddAnnotation(size_t begin_offset, size_t end_offset, + const std::string& file_path, + const std::vector& path) override { typename AnnotationProto::Annotation* annotation = annotation_proto_->add_annotation(); for (int i = 0; i < path.size(); ++i) { @@ -95,7 +95,7 @@ class AnnotationProtoCollector : public AnnotationCollector { annotation->set_end(end_offset); } // Override for AnnotationCollector::AddAnnotation. - virtual void AddAnnotationNew(Annotation& a) override { + void AddAnnotationNew(Annotation& a) override { auto* annotation = annotation_proto_->add_annotation(); annotation->ParseFromString(a.second); annotation->set_begin(a.first.first); diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index 6a48673b974de..3ee81abc806b5 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc @@ -224,6 +224,21 @@ Tokenizer::~Tokenizer() { } } +bool Tokenizer::report_whitespace() const { return report_whitespace_; } +// Note: `set_report_whitespace(false)` implies `set_report_newlines(false)`. +void Tokenizer::set_report_whitespace(bool report) { + report_whitespace_ = report; + report_newlines_ &= report; +} + +// If true, newline tokens are reported by Next(). +bool Tokenizer::report_newlines() const { return report_newlines_; } +// Note: `set_report_newlines(true)` implies `set_report_whitespace(true)`. +void Tokenizer::set_report_newlines(bool report) { + report_newlines_ = report; + report_whitespace_ |= report; // enable report_whitespace if necessary +} + // ------------------------------------------------------------------- // Internal helpers. @@ -560,13 +575,46 @@ Tokenizer::NextCommentStatus Tokenizer::TryConsumeCommentStart() { } } +bool Tokenizer::TryConsumeWhitespace() { + if (report_newlines_) { + if (TryConsumeOne()) { + ConsumeZeroOrMore(); + current_.type = TYPE_WHITESPACE; + return true; + } + return false; + } + if (TryConsumeOne()) { + ConsumeZeroOrMore(); + current_.type = TYPE_WHITESPACE; + return report_whitespace_; + } + return false; +} + +bool Tokenizer::TryConsumeNewline() { + if (!report_whitespace_ || !report_newlines_) { + return false; + } + if (TryConsume('\n')) { + current_.type = TYPE_NEWLINE; + return true; + } + return false; +} + // ------------------------------------------------------------------- bool Tokenizer::Next() { previous_ = current_; while (!read_error_) { - ConsumeZeroOrMore(); + StartToken(); + bool report_token = TryConsumeWhitespace() || TryConsumeNewline(); + EndToken(); + if (report_token) { + return true; + } switch (TryConsumeCommentStart()) { case LINE_COMMENT: @@ -990,7 +1038,8 @@ static inline bool IsTrailSurrogate(uint32_t code_point) { } // Combine a head and trail surrogate into a single Unicode code point. -static uint32_t AssembleUTF16(uint32_t head_surrogate, uint32_t trail_surrogate) { +static uint32_t AssembleUTF16(uint32_t head_surrogate, + uint32_t trail_surrogate) { GOOGLE_DCHECK(IsHeadSurrogate(head_surrogate)); GOOGLE_DCHECK(IsTrailSurrogate(trail_surrogate)); return 0x10000 + (((head_surrogate - kMinHeadSurrogate) << 10) | diff --git a/src/google/protobuf/io/tokenizer.h b/src/google/protobuf/io/tokenizer.h index ac23c2eacd480..f7b693e8ac08f 100644 --- a/src/google/protobuf/io/tokenizer.h +++ b/src/google/protobuf/io/tokenizer.h @@ -122,6 +122,13 @@ class PROTOBUF_EXPORT Tokenizer { TYPE_SYMBOL, // Any other printable character, like '!' or '+'. // Symbols are always a single character, so "!+$%" is // four tokens. + TYPE_WHITESPACE, // A sequence of whitespace. This token type is only + // produced if report_whitespace() is true. It is not + // reported for whitespace within comments or strings. + TYPE_NEWLINE, // A newline (\n). This token type is only + // produced if report_whitespace() is true and + // report_newlines() is true. It is not reported for + // newlines in comments or strings. }; // Structure representing a token read from the token stream. @@ -252,6 +259,16 @@ class PROTOBUF_EXPORT Tokenizer { allow_multiline_strings_ = allow; } + // If true, whitespace tokens are reported by Next(). + // Note: `set_report_whitespace(false)` implies `set_report_newlines(false)`. + bool report_whitespace() const; + void set_report_whitespace(bool report); + + // If true, newline tokens are reported by Next(). + // Note: `set_report_newlines(true)` implies `set_report_whitespace(true)`. + bool report_newlines() const; + void set_report_newlines(bool report); + // External helper: validate an identifier. static bool IsIdentifier(const std::string& text); @@ -287,6 +304,8 @@ class PROTOBUF_EXPORT Tokenizer { CommentStyle comment_style_; bool require_space_after_number_; bool allow_multiline_strings_; + bool report_whitespace_ = false; + bool report_newlines_ = false; // Since we count columns we need to interpret tabs somehow. We'll take // the standard 8-character definition for lack of any way to do better. @@ -360,6 +379,14 @@ class PROTOBUF_EXPORT Tokenizer { // of comment it is. NextCommentStatus TryConsumeCommentStart(); + // If we're looking at a TYPE_WHITESPACE token and `report_whitespace_` is + // true, consume it and return true. + bool TryConsumeWhitespace(); + + // If we're looking at a TYPE_NEWLINE token and `report_newlines_` is true, + // consume it and return true. + bool TryConsumeNewline(); + // ----------------------------------------------------------------- // These helper methods make the parsing code more readable. The // "character classes" referred to are defined at the top of the .cc file. diff --git a/src/google/protobuf/io/tokenizer_unittest.cc b/src/google/protobuf/io/tokenizer_unittest.cc index 2233eb9c1d4ce..0b2e76c66bd2e 100644 --- a/src/google/protobuf/io/tokenizer_unittest.cc +++ b/src/google/protobuf/io/tokenizer_unittest.cc @@ -317,6 +317,45 @@ TEST_1D(TokenizerTest, FloatSuffix, kBlockSizes) { EXPECT_TRUE(error_collector.text_.empty()); } +SimpleTokenCase kWhitespaceTokenCases[] = { + {" ", Tokenizer::TYPE_WHITESPACE}, + {" ", Tokenizer::TYPE_WHITESPACE}, + {"\t", Tokenizer::TYPE_WHITESPACE}, + {"\v", Tokenizer::TYPE_WHITESPACE}, + {"\t ", Tokenizer::TYPE_WHITESPACE}, + {"\v\t", Tokenizer::TYPE_WHITESPACE}, + {" \t\r", Tokenizer::TYPE_WHITESPACE}, + // Newlines: + {"\n", Tokenizer::TYPE_NEWLINE}, +}; + +TEST_2D(TokenizerTest, Whitespace, kWhitespaceTokenCases, kBlockSizes) { + { + TestInputStream input(kWhitespaceTokenCases_case.input.data(), + kWhitespaceTokenCases_case.input.size(), + kBlockSizes_case); + TestErrorCollector error_collector; + Tokenizer tokenizer(&input, &error_collector); + + EXPECT_FALSE(tokenizer.Next()); + } + { + TestInputStream input(kWhitespaceTokenCases_case.input.data(), + kWhitespaceTokenCases_case.input.size(), + kBlockSizes_case); + TestErrorCollector error_collector; + Tokenizer tokenizer(&input, &error_collector); + tokenizer.set_report_whitespace(true); + tokenizer.set_report_newlines(true); + + ASSERT_TRUE(tokenizer.Next()); + EXPECT_EQ(tokenizer.current().text, kWhitespaceTokenCases_case.input); + EXPECT_EQ(tokenizer.current().type, kWhitespaceTokenCases_case.type); + + EXPECT_FALSE(tokenizer.Next()); + } +} + #endif // ------------------------------------------------------------------- @@ -476,6 +515,81 @@ TEST_2D(TokenizerTest, MultipleTokens, kMultiTokenCases, kBlockSizes) { EXPECT_TRUE(error_collector.text_.empty()); } +MultiTokenCase kMultiWhitespaceTokenCases[] = { + // Test all token types at the same time. + {"foo 1 \t1.2 \n +\v'bar'", + { + {Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0, 3}, + {Tokenizer::TYPE_WHITESPACE, " ", 0, 3, 4}, + {Tokenizer::TYPE_INTEGER, "1", 0, 4, 5}, + {Tokenizer::TYPE_WHITESPACE, " \t", 0, 5, 8}, + {Tokenizer::TYPE_FLOAT, "1.2", 0, 8, 11}, + {Tokenizer::TYPE_WHITESPACE, " ", 0, 11, 13}, + {Tokenizer::TYPE_NEWLINE, "\n", 0, 13, 0}, + {Tokenizer::TYPE_WHITESPACE, " ", 1, 0, 3}, + {Tokenizer::TYPE_SYMBOL, "+", 1, 3, 4}, + {Tokenizer::TYPE_WHITESPACE, "\v", 1, 4, 5}, + {Tokenizer::TYPE_STRING, "'bar'", 1, 5, 10}, + {Tokenizer::TYPE_END, "", 1, 10, 10}, + }}, + +}; + +TEST_2D(TokenizerTest, MultipleWhitespaceTokens, kMultiWhitespaceTokenCases, + kBlockSizes) { + // Set up the tokenizer. + TestInputStream input(kMultiWhitespaceTokenCases_case.input.data(), + kMultiWhitespaceTokenCases_case.input.size(), + kBlockSizes_case); + TestErrorCollector error_collector; + Tokenizer tokenizer(&input, &error_collector); + tokenizer.set_report_whitespace(true); + tokenizer.set_report_newlines(true); + + // Before Next() is called, the initial token should always be TYPE_START. + EXPECT_EQ(Tokenizer::TYPE_START, tokenizer.current().type); + EXPECT_EQ("", tokenizer.current().text); + EXPECT_EQ(0, tokenizer.current().line); + EXPECT_EQ(0, tokenizer.current().column); + EXPECT_EQ(0, tokenizer.current().end_column); + + // Loop through all expected tokens. + int i = 0; + Tokenizer::Token token; + do { + token = kMultiWhitespaceTokenCases_case.output[i++]; + + SCOPED_TRACE(testing::Message() << "Token #" << i << ": " << token.text); + + Tokenizer::Token previous = tokenizer.current(); + + // Next() should only return false when it hits the end token. + if (token.type != Tokenizer::TYPE_END) { + ASSERT_TRUE(tokenizer.Next()); + } else { + ASSERT_FALSE(tokenizer.Next()); + } + + // Check that the previous token is set correctly. + EXPECT_EQ(previous.type, tokenizer.previous().type); + EXPECT_EQ(previous.text, tokenizer.previous().text); + EXPECT_EQ(previous.line, tokenizer.previous().line); + EXPECT_EQ(previous.column, tokenizer.previous().column); + EXPECT_EQ(previous.end_column, tokenizer.previous().end_column); + + // Check that the token matches the expected one. + EXPECT_EQ(token.type, tokenizer.current().type); + EXPECT_EQ(token.text, tokenizer.current().text); + EXPECT_EQ(token.line, tokenizer.current().line); + EXPECT_EQ(token.column, tokenizer.current().column); + EXPECT_EQ(token.end_column, tokenizer.current().end_column); + + } while (token.type != Tokenizer::TYPE_END); + + // There should be no errors. + EXPECT_TRUE(error_collector.text_.empty()); +} + // This test causes gcc 3.3.5 (and earlier?) to give the cryptic error: // "sorry, unimplemented: `method_call_expr' not supported by dump_expr" #if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h index 1bd0d932c2362..0708366c686b9 100644 --- a/src/google/protobuf/map.h +++ b/src/google/protobuf/map.h @@ -50,6 +50,10 @@ #include #endif // defined(__cpp_lib_string_view) +#if !defined(GOOGLE_PROTOBUF_NO_RDTSC) && defined(__APPLE__) +#include +#endif + #include #include #include @@ -1080,12 +1084,24 @@ class Map { // lower bits are not very random, due to alignment, so we discard them // and shift the higher bits into their place. size_type s = reinterpret_cast(this) >> 4; -#if defined(__x86_64__) && defined(__GNUC__) && \ - !defined(GOOGLE_PROTOBUF_NO_RDTSC) +#if !defined(GOOGLE_PROTOBUF_NO_RDTSC) +#if defined(__APPLE__) + // Use a commpage-based fast time function on Apple environments (MacOS, + // iOS, tvOS, watchOS, etc). + s += mach_absolute_time(); +#elif defined(__x86_64__) && defined(__GNUC__) uint32_t hi, lo; asm volatile("rdtsc" : "=a"(lo), "=d"(hi)); s += ((static_cast(hi) << 32) | lo); +#elif defined(__aarch64__) && defined(__GNUC__) + // There is no rdtsc on ARMv8. CNTVCT_EL0 is the virtual counter of the + // system timer. It runs at a different frequency than the CPU's, but is + // the best source of time-based entropy we get. + uint64_t virtual_timer_value; + asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value)); + s += virtual_timer_value; #endif +#endif // !defined(GOOGLE_PROTOBUF_NO_RDTSC) return s; } diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h index 7dd50e2389b56..082a1eef567e1 100644 --- a/src/google/protobuf/map_entry_lite.h +++ b/src/google/protobuf/map_entry_lite.h @@ -194,7 +194,7 @@ class MapEntryImpl : public Base { _has_bits_{} {} ~MapEntryImpl() { - if (Base::GetArenaForAllocation() != NULL) return; + if (Base::GetArenaForAllocation() != nullptr) return; KeyTypeHandler::DeleteNoArena(key_); ValueTypeHandler::DeleteNoArena(value_); } @@ -528,7 +528,9 @@ class MapEntryLite : public MapEntryImpl(); } + ~MapEntryLite() { + MessageLite::_internal_metadata_.template Delete(); + } void MergeFrom(const MapEntryLite& other) { MergeFromInternal(other); } private: diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc index 1581cafd65edd..367cc2a4ce703 100644 --- a/src/google/protobuf/map_field.cc +++ b/src/google/protobuf/map_field.cc @@ -40,7 +40,7 @@ namespace protobuf { namespace internal { MapFieldBase::~MapFieldBase() { - if (repeated_field_ != NULL && arena_ == NULL) delete repeated_field_; + if (repeated_field_ != nullptr && arena_ == nullptr) delete repeated_field_; } const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const { @@ -56,9 +56,44 @@ RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() { return reinterpret_cast(repeated_field_); } +void MapFieldBase::SwapState(MapFieldBase* other) { + // a relaxed swap of the atomic + auto other_state = other->state_.load(std::memory_order_relaxed); + auto this_state = state_.load(std::memory_order_relaxed); + other->state_.store(this_state, std::memory_order_relaxed); + state_.store(other_state, std::memory_order_relaxed); +} + +void SwapRepeatedPtrToNull(RepeatedPtrField** from, + RepeatedPtrField** to, Arena* from_arena, + Arena* to_arena) { + GOOGLE_DCHECK(*from != nullptr); + GOOGLE_DCHECK(*to == nullptr); + *to = Arena::CreateMessage >(to_arena); + **to = std::move(**from); + if (from_arena == nullptr) { + delete *from; + } + *from = nullptr; +} + void MapFieldBase::Swap(MapFieldBase* other) { - // TODO(teboring): This is incorrect when on different arenas. - InternalSwap(other); + if (arena_ == other->arena_) { + InternalSwap(other); + return; + } + if (repeated_field_ != nullptr || other->repeated_field_ != nullptr) { + if (repeated_field_ == nullptr) { + SwapRepeatedPtrToNull(&other->repeated_field_, &repeated_field_, + other->arena_, arena_); + } else if (other->repeated_field_ == nullptr) { + SwapRepeatedPtrToNull(&repeated_field_, &other->repeated_field_, arena_, + other->arena_); + } else { + repeated_field_->Swap(other->repeated_field_); + } + } + SwapState(other); } void MapFieldBase::UnsafeShallowSwap(MapFieldBase* other) { @@ -69,11 +104,7 @@ void MapFieldBase::UnsafeShallowSwap(MapFieldBase* other) { void MapFieldBase::InternalSwap(MapFieldBase* other) { std::swap(arena_, other->arena_); std::swap(repeated_field_, other->repeated_field_); - // a relaxed swap of the atomic - auto other_state = other->state_.load(std::memory_order_relaxed); - auto this_state = state_.load(std::memory_order_relaxed); - other->state_.store(this_state, std::memory_order_relaxed); - state_.store(other_state, std::memory_order_relaxed); + SwapState(other); } size_t MapFieldBase::SpaceUsedExcludingSelfLong() const { @@ -86,7 +117,7 @@ size_t MapFieldBase::SpaceUsedExcludingSelfLong() const { } size_t MapFieldBase::SpaceUsedExcludingSelfNoLock() const { - if (repeated_field_ != NULL) { + if (repeated_field_ != nullptr) { return repeated_field_->SpaceUsedExcludingSelfLong(); } else { return 0; @@ -156,7 +187,7 @@ void MapFieldBase::SyncRepeatedFieldWithMap() const { } void MapFieldBase::SyncRepeatedFieldWithMapNoLock() const { - if (repeated_field_ == NULL) { + if (repeated_field_ == nullptr) { repeated_field_ = Arena::CreateMessage >(arena_); } } @@ -403,7 +434,7 @@ void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const { const Reflection* reflection = default_entry_->GetReflection(); const FieldDescriptor* key_des = default_entry_->GetDescriptor()->map_key(); const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value(); - if (MapFieldBase::repeated_field_ == NULL) { + if (MapFieldBase::repeated_field_ == nullptr) { MapFieldBase::repeated_field_ = Arena::CreateMessage >(MapFieldBase::arena_); } @@ -566,7 +597,7 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const { size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const { size_t size = 0; - if (MapFieldBase::repeated_field_ != NULL) { + if (MapFieldBase::repeated_field_ != nullptr) { size += MapFieldBase::repeated_field_->SpaceUsedExcludingSelfLong(); } size += sizeof(map_); diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h index 666844168116f..c87d44e5eb270 100644 --- a/src/google/protobuf/map_field.h +++ b/src/google/protobuf/map_field.h @@ -324,7 +324,7 @@ class MapFieldAccessor; class PROTOBUF_EXPORT MapFieldBase { public: MapFieldBase() - : arena_(NULL), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {} + : arena_(nullptr), repeated_field_(nullptr), state_(STATE_MODIFIED_MAP) {} // This constructor is for constant initialized global instances. // It uses a linker initialized mutex, so it is not compatible with regular @@ -466,6 +466,10 @@ class PROTOBUF_EXPORT MapFieldBase { // IncreaseIterator() is called by operator++() of MapIterator only. // It implements the ++ operator of MapIterator. virtual void IncreaseIterator(MapIterator* map_iter) const = 0; + + // Swaps state_ with another MapFieldBase + void SwapState(MapFieldBase* other); + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldBase); }; @@ -573,15 +577,15 @@ class MapField : public TypeDefinedMapFieldBase { void InternalSwap(MapField* other); // Used in the implementation of parsing. Caller should take the ownership iff - // arena_ is NULL. + // arena_ is nullptr. EntryType* NewEntry() const { return impl_.NewEntry(); } // Used in the implementation of serializing enum value type. Caller should - // take the ownership iff arena_ is NULL. + // take the ownership iff arena_ is nullptr. EntryType* NewEnumEntryWrapper(const Key& key, const T t) const { return impl_.NewEnumEntryWrapper(key, t); } // Used in the implementation of serializing other value types. Caller should - // take the ownership iff arena_ is NULL. + // take the ownership iff arena_ is nullptr. EntryType* NewEntryWrapper(const Key& key, const T& t) const { return impl_.NewEntryWrapper(key, t); } diff --git a/src/google/protobuf/map_field_inl.h b/src/google/protobuf/map_field_inl.h index 35231b2e7aacc..7c4c2323c4116 100644 --- a/src/google/protobuf/map_field_inl.h +++ b/src/google/protobuf/map_field_inl.h @@ -138,7 +138,7 @@ template void TypeDefinedMapFieldBase::InitializeIterator( MapIterator* map_iter) const { map_iter->iter_ = new typename Map::const_iterator; - GOOGLE_CHECK(map_iter->iter_ != NULL); + GOOGLE_CHECK(map_iter->iter_ != nullptr); } template @@ -304,7 +304,7 @@ template void MapField::SyncRepeatedFieldWithMapNoLock() const { - if (this->MapFieldBase::repeated_field_ == NULL) { + if (this->MapFieldBase::repeated_field_ == nullptr) { this->MapFieldBase::repeated_field_ = Arena::CreateMessage >( this->MapFieldBase::arena_); @@ -341,7 +341,7 @@ void MapField* repeated_field = reinterpret_cast*>( this->MapFieldBase::repeated_field_); - GOOGLE_CHECK(this->MapFieldBase::repeated_field_ != NULL); + GOOGLE_CHECK(this->MapFieldBase::repeated_field_ != nullptr); map->clear(); for (typename RepeatedPtrField::iterator it = repeated_field->begin(); @@ -361,7 +361,7 @@ template ::SpaceUsedExcludingSelfNoLock() const { size_t size = 0; - if (this->MapFieldBase::repeated_field_ != NULL) { + if (this->MapFieldBase::repeated_field_ != nullptr) { size += this->MapFieldBase::repeated_field_->SpaceUsedExcludingSelfLong(); } size += impl_.GetMap().SpaceUsedExcludingSelfLong(); diff --git a/src/google/protobuf/map_field_lite.h b/src/google/protobuf/map_field_lite.h index 2a321063e1709..255a0bc15b802 100644 --- a/src/google/protobuf/map_field_lite.h +++ b/src/google/protobuf/map_field_lite.h @@ -84,17 +84,17 @@ class MapFieldLite { void InternalSwap(MapFieldLite* other) { map_.InternalSwap(other->map_); } // Used in the implementation of parsing. Caller should take the ownership iff - // arena_ is NULL. + // arena_ is nullptr. EntryType* NewEntry() const { return Arena::CreateMessage(map_.arena()); } // Used in the implementation of serializing enum value type. Caller should - // take the ownership iff arena_ is NULL. + // take the ownership iff arena_ is nullptr. EntryType* NewEnumEntryWrapper(const Key& key, const T t) const { return EntryType::EnumWrap(key, t, map_.arena_); } // Used in the implementation of serializing other value types. Caller should - // take the ownership iff arena_ is NULL. + // take the ownership iff arena_ is nullptr. EntryType* NewEntryWrapper(const Key& key, const T& t) const { return EntryType::Wrap(key, t, map_.arena_); } diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc index 982a34ffb8621..cfc08f4f6a9d8 100644 --- a/src/google/protobuf/map_field_test.cc +++ b/src/google/protobuf/map_field_test.cc @@ -209,7 +209,7 @@ TEST_P(MapFieldBasePrimitiveTest, Arena) { Arena::CreateMessage(&arena); // Trigger conversion to repeated field. - EXPECT_TRUE(map_field->MutableRepeatedField() != NULL); + EXPECT_TRUE(map_field->MutableRepeatedField() != nullptr); EXPECT_EQ(map_field->GetArenaForInternalRepeatedField(), &arena); } @@ -308,7 +308,7 @@ class MapFieldStateTest EXPECT_EQ(map_size, map->size()); if (is_repeated_null) { - EXPECT_TRUE(repeated_field == NULL); + EXPECT_TRUE(repeated_field == nullptr); } else { if (repeated_field == nullptr) { EXPECT_EQ(repeated_size, 0); diff --git a/src/google/protobuf/map_test.inc b/src/google/protobuf/map_test.inc index 4e8304fa4680c..733f13beff186 100644 --- a/src/google/protobuf/map_test.inc +++ b/src/google/protobuf/map_test.inc @@ -884,7 +884,7 @@ TEST_F(MapImplTest, CopyConstructorWithArena) { } TEST_F(MapImplTest, CopyConstructorWithoutArena) { - CopyConstructorHelper(NULL, &map_); + CopyConstructorHelper(nullptr, &map_); } TEST_F(MapImplTest, IterConstructor) { @@ -1023,6 +1023,33 @@ TEST_F(MapImplTest, SwapArena) { EXPECT_THAT(m2, testing::UnorderedElementsAre(testing::Pair(9398, 41999))); } +TEST_F(MapImplTest, SwapFieldArenaReflection) { + MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor()); + Arena arena; + + { + // Tests filled lfs and empty rhs. + TestMap rhs; + + { + // Use local_arena to allocate lhs to trigger use-after-free error. + Arena local_arena; + auto* lhs = Arena::CreateMessage(&local_arena); + const auto* reflection = lhs->GetReflection(); + std::vector fields; + + reflection_tester.SetMapFieldsViaReflection(lhs); + reflection->ListFields(*lhs, &fields); + + reflection->SwapFields(lhs, &rhs, fields); + + reflection_tester.ExpectClearViaReflection(*lhs); + } + + reflection_tester.ExpectMapFieldsSetViaReflection(rhs); + } +} + TEST_F(MapImplTest, CopyAssignMapIterator) { TestMap message; MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor()); @@ -1091,11 +1118,7 @@ bool MapOrderingIsRandom(int a, int b) { } // This test verifies that the iteration order is reasonably random even for -// small maps. Currently we only have sufficient randomness for debug builds and -// builds where we can use the RDTSC instruction, so we only test for those -// builds. -#if defined(__x86_64__) && defined(__GNUC__) && \ - !defined(GOOGLE_PROTOBUF_NO_RDTSC) +// small maps. TEST_F(MapImplTest, RandomOrdering) { for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { @@ -1105,7 +1128,6 @@ TEST_F(MapImplTest, RandomOrdering) { } } } -#endif template void TestTransparent(const Key& key, const Key& miss_key) { @@ -3018,8 +3040,8 @@ class MapFieldInDynamicMessageTest : public testing::Test { std::string(UNITTEST_PACKAGE_NAME) + ".TestMap"); recursive_map_descriptor_ = pool_->FindMessageTypeByName( std::string(UNITTEST_PACKAGE_NAME) + ".TestRecursiveMapMessage"); - ASSERT_TRUE(map_descriptor_ != NULL); - ASSERT_TRUE(recursive_map_descriptor_ != NULL); + ASSERT_TRUE(map_descriptor_ != nullptr); + ASSERT_TRUE(recursive_map_descriptor_ != nullptr); map_prototype_ = factory_.GetPrototype(map_descriptor_); } }; @@ -3759,7 +3781,7 @@ TEST(ArenaTest, StringMapNoLeak) { } (*message->mutable_map_string_string())[data] = data; // We rely on heap checkers to detect memory leak for us. - ASSERT_FALSE(message == NULL); + ASSERT_FALSE(message == nullptr); } TEST(ArenaTest, IsInitialized) { diff --git a/src/google/protobuf/map_type_handler.h b/src/google/protobuf/map_type_handler.h index 7f2892bfb59fc..2857342519f31 100644 --- a/src/google/protobuf/map_type_handler.h +++ b/src/google/protobuf/map_type_handler.h @@ -510,7 +510,7 @@ inline size_t MapTypeHandler inline void MapTypeHandler::Clear( Type** value, Arena* /* arena */) { - if (*value != NULL) (*value)->Clear(); + if (*value != nullptr) (*value)->Clear(); } template inline void MapTypeHandler::Merge( @@ -533,7 +533,7 @@ constexpr auto MapTypeHandler::Constinit() template inline Type* MapTypeHandler::EnsureMutable( Type** value, Arena* arena) { - if (*value == NULL) { + if (*value == nullptr) { *value = MapArenaMessageCreator< Type, Arena::is_arena_constructable::type::value>::CreateMessage(arena); @@ -545,7 +545,7 @@ template inline const Type& MapTypeHandler::DefaultIfNotInitialized( const Type* value) { - return value != NULL ? *value : *Type::internal_default_instance(); + return value != nullptr ? *value : *Type::internal_default_instance(); } template diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc index 6f40694841a52..7e50ef17a7a77 100644 --- a/src/google/protobuf/message.cc +++ b/src/google/protobuf/message.cc @@ -275,35 +275,35 @@ const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) { { ReaderMutexLock lock(&mutex_); const Message* result = FindPtrOrNull(type_map_, type); - if (result != NULL) return result; + if (result != nullptr) return result; } // If the type is not in the generated pool, then we can't possibly handle // it. - if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL; + if (type->file()->pool() != DescriptorPool::generated_pool()) return nullptr; // Apparently the file hasn't been registered yet. Let's do that now. const internal::DescriptorTable* registration_data = FindPtrOrNull(file_map_, type->file()->name().c_str()); - if (registration_data == NULL) { + if (registration_data == nullptr) { GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't " "registered: " << type->file()->name(); - return NULL; + return nullptr; } WriterMutexLock lock(&mutex_); // Check if another thread preempted us. const Message* result = FindPtrOrNull(type_map_, type); - if (result == NULL) { + if (result == nullptr) { // Nope. OK, register everything. internal::RegisterFileLevelMetadata(registration_data); // Should be here now. result = FindPtrOrNull(type_map_, type); } - if (result == NULL) { + if (result == nullptr) { GOOGLE_LOG(DFATAL) << "Type appears to be in generated pool but wasn't " << "registered: " << type->full_name(); } @@ -367,7 +367,7 @@ const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor( } } GOOGLE_LOG(FATAL) << "Should not reach here."; - return NULL; + return nullptr; } namespace internal { diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h index c03ad4bd74e0c..ca33dbe8389ed 100644 --- a/src/google/protobuf/message.h +++ b/src/google/protobuf/message.h @@ -1020,6 +1020,11 @@ class PROTOBUF_EXPORT Reflection final { IsEagerlyVerifiedLazyField(field); } + // Returns true if the field is lazy extension. It is meant to allow python + // reparse lazy field until b/157559327 is fixed. + bool IsLazyExtension(const Message& message, + const FieldDescriptor* field) const; + bool IsLazilyVerifiedLazyField(const FieldDescriptor* field) const; bool IsEagerlyVerifiedLazyField(const FieldDescriptor* field) const; diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc index 3dea09e4088a0..85d0e070dbf38 100644 --- a/src/google/protobuf/message_lite.cc +++ b/src/google/protobuf/message_lite.cc @@ -197,7 +197,7 @@ template bool MergeFromImpl(BoundedZCIS input, MessageLite* msg, MessageLite* MessageLite::New(Arena* arena) const { MessageLite* message = New(); - if (arena != NULL) { + if (arena != nullptr) { arena->Own(message); } return message; diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h index d8138503ce6f0..b41ee02ef6dc7 100644 --- a/src/google/protobuf/message_lite.h +++ b/src/google/protobuf/message_lite.h @@ -218,7 +218,7 @@ class PROTOBUF_EXPORT MessageLite { virtual MessageLite* New() const = 0; // Construct a new instance on the arena. Ownership is passed to the caller - // if arena is a NULL. Default implementation for backwards compatibility. + // if arena is a nullptr. Default implementation for backwards compatibility. virtual MessageLite* New(Arena* arena) const; // Same as GetOwningArena. @@ -520,7 +520,7 @@ class PROTOBUF_EXPORT MessageLite { private: // TODO(gerbens) make this a pure abstract function - virtual const void* InternalGetTable() const { return NULL; } + virtual const void* InternalGetTable() const { return nullptr; } friend class FastReflectionMessageMutator; friend class FastReflectionStringSetter; diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc index 408c23325df76..3e1de4842b730 100644 --- a/src/google/protobuf/message_unittest.inc +++ b/src/google/protobuf/message_unittest.inc @@ -39,6 +39,8 @@ #include #include +#include + #include #ifndef _MSC_VER #include @@ -487,6 +489,8 @@ class RepeatedInputStream : public io::ZeroCopyInputStream { } // namespace TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) { + constexpr int32_t kint32max = std::numeric_limits::max(); + // Create a message with a large std::string field. std::string value = std::string(64 * 1024 * 1024, 'x'); UNITTEST::TestAllTypes message; diff --git a/src/google/protobuf/metadata_lite.h b/src/google/protobuf/metadata_lite.h index 0b90f2851755d..e6ecfb7e21a16 100644 --- a/src/google/protobuf/metadata_lite.h +++ b/src/google/protobuf/metadata_lite.h @@ -188,7 +188,7 @@ class InternalMetadata { template PROTOBUF_NOINLINE void DeleteOutOfLineHelper() { - if (arena() == NULL) { + if (arena() == nullptr) { delete PtrValue>(); } } diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc index 47a35f71ecf82..ebc8a559b253b 100644 --- a/src/google/protobuf/port_def.inc +++ b/src/google/protobuf/port_def.inc @@ -395,7 +395,7 @@ // choose 16 rather than some other number just in case the compiler would // be confused by an unaligned pointer. #define PROTOBUF_FIELD_OFFSET(TYPE, FIELD) \ - static_cast< ::google::protobuf::uint32>(reinterpret_cast( \ + static_cast< ::uint32_t>(reinterpret_cast( \ &reinterpret_cast(16)->FIELD) - \ reinterpret_cast(16)) #endif diff --git a/src/google/protobuf/preserve_unknown_enum_test.cc b/src/google/protobuf/preserve_unknown_enum_test.cc index ed21a88b81571..7e6bbf121abcb 100644 --- a/src/google/protobuf/preserve_unknown_enum_test.cc +++ b/src/google/protobuf/preserve_unknown_enum_test.cc @@ -245,7 +245,7 @@ TEST(PreserveUnknownEnumTest, Proto2CatchesUnknownValues) { // SetRepeatedEnumValue. const EnumValueDescriptor* enum_value = repeated_field->enum_type()->FindValueByName("BAR"); - EXPECT_TRUE(enum_value != NULL); + EXPECT_TRUE(enum_value != nullptr); r->AddEnum(&message, repeated_field, enum_value); const FieldDescriptor* singular_field = diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h index 00be9c02b7b93..498ab712bca19 100644 --- a/src/google/protobuf/reflection.h +++ b/src/google/protobuf/reflection.h @@ -92,7 +92,7 @@ class RepeatedFieldRef< const Reflection* reflection = message.GetReflection(); data_ = reflection->RepeatedFieldData(const_cast(&message), field, internal::RefTypeTraits::cpp_type, - NULL); + nullptr); accessor_ = reflection->RepeatedFieldAccessor(field); } @@ -143,7 +143,7 @@ class MutableRepeatedFieldRef< MutableRepeatedFieldRef(Message* message, const FieldDescriptor* field) { const Reflection* reflection = message->GetReflection(); data_ = reflection->RepeatedFieldData( - message, field, internal::RefTypeTraits::cpp_type, NULL); + message, field, internal::RefTypeTraits::cpp_type, nullptr); accessor_ = reflection->RepeatedFieldAccessor(field); } @@ -504,7 +504,7 @@ struct RefTypeTraits< typedef T* IteratorPointerType; static constexpr FieldDescriptor::CppType cpp_type = PrimitiveTraits::cpp_type; - static const Descriptor* GetMessageFieldDescriptor() { return NULL; } + static const Descriptor* GetMessageFieldDescriptor() { return nullptr; } }; template @@ -518,7 +518,7 @@ struct RefTypeTraits< typedef int32_t* IteratorPointerType; static constexpr FieldDescriptor::CppType cpp_type = FieldDescriptor::CPPTYPE_ENUM; - static const Descriptor* GetMessageFieldDescriptor() { return NULL; } + static const Descriptor* GetMessageFieldDescriptor() { return nullptr; } }; template @@ -531,7 +531,7 @@ struct RefTypeTraits< typedef const std::string* IteratorPointerType; static constexpr FieldDescriptor::CppType cpp_type = FieldDescriptor::CPPTYPE_STRING; - static const Descriptor* GetMessageFieldDescriptor() { return NULL; } + static const Descriptor* GetMessageFieldDescriptor() { return nullptr; } }; template @@ -542,7 +542,7 @@ struct MessageDescriptorGetter { }; template <> struct MessageDescriptorGetter { - static const Descriptor* get() { return NULL; } + static const Descriptor* get() { return nullptr; } }; template diff --git a/src/google/protobuf/repeated_field.cc b/src/google/protobuf/repeated_field.cc index 501575bb3fdd7..8a6b75d77eb70 100644 --- a/src/google/protobuf/repeated_field.cc +++ b/src/google/protobuf/repeated_field.cc @@ -50,7 +50,7 @@ namespace internal { void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) { int new_size = current_size_ + extend_amount; if (total_size_ >= new_size) { - // N.B.: rep_ is non-NULL because extend_amount is always > 0, hence + // N.B.: rep_ is non-nullptr because extend_amount is always > 0, hence // total_size must be non-zero since it is lower-bounded by new_size. return &rep_->elements[current_size_]; } @@ -64,7 +64,7 @@ void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) { sizeof(old_rep->elements[0]))) << "Requested size is too large to fit into size_t."; size_t bytes = kRepHeaderSize + sizeof(old_rep->elements[0]) * new_size; - if (arena == NULL) { + if (arena == nullptr) { rep_ = reinterpret_cast(::operator new(bytes)); } else { rep_ = reinterpret_cast(Arena::CreateArray(arena, bytes)); @@ -80,7 +80,7 @@ void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) { } else { rep_->allocated_size = 0; } - if (arena == NULL) { + if (arena == nullptr) { #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) const size_t old_size = old_total_size * sizeof(rep_->elements[0]) + kRepHeaderSize; @@ -98,6 +98,24 @@ void RepeatedPtrFieldBase::Reserve(int new_size) { } } +void RepeatedPtrFieldBase::DestroyProtos() { + GOOGLE_DCHECK(rep_); + GOOGLE_DCHECK(arena_ == nullptr); + int n = rep_->allocated_size; + void* const* elements = rep_->elements; + for (int i = 0; i < n; i++) { + delete static_cast(elements[i]); + } +#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) + const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize; + ::operator delete(static_cast(rep_), size); + rep_ = nullptr; +#else + ::operator delete(static_cast(rep_)); + rep_ = nullptr; +#endif +} + void* RepeatedPtrFieldBase::AddOutOfLineHelper(void* obj) { if (!rep_ || rep_->allocated_size == total_size_) { InternalExtend(1); // Equivalent to "Reserve(total_size_ + 1)" @@ -108,7 +126,7 @@ void* RepeatedPtrFieldBase::AddOutOfLineHelper(void* obj) { } void RepeatedPtrFieldBase::CloseGap(int start, int num) { - if (rep_ == NULL) return; + if (rep_ == nullptr) return; // Close up a gap of "num" elements starting at offset "start". for (int i = start + num; i < rep_->allocated_size; ++i) rep_->elements[i - num] = rep_->elements[i]; @@ -117,7 +135,7 @@ void RepeatedPtrFieldBase::CloseGap(int start, int num) { } MessageLite* RepeatedPtrFieldBase::AddWeak(const MessageLite* prototype) { - if (rep_ != NULL && current_size_ < rep_->allocated_size) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { return reinterpret_cast(rep_->elements[current_size_++]); } if (!rep_ || rep_->allocated_size == total_size_) { diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h index 68f6e435226bf..dd0fa519b9d3a 100644 --- a/src/google/protobuf/repeated_field.h +++ b/src/google/protobuf/repeated_field.h @@ -213,7 +213,7 @@ class RepeatedField final { void RemoveLast(); // Extract elements with indices in "[start .. start+num-1]". - // Copy them into "elements[0 .. num-1]" if "elements" is not NULL. + // Copy them into "elements[0 .. num-1]" if "elements" is not nullptr. // Caution: implementation also moves elements with indices [start+num ..]. // Calling this routine inside a loop can cause quadratic behavior. void ExtractSubrange(int start, int num, Element* elements); @@ -391,7 +391,7 @@ class RepeatedField final { // Internal helper to delete all elements and deallocate the storage. void InternalDeallocate(Rep* rep, int size) { - if (rep != NULL) { + if (rep != nullptr) { Element* e = &rep->elements[0]; if (!std::is_trivial::value) { Element* limit = &rep->elements[size]; @@ -399,7 +399,7 @@ class RepeatedField final { e->~Element(); } } - if (rep->arena == NULL) { + if (rep->arena == nullptr) { #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) const size_t bytes = size * sizeof(*e) + kRepHeaderSize; ::operator delete(static_cast(rep), bytes); @@ -599,6 +599,8 @@ class PROTOBUF_EXPORT RepeatedPtrFieldBase { // Must be called from destructor. template void Destroy(); + bool NeedsDestroy() const { return rep_ != nullptr && arena_ == nullptr; } + void DestroyProtos(); bool empty() const; int size() const; @@ -613,7 +615,8 @@ class PROTOBUF_EXPORT RepeatedPtrFieldBase { template void Delete(int index); template - typename TypeHandler::Type* Add(typename TypeHandler::Type* prototype = NULL); + typename TypeHandler::Type* Add( + typename TypeHandler::Type* prototype = nullptr); public: // The next few methods are public so that they can be called from generated @@ -625,8 +628,8 @@ class PROTOBUF_EXPORT RepeatedPtrFieldBase { // Creates and adds an element using the given prototype, without introducing // a link-time dependency on the concrete message type. This method is used to - // implement implicit weak fields. The prototype may be NULL, in which case an - // ImplicitWeakMessage will be used as a placeholder. + // implement implicit weak fields. The prototype may be nullptr, in which case + // an ImplicitWeakMessage will be used as a placeholder. MessageLite* AddWeak(const MessageLite* prototype); template @@ -681,7 +684,7 @@ class PROTOBUF_EXPORT RepeatedPtrFieldBase { // Advanced memory management -------------------------------------- - // Like Add(), but if there are no cleared objects to use, returns NULL. + // Like Add(), but if there are no cleared objects to use, returns nullptr. template typename TypeHandler::Type* AddFromCleared(); @@ -833,9 +836,9 @@ class GenericTypeHandler { return Arena::Create(arena, std::move(value)); } static inline GenericType* NewFromPrototype(const GenericType* prototype, - Arena* arena = NULL); + Arena* arena = nullptr); static inline void Delete(GenericType* value, Arena* arena) { - if (arena == NULL) { + if (arena == nullptr) { delete value; } } @@ -911,7 +914,7 @@ class StringTypeHandler { } static inline Arena* GetOwningArena(std::string*) { return nullptr; } static inline void Delete(std::string* value, Arena* arena) { - if (arena == NULL) { + if (arena == nullptr) { delete value; } } @@ -1106,9 +1109,9 @@ class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { // Extract elements with indices in the range "[start .. start+num-1]". // The caller assumes ownership of the extracted elements and is responsible // for deleting them when they are no longer needed. - // If "elements" is non-NULL, then pointers to the extracted elements + // If "elements" is non-nullptr, then pointers to the extracted elements // are stored in "elements[0 .. num-1]" for the convenience of the caller. - // If "elements" is NULL, then the caller must use some other mechanism + // If "elements" is nullptr, then the caller must use some other mechanism // to perform any further operations (like deletion) on these elements. // Caution: implementation also moves elements with indices [start+num ..]. // Calling this routine inside a loop can cause quadratic behavior. @@ -1430,7 +1433,7 @@ void RepeatedField::ExtractSubrange(int start, int num, GOOGLE_DCHECK_LE(start + num, this->current_size_); // Save the values of the removed elements if requested. - if (elements != NULL) { + if (elements != nullptr) { for (int i = 0; i < num; ++i) elements[i] = this->Get(i + start); } @@ -1605,7 +1608,7 @@ inline int CalculateReserveSize(int total_size, int new_size) { template void RepeatedField::Reserve(int new_size) { if (total_size_ >= new_size) return; - Rep* old_rep = total_size_ > 0 ? rep() : NULL; + Rep* old_rep = total_size_ > 0 ? rep() : nullptr; Rep* new_rep; Arena* arena = GetArena(); new_size = internal::CalculateReserveSize(total_size_, new_size); @@ -1615,7 +1618,7 @@ void RepeatedField::Reserve(int new_size) { << "Requested size is too large to fit into size_t."; size_t bytes = kRepHeaderSize + sizeof(Element) * static_cast(new_size); - if (arena == NULL) { + if (arena == nullptr) { new_rep = static_cast(::operator new(bytes)); } else { new_rep = reinterpret_cast(Arena::CreateArray(arena, bytes)); @@ -1695,18 +1698,18 @@ struct ElementCopier { namespace internal { constexpr RepeatedPtrFieldBase::RepeatedPtrFieldBase() - : arena_(NULL), current_size_(0), total_size_(0), rep_(NULL) {} + : arena_(nullptr), current_size_(0), total_size_(0), rep_(nullptr) {} inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(Arena* arena) - : arena_(arena), current_size_(0), total_size_(0), rep_(NULL) {} + : arena_(arena), current_size_(0), total_size_(0), rep_(nullptr) {} template void RepeatedPtrFieldBase::Destroy() { - if (rep_ != NULL && arena_ == NULL) { + if (rep_ != nullptr && arena_ == nullptr) { int n = rep_->allocated_size; void* const* elements = rep_->elements; for (int i = 0; i < n; i++) { - TypeHandler::Delete(cast(elements[i]), NULL); + TypeHandler::Delete(cast(elements[i]), nullptr); } #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize; @@ -1715,7 +1718,7 @@ void RepeatedPtrFieldBase::Destroy() { ::operator delete(static_cast(rep_)); #endif } - rep_ = NULL; + rep_ = nullptr; } template @@ -1794,7 +1797,7 @@ inline void RepeatedPtrFieldBase::Delete(int index) { template inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add( typename TypeHandler::Type* prototype) { - if (rep_ != NULL && current_size_ < rep_->allocated_size) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { return cast(rep_->elements[current_size_++]); } typename TypeHandler::Type* result = @@ -1806,7 +1809,7 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add( template ::type*> inline void RepeatedPtrFieldBase::Add(typename TypeHandler::Type&& value) { - if (rep_ != NULL && current_size_ < rep_->allocated_size) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { *cast(rep_->elements[current_size_++]) = std::move(value); return; } @@ -1856,7 +1859,7 @@ inline void RepeatedPtrFieldBase::MergeFrom(const RepeatedPtrFieldBase& other) { inline void RepeatedPtrFieldBase::MergeFromInternal( const RepeatedPtrFieldBase& other, void (RepeatedPtrFieldBase::*inner_loop)(void**, void**, int, int)) { - // Note: wrapper has already guaranteed that other.rep_ != NULL here. + // Note: wrapper has already guaranteed that other.rep_ != nullptr here. int other_size = other.current_size_; void** other_elements = other.rep_->elements; void** new_elements = InternalExtend(other_size); @@ -1906,11 +1909,11 @@ inline void RepeatedPtrFieldBase::CopyFrom(const RepeatedPtrFieldBase& other) { inline int RepeatedPtrFieldBase::Capacity() const { return total_size_; } inline void* const* RepeatedPtrFieldBase::raw_data() const { - return rep_ ? rep_->elements : NULL; + return rep_ ? rep_->elements : nullptr; } inline void** RepeatedPtrFieldBase::raw_mutable_data() const { - return rep_ ? const_cast(rep_->elements) : NULL; + return rep_ ? const_cast(rep_->elements) : nullptr; } template @@ -1936,7 +1939,7 @@ inline void RepeatedPtrFieldBase::SwapElements(int index1, int index2) { template inline size_t RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() const { size_t allocated_bytes = static_cast(total_size_) * sizeof(void*); - if (rep_ != NULL) { + if (rep_ != nullptr) { for (int i = 0; i < rep_->allocated_size; ++i) { allocated_bytes += TypeHandler::SpaceUsedLong(*cast(rep_->elements[i])); @@ -1948,10 +1951,10 @@ inline size_t RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() const { template inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() { - if (rep_ != NULL && current_size_ < rep_->allocated_size) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { return cast(rep_->elements[current_size_++]); } else { - return NULL; + return nullptr; } } @@ -1989,7 +1992,7 @@ void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy( // Ensure that either the value is in the same arena, or if not, we do the // appropriate thing: Own() it (if it's on heap and we're in an arena) or copy // it to our arena/heap (otherwise). - if (my_arena != NULL && value_arena == NULL) { + if (my_arena != nullptr && value_arena == nullptr) { my_arena->Own(value); } else if (my_arena != value_arena) { typename TypeHandler::Type* new_value = @@ -2107,7 +2110,7 @@ inline int RepeatedPtrFieldBase::ClearedCount() const { template inline void RepeatedPtrFieldBase::AddCleared( typename TypeHandler::Type* value) { - GOOGLE_DCHECK(GetArena() == NULL) + GOOGLE_DCHECK(GetArena() == nullptr) << "AddCleared() can only be used on a RepeatedPtrField not on an arena."; GOOGLE_DCHECK(TypeHandler::GetOwningArena(value) == nullptr) << "AddCleared() can only accept values not on an arena."; @@ -2119,11 +2122,11 @@ inline void RepeatedPtrFieldBase::AddCleared( template inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseCleared() { - GOOGLE_DCHECK(GetArena() == NULL) + GOOGLE_DCHECK(GetArena() == nullptr) << "ReleaseCleared() can only be used on a RepeatedPtrField not on " << "an arena."; - GOOGLE_DCHECK(GetArena() == NULL); - GOOGLE_DCHECK(rep_ != NULL); + GOOGLE_DCHECK(GetArena() == nullptr); + GOOGLE_DCHECK(rep_ != nullptr); GOOGLE_DCHECK_GT(rep_->allocated_size, current_size_); return cast(rep_->elements[--rep_->allocated_size]); } @@ -2163,7 +2166,15 @@ inline RepeatedPtrField::RepeatedPtrField(Iter begin, Iter end) { template RepeatedPtrField::~RepeatedPtrField() { - Destroy(); +#ifdef __cpp_if_constexpr + if constexpr (std::is_base_of::value) { +#else + if (std::is_base_of::value) { +#endif + if (NeedsDestroy()) DestroyProtos(); + } else { + Destroy(); + } } template @@ -2344,8 +2355,8 @@ inline void RepeatedPtrField::ExtractSubrangeInternal( // ExtractSubrange() must return heap-allocated objects by contract, and we // cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that // we are not on an arena. - GOOGLE_DCHECK(GetArena() == NULL) - << "ExtractSubrange() when arena is non-NULL is only supported when " + GOOGLE_DCHECK(GetArena() == nullptr) + << "ExtractSubrange() when arena is non-nullptr is only supported when " << "the Element type supplies a MergeFrom() operation to make copies."; UnsafeArenaExtractSubrange(start, num, elements); } @@ -2359,7 +2370,7 @@ inline void RepeatedPtrField::UnsafeArenaExtractSubrange( if (num > 0) { // Save the values of the removed elements if requested. - if (elements != NULL) { + if (elements != nullptr) { for (int i = 0; i < num; ++i) { elements[i] = RepeatedPtrFieldBase::Mutable(i + start); } @@ -2514,7 +2525,7 @@ class RepeatedPtrIterator { using pointer = Element*; using reference = Element&; - RepeatedPtrIterator() : it_(NULL) {} + RepeatedPtrIterator() : it_(nullptr) {} explicit RepeatedPtrIterator(void* const* it) : it_(it) {} // Allow "upcasting" from RepeatedPtrIterator to @@ -2607,7 +2618,7 @@ class RepeatedPtrOverPtrsIterator { using pointer = Element*; using reference = Element&; - RepeatedPtrOverPtrsIterator() : it_(NULL) {} + RepeatedPtrOverPtrsIterator() : it_(nullptr) {} explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {} // dereferenceable diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc index 384d32f530dfa..63b234930ee0a 100644 --- a/src/google/protobuf/repeated_field_reflection_unittest.cc +++ b/src/google/protobuf/repeated_field_reflection_unittest.cc @@ -165,7 +165,7 @@ TEST(RepeatedFieldReflectionTest, ExtensionFields) { const FieldDescriptor* fd_repeated_int64_extension = desc->file()->FindExtensionByName("repeated_int64_extension"); - GOOGLE_CHECK(fd_repeated_int64_extension != NULL); + GOOGLE_CHECK(fd_repeated_int64_extension != nullptr); const RepeatedField& rf_int64_extension = refl->GetRepeatedField(extended_message, @@ -538,7 +538,7 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefForExtensionFields) { const FieldDescriptor* fd_repeated_int64_extension = desc->file()->FindExtensionByName("repeated_int64_extension"); - GOOGLE_CHECK(fd_repeated_int64_extension != NULL); + GOOGLE_CHECK(fd_repeated_int64_extension != nullptr); const RepeatedFieldRef rf_int64_extension = refl->GetRepeatedFieldRef(extended_message, diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc index 5db0b6cf2ca28..ad1e82bfd9690 100644 --- a/src/google/protobuf/repeated_field_unittest.cc +++ b/src/google/protobuf/repeated_field_unittest.cc @@ -1534,7 +1534,7 @@ TEST(RepeatedPtrField, ExtractSubrange) { // Create a catcher array and call ExtractSubrange. std::string* catcher[10]; - for (int i = 0; i < 10; ++i) catcher[i] = NULL; + for (int i = 0; i < 10; ++i) catcher[i] = nullptr; field.ExtractSubrange(start, num, catcher); // Does the resulting array have the right size? @@ -1543,7 +1543,7 @@ TEST(RepeatedPtrField, ExtractSubrange) { // Were the removed elements extracted into the catcher array? for (int i = 0; i < num; ++i) EXPECT_EQ(*catcher[i], *subject[start + i]); - EXPECT_EQ(NULL, catcher[num]); + EXPECT_EQ(nullptr, catcher[num]); // Does the resulting array contain the right values? for (int i = 0; i < start; ++i) @@ -1908,7 +1908,7 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { std::lower_bound(proto_array_.pointer_begin(), proto_array_.pointer_end(), &v, StringLessThan()); - GOOGLE_CHECK(*it != NULL); + GOOGLE_CHECK(*it != nullptr); EXPECT_EQ(**it, "n"); EXPECT_TRUE(it == proto_array_.pointer_begin() + 3); @@ -1919,7 +1919,7 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { const_proto_array_->pointer_begin(), const_proto_array_->pointer_end(), &v, StringLessThan()); - GOOGLE_CHECK(*it != NULL); + GOOGLE_CHECK(*it != nullptr); EXPECT_EQ(**it, "n"); EXPECT_TRUE(it == const_proto_array_->pointer_begin() + 3); diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc index 7748dc365b22d..7ccd359d166a4 100644 --- a/src/google/protobuf/source_context.pb.cc +++ b/src/google/protobuf/source_context.pb.cc @@ -100,7 +100,7 @@ SourceContext::SourceContext(const SourceContext& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceContext) } -void SourceContext::SharedCtor() { +inline void SourceContext::SharedCtor() { file_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index 754be72877901..4a4ac3df59bdc 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h @@ -120,7 +120,12 @@ class PROTOBUF_EXPORT SourceContext final : } inline void Swap(SourceContext* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc index ab60a03c406f5..81c38eb71e1f7 100644 --- a/src/google/protobuf/struct.pb.cc +++ b/src/google/protobuf/struct.pb.cc @@ -205,7 +205,7 @@ Struct::Struct(const Struct& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Struct) } -void Struct::SharedCtor() { +inline void Struct::SharedCtor() { } Struct::~Struct() { @@ -498,7 +498,7 @@ Value::Value(const Value& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Value) } -void Value::SharedCtor() { +inline void Value::SharedCtor() { clear_has_kind(); } @@ -865,7 +865,7 @@ ListValue::ListValue(const ListValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue) } -void ListValue::SharedCtor() { +inline void ListValue::SharedCtor() { } ListValue::~ListValue() { diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index a7fb54f1e766d..151a895640401 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h @@ -185,7 +185,12 @@ class PROTOBUF_EXPORT Struct final : } inline void Swap(Struct* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -351,7 +356,12 @@ class PROTOBUF_EXPORT Value final : } inline void Swap(Value* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -605,7 +615,12 @@ class PROTOBUF_EXPORT ListValue final : } inline void Swap(ListValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index 23125bf4be1ba..821e1ccf336f4 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h @@ -176,7 +176,7 @@ class FatalException : public std::exception { : filename_(filename), line_(line), message_(message) {} virtual ~FatalException() throw(); - virtual const char* what() const throw() override; + const char* what() const throw() override; const char* filename() const { return filename_; } int line() const { return line_; } diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h index 5c025b1496f17..c4599913be223 100644 --- a/src/google/protobuf/stubs/mutex.h +++ b/src/google/protobuf/stubs/mutex.h @@ -144,10 +144,11 @@ using Mutex = WrappedMutex; // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class GOOGLE_PROTOBUF_SCOPED_CAPABILITY PROTOBUF_EXPORT MutexLock { public: - explicit MutexLock(Mutex *mu) GOOGLE_PROTOBUF_ACQUIRE(mu) : mu_(mu) { + explicit MutexLock(Mutex* mu) GOOGLE_PROTOBUF_ACQUIRE(mu) : mu_(mu) { this->mu_->Lock(); } ~MutexLock() GOOGLE_PROTOBUF_RELEASE() { this->mu_->Unlock(); } + private: Mutex *const mu_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock); diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h index d4d2736c8579e..fa0ec47150d79 100644 --- a/src/google/protobuf/stubs/port.h +++ b/src/google/protobuf/stubs/port.h @@ -265,8 +265,7 @@ static inline uint32 bswap_32(uint32 x) { #ifndef bswap_64 static inline uint64 bswap_64(uint64 x) { - return (((x & uint64_t{0xFFu}) << 56) | - ((x & uint64_t{0xFF00u}) << 40) | + return (((x & uint64_t{0xFFu}) << 56) | ((x & uint64_t{0xFF00u}) << 40) | ((x & uint64_t{0xFF0000u}) << 24) | ((x & uint64_t{0xFF000000u}) << 8) | ((x & uint64_t{0xFF00000000u}) >> 8) | diff --git a/src/google/protobuf/stubs/stringprintf_unittest.cc b/src/google/protobuf/stubs/stringprintf_unittest.cc index 63f38bfe1eb4b..dbecd2b33c86a 100644 --- a/src/google/protobuf/stubs/stringprintf_unittest.cc +++ b/src/google/protobuf/stubs/stringprintf_unittest.cc @@ -31,14 +31,13 @@ // from google3/base/stringprintf_unittest.cc #include +#include +#include #include #include #include -#include -#include - namespace google { namespace protobuf { namespace { @@ -110,10 +109,10 @@ TEST(StringPrintfTest, Multibyte) { // Repeat with longer string, to make sure that the dynamically // allocated path in StringAppendV is handled correctly. const size_t n = 2048; - std::array buf; - memset(&buf[0], ' ', n-3); + std::array buf; + memset(&buf[0], ' ', n - 3); memcpy(&buf[0] + n - 3, kInvalidCodePoint, 4); - value = StringPrintf("%.*s", n, &buf[0]); + value = StringPrintf("%.*s", n, &buf[0]); // See GRTEv2 vs. GRTEv3 comment above. EXPECT_TRUE(value.empty() || value == &buf[0]); diff --git a/src/google/protobuf/stubs/strutil_unittest.cc b/src/google/protobuf/stubs/strutil_unittest.cc index 0fbfab4cf66da..0bb9558e54a34 100644 --- a/src/google/protobuf/stubs/strutil_unittest.cc +++ b/src/google/protobuf/stubs/strutil_unittest.cc @@ -345,93 +345,97 @@ static struct { const char* plaintext; const char* ciphertext; } base64_strings[] = { - // Some google quotes - // Ciphertext created with "uuencode (GNU sharutils) 4.6.3" - // (Note that we're testing the websafe encoding, though, so if - // you add messages, be sure to run "tr -- '+/' '-_'" on the output) - { "I was always good at math and science, and I never realized " - "that was unusual or somehow undesirable. So one of the things " - "I care a lot about is helping to remove that stigma, " - "to show girls that you can be feminine, you can like the things " - "that girls like, but you can also be really good at technology. " - "You can be really good at building things." - " - Marissa Meyer, Newsweek, 2010-12-22" "\n", - - "SSB3YXMgYWx3YXlzIGdvb2QgYXQgbWF0aCBhbmQgc2NpZW5jZSwgYW5kIEkg" - "bmV2ZXIgcmVhbGl6ZWQgdGhhdCB3YXMgdW51c3VhbCBvciBzb21laG93IHVu" - "ZGVzaXJhYmxlLiBTbyBvbmUgb2YgdGhlIHRoaW5ncyBJIGNhcmUgYSBsb3Qg" - "YWJvdXQgaXMgaGVscGluZyB0byByZW1vdmUgdGhhdCBzdGlnbWEsIHRvIHNo" - "b3cgZ2lybHMgdGhhdCB5b3UgY2FuIGJlIGZlbWluaW5lLCB5b3UgY2FuIGxp" - "a2UgdGhlIHRoaW5ncyB0aGF0IGdpcmxzIGxpa2UsIGJ1dCB5b3UgY2FuIGFs" - "c28gYmUgcmVhbGx5IGdvb2QgYXQgdGVjaG5vbG9neS4gWW91IGNhbiBiZSBy" - "ZWFsbHkgZ29vZCBhdCBidWlsZGluZyB0aGluZ3MuIC0gTWFyaXNzYSBNZXll" - "ciwgTmV3c3dlZWssIDIwMTAtMTItMjIK" }, - - { "Typical first year for a new cluster: " - "~0.5 overheating " - "~1 PDU failure " - "~1 rack-move " - "~1 network rewiring " - "~20 rack failures " - "~5 racks go wonky " - "~8 network maintenances " - "~12 router reloads " - "~3 router failures " - "~dozens of minor 30-second blips for dns " - "~1000 individual machine failures " - "~thousands of hard drive failures " - "slow disks, bad memory, misconfigured machines, flaky machines, etc." - " - Jeff Dean, The Joys of Real Hardware" "\n", - - "VHlwaWNhbCBmaXJzdCB5ZWFyIGZvciBhIG5ldyBjbHVzdGVyOiB-MC41IG92" - "ZXJoZWF0aW5nIH4xIFBEVSBmYWlsdXJlIH4xIHJhY2stbW92ZSB-MSBuZXR3" - "b3JrIHJld2lyaW5nIH4yMCByYWNrIGZhaWx1cmVzIH41IHJhY2tzIGdvIHdv" - "bmt5IH44IG5ldHdvcmsgbWFpbnRlbmFuY2VzIH4xMiByb3V0ZXIgcmVsb2Fk" - "cyB-MyByb3V0ZXIgZmFpbHVyZXMgfmRvemVucyBvZiBtaW5vciAzMC1zZWNv" - "bmQgYmxpcHMgZm9yIGRucyB-MTAwMCBpbmRpdmlkdWFsIG1hY2hpbmUgZmFp" - "bHVyZXMgfnRob3VzYW5kcyBvZiBoYXJkIGRyaXZlIGZhaWx1cmVzIHNsb3cg" - "ZGlza3MsIGJhZCBtZW1vcnksIG1pc2NvbmZpZ3VyZWQgbWFjaGluZXMsIGZs" - "YWt5IG1hY2hpbmVzLCBldGMuIC0gSmVmZiBEZWFuLCBUaGUgSm95cyBvZiBS" - "ZWFsIEhhcmR3YXJlCg" }, - - { "I'm the head of the webspam team at Google. " - "That means that if you type your name into Google and get porn back, " - "it's my fault. Unless you're a porn star, in which case porn is a " - "completely reasonable response." - " - Matt Cutts, Google Plus" "\n", - - "SSdtIHRoZSBoZWFkIG9mIHRoZSB3ZWJzcGFtIHRlYW0gYXQgR29vZ2xlLiAg" - "VGhhdCBtZWFucyB0aGF0IGlmIHlvdSB0eXBlIHlvdXIgbmFtZSBpbnRvIEdv" - "b2dsZSBhbmQgZ2V0IHBvcm4gYmFjaywgaXQncyBteSBmYXVsdC4gVW5sZXNz" - "IHlvdSdyZSBhIHBvcm4gc3RhciwgaW4gd2hpY2ggY2FzZSBwb3JuIGlzIGEg" - "Y29tcGxldGVseSByZWFzb25hYmxlIHJlc3BvbnNlLiAtIE1hdHQgQ3V0dHMs" - "IEdvb2dsZSBQbHVzCg" }, - - { "It will still be a long time before machines approach human intelligence. " - "But luckily, machines don't actually have to be intelligent; " - "they just have to fake it. Access to a wealth of information, " - "combined with a rudimentary decision-making capacity, " - "can often be almost as useful. Of course, the results are better yet " - "when coupled with intelligence. A reference librarian with access to " - "a good search engine is a formidable tool." - " - Craig Silverstein, Siemens Pictures of the Future, Spring 2004" "\n", - - "SXQgd2lsbCBzdGlsbCBiZSBhIGxvbmcgdGltZSBiZWZvcmUgbWFjaGluZXMg" - "YXBwcm9hY2ggaHVtYW4gaW50ZWxsaWdlbmNlLiBCdXQgbHVja2lseSwgbWFj" - "aGluZXMgZG9uJ3QgYWN0dWFsbHkgaGF2ZSB0byBiZSBpbnRlbGxpZ2VudDsg" - "dGhleSBqdXN0IGhhdmUgdG8gZmFrZSBpdC4gQWNjZXNzIHRvIGEgd2VhbHRo" - "IG9mIGluZm9ybWF0aW9uLCBjb21iaW5lZCB3aXRoIGEgcnVkaW1lbnRhcnkg" - "ZGVjaXNpb24tbWFraW5nIGNhcGFjaXR5LCBjYW4gb2Z0ZW4gYmUgYWxtb3N0" - "IGFzIHVzZWZ1bC4gT2YgY291cnNlLCB0aGUgcmVzdWx0cyBhcmUgYmV0dGVy" - "IHlldCB3aGVuIGNvdXBsZWQgd2l0aCBpbnRlbGxpZ2VuY2UuIEEgcmVmZXJl" - "bmNlIGxpYnJhcmlhbiB3aXRoIGFjY2VzcyB0byBhIGdvb2Qgc2VhcmNoIGVu" - "Z2luZSBpcyBhIGZvcm1pZGFibGUgdG9vbC4gLSBDcmFpZyBTaWx2ZXJzdGVp" - "biwgU2llbWVucyBQaWN0dXJlcyBvZiB0aGUgRnV0dXJlLCBTcHJpbmcgMjAw" - "NAo" }, - - // Degenerate edge case - { "", - "" }, + // Some google quotes + // Ciphertext created with "uuencode (GNU sharutils) 4.6.3" + // (Note that we're testing the websafe encoding, though, so if + // you add messages, be sure to run "tr -- '+/' '-_'" on the output) + {"I was always good at math and science, and I never realized " + "that was unusual or somehow undesirable. So one of the things " + "I care a lot about is helping to remove that stigma, " + "to show girls that you can be feminine, you can like the things " + "that girls like, but you can also be really good at technology. " + "You can be really good at building things." + " - Marissa Meyer, Newsweek, 2010-12-22" + "\n", + + "SSB3YXMgYWx3YXlzIGdvb2QgYXQgbWF0aCBhbmQgc2NpZW5jZSwgYW5kIEkg" + "bmV2ZXIgcmVhbGl6ZWQgdGhhdCB3YXMgdW51c3VhbCBvciBzb21laG93IHVu" + "ZGVzaXJhYmxlLiBTbyBvbmUgb2YgdGhlIHRoaW5ncyBJIGNhcmUgYSBsb3Qg" + "YWJvdXQgaXMgaGVscGluZyB0byByZW1vdmUgdGhhdCBzdGlnbWEsIHRvIHNo" + "b3cgZ2lybHMgdGhhdCB5b3UgY2FuIGJlIGZlbWluaW5lLCB5b3UgY2FuIGxp" + "a2UgdGhlIHRoaW5ncyB0aGF0IGdpcmxzIGxpa2UsIGJ1dCB5b3UgY2FuIGFs" + "c28gYmUgcmVhbGx5IGdvb2QgYXQgdGVjaG5vbG9neS4gWW91IGNhbiBiZSBy" + "ZWFsbHkgZ29vZCBhdCBidWlsZGluZyB0aGluZ3MuIC0gTWFyaXNzYSBNZXll" + "ciwgTmV3c3dlZWssIDIwMTAtMTItMjIK"}, + + {"Typical first year for a new cluster: " + "~0.5 overheating " + "~1 PDU failure " + "~1 rack-move " + "~1 network rewiring " + "~20 rack failures " + "~5 racks go wonky " + "~8 network maintenances " + "~12 router reloads " + "~3 router failures " + "~dozens of minor 30-second blips for dns " + "~1000 individual machine failures " + "~thousands of hard drive failures " + "slow disks, bad memory, misconfigured machines, flaky machines, etc." + " - Jeff Dean, The Joys of Real Hardware" + "\n", + + "VHlwaWNhbCBmaXJzdCB5ZWFyIGZvciBhIG5ldyBjbHVzdGVyOiB-MC41IG92" + "ZXJoZWF0aW5nIH4xIFBEVSBmYWlsdXJlIH4xIHJhY2stbW92ZSB-MSBuZXR3" + "b3JrIHJld2lyaW5nIH4yMCByYWNrIGZhaWx1cmVzIH41IHJhY2tzIGdvIHdv" + "bmt5IH44IG5ldHdvcmsgbWFpbnRlbmFuY2VzIH4xMiByb3V0ZXIgcmVsb2Fk" + "cyB-MyByb3V0ZXIgZmFpbHVyZXMgfmRvemVucyBvZiBtaW5vciAzMC1zZWNv" + "bmQgYmxpcHMgZm9yIGRucyB-MTAwMCBpbmRpdmlkdWFsIG1hY2hpbmUgZmFp" + "bHVyZXMgfnRob3VzYW5kcyBvZiBoYXJkIGRyaXZlIGZhaWx1cmVzIHNsb3cg" + "ZGlza3MsIGJhZCBtZW1vcnksIG1pc2NvbmZpZ3VyZWQgbWFjaGluZXMsIGZs" + "YWt5IG1hY2hpbmVzLCBldGMuIC0gSmVmZiBEZWFuLCBUaGUgSm95cyBvZiBS" + "ZWFsIEhhcmR3YXJlCg"}, + + {"I'm the head of the webspam team at Google. " + "That means that if you type your name into Google and get porn back, " + "it's my fault. Unless you're a porn star, in which case porn is a " + "completely reasonable response." + " - Matt Cutts, Google Plus" + "\n", + + "SSdtIHRoZSBoZWFkIG9mIHRoZSB3ZWJzcGFtIHRlYW0gYXQgR29vZ2xlLiAg" + "VGhhdCBtZWFucyB0aGF0IGlmIHlvdSB0eXBlIHlvdXIgbmFtZSBpbnRvIEdv" + "b2dsZSBhbmQgZ2V0IHBvcm4gYmFjaywgaXQncyBteSBmYXVsdC4gVW5sZXNz" + "IHlvdSdyZSBhIHBvcm4gc3RhciwgaW4gd2hpY2ggY2FzZSBwb3JuIGlzIGEg" + "Y29tcGxldGVseSByZWFzb25hYmxlIHJlc3BvbnNlLiAtIE1hdHQgQ3V0dHMs" + "IEdvb2dsZSBQbHVzCg"}, + + {"It will still be a long time before machines approach human " + "intelligence. " + "But luckily, machines don't actually have to be intelligent; " + "they just have to fake it. Access to a wealth of information, " + "combined with a rudimentary decision-making capacity, " + "can often be almost as useful. Of course, the results are better yet " + "when coupled with intelligence. A reference librarian with access to " + "a good search engine is a formidable tool." + " - Craig Silverstein, Siemens Pictures of the Future, Spring 2004" + "\n", + + "SXQgd2lsbCBzdGlsbCBiZSBhIGxvbmcgdGltZSBiZWZvcmUgbWFjaGluZXMg" + "YXBwcm9hY2ggaHVtYW4gaW50ZWxsaWdlbmNlLiBCdXQgbHVja2lseSwgbWFj" + "aGluZXMgZG9uJ3QgYWN0dWFsbHkgaGF2ZSB0byBiZSBpbnRlbGxpZ2VudDsg" + "dGhleSBqdXN0IGhhdmUgdG8gZmFrZSBpdC4gQWNjZXNzIHRvIGEgd2VhbHRo" + "IG9mIGluZm9ybWF0aW9uLCBjb21iaW5lZCB3aXRoIGEgcnVkaW1lbnRhcnkg" + "ZGVjaXNpb24tbWFraW5nIGNhcGFjaXR5LCBjYW4gb2Z0ZW4gYmUgYWxtb3N0" + "IGFzIHVzZWZ1bC4gT2YgY291cnNlLCB0aGUgcmVzdWx0cyBhcmUgYmV0dGVy" + "IHlldCB3aGVuIGNvdXBsZWQgd2l0aCBpbnRlbGxpZ2VuY2UuIEEgcmVmZXJl" + "bmNlIGxpYnJhcmlhbiB3aXRoIGFjY2VzcyB0byBhIGdvb2Qgc2VhcmNoIGVu" + "Z2luZSBpcyBhIGZvcm1pZGFibGUgdG9vbC4gLSBDcmFpZyBTaWx2ZXJzdGVp" + "biwgU2llbWVucyBQaWN0dXJlcyBvZiB0aGUgRnV0dXJlLCBTcHJpbmcgMjAw" + "NAo"}, + + // Degenerate edge case + {"", ""}, }; TEST(Base64, EscapeAndUnescape) { @@ -469,10 +473,9 @@ TEST(Base64, EscapeAndUnescape) { // If we encode it into a buffer of exactly the right length... memset(encode_buffer, 0, sizeof(encode_buffer)); - encode_length = Base64Escape(unsigned_plaintext, - base64_tests[i].plain_length, - encode_buffer, - cipher_length); + encode_length = + Base64Escape(unsigned_plaintext, base64_tests[i].plain_length, + encode_buffer, cipher_length); // Is it still of the expected length? EXPECT_EQ(encode_length, cipher_length); @@ -481,8 +484,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it back: decode_str.clear(); - EXPECT_TRUE(Base64Unescape( - StringPiece(encode_buffer, cipher_length), &decode_str)); + EXPECT_TRUE( + Base64Unescape(StringPiece(encode_buffer, cipher_length), &decode_str)); // Is it of the expected length? EXPECT_EQ(base64_tests[i].plain_length, decode_str.length()); @@ -498,8 +501,8 @@ TEST(Base64, EscapeAndUnescape) { EXPECT_EQ(encoded, std::string(encode_buffer, cipher_length)); std::string decoded("this junk should be ignored"); - EXPECT_TRUE(Base64Unescape( - StringPiece(encode_buffer, cipher_length), &decoded)); + EXPECT_TRUE( + Base64Unescape(StringPiece(encode_buffer, cipher_length), &decoded)); EXPECT_EQ(decoded.size(), base64_tests[i].plain_length); EXPECT_EQ_ARRAY(decoded.size(), decoded, base64_tests[i].plaintext, i); @@ -602,11 +605,9 @@ TEST(Base64, EscapeAndUnescape) { // If we encode it into a buffer of exactly the right length... memset(encode_buffer, 0, sizeof(encode_buffer)); - encode_length = WebSafeBase64Escape(unsigned_plaintext, - base64_tests[i].plain_length, - encode_buffer, - cipher_length, - true); + encode_length = + WebSafeBase64Escape(unsigned_plaintext, base64_tests[i].plain_length, + encode_buffer, cipher_length, true); // Is it still of the expected length? EXPECT_EQ(encode_length, cipher_length); @@ -623,10 +624,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it back: memset(decode_buffer, 0, sizeof(decode_buffer)); - decode_length = WebSafeBase64Unescape(encode_buffer, - cipher_length, - decode_buffer, - sizeof(decode_buffer)); + decode_length = WebSafeBase64Unescape(encode_buffer, cipher_length, + decode_buffer, sizeof(decode_buffer)); // Is it of the expected length? EXPECT_EQ(decode_length, base64_tests[i].plain_length); @@ -637,10 +636,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it into a buffer of exactly the right length... memset(decode_buffer, 0, sizeof(decode_buffer)); - decode_length = WebSafeBase64Unescape(encode_buffer, - cipher_length, - decode_buffer, - decode_length); + decode_length = WebSafeBase64Unescape(encode_buffer, cipher_length, + decode_buffer, decode_length); // Is it still of the expected length? EXPECT_EQ(decode_length, base64_tests[i].plain_length); @@ -656,10 +653,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it back: memset(decode_buffer, 0, sizeof(decode_buffer)); - decode_length = WebSafeBase64Unescape(encode_buffer, - cipher_length, - decode_buffer, - sizeof(decode_buffer)); + decode_length = WebSafeBase64Unescape(encode_buffer, cipher_length, + decode_buffer, sizeof(decode_buffer)); // Is it of the expected length? EXPECT_EQ(decode_length, base64_tests[i].plain_length); @@ -670,10 +665,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it into a buffer of exactly the right length... memset(decode_buffer, 0, sizeof(decode_buffer)); - decode_length = WebSafeBase64Unescape(encode_buffer, - cipher_length, - decode_buffer, - decode_length); + decode_length = WebSafeBase64Unescape(encode_buffer, cipher_length, + decode_buffer, decode_length); // Is it still of the expected length? EXPECT_EQ(decode_length, base64_tests[i].plain_length); @@ -684,8 +677,8 @@ TEST(Base64, EscapeAndUnescape) { // Let's try the string version of the decoder decoded = "this junk should be ignored"; - EXPECT_TRUE(WebSafeBase64Unescape( - StringPiece(encode_buffer, cipher_length), &decoded)); + EXPECT_TRUE(WebSafeBase64Unescape(StringPiece(encode_buffer, cipher_length), + &decoded)); EXPECT_EQ(decoded.size(), base64_tests[i].plain_length); EXPECT_EQ_ARRAY(decoded.size(), decoded, base64_tests[i].plaintext, i); @@ -718,11 +711,9 @@ TEST(Base64, EscapeAndUnescape) { // If we encode it into a buffer of exactly the right length... memset(encode_buffer, 0, sizeof(encode_buffer)); - encode_length = WebSafeBase64Escape(unsigned_plaintext, - base64_tests[i].plain_length, - encode_buffer, - cipher_length, - false); + encode_length = + WebSafeBase64Escape(unsigned_plaintext, base64_tests[i].plain_length, + encode_buffer, cipher_length, false); // Is it still of the expected length? EXPECT_EQ(encode_length, cipher_length); @@ -738,10 +729,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it back: memset(decode_buffer, 0, sizeof(decode_buffer)); - decode_length = WebSafeBase64Unescape(encode_buffer, - cipher_length, - decode_buffer, - sizeof(decode_buffer)); + decode_length = WebSafeBase64Unescape(encode_buffer, cipher_length, + decode_buffer, sizeof(decode_buffer)); // Is it of the expected length? EXPECT_EQ(decode_length, base64_tests[i].plain_length); @@ -752,10 +741,8 @@ TEST(Base64, EscapeAndUnescape) { // If we decode it into a buffer of exactly the right length... memset(decode_buffer, 0, sizeof(decode_buffer)); - decode_length = WebSafeBase64Unescape(encode_buffer, - cipher_length, - decode_buffer, - decode_length); + decode_length = WebSafeBase64Unescape(encode_buffer, cipher_length, + decode_buffer, decode_length); // Is it still of the expected length? EXPECT_EQ(decode_length, base64_tests[i].plain_length); @@ -767,8 +754,8 @@ TEST(Base64, EscapeAndUnescape) { // Let's try the string version of the decoder decoded = "this junk should be ignored"; - EXPECT_TRUE(WebSafeBase64Unescape( - StringPiece(encode_buffer, cipher_length), &decoded)); + EXPECT_TRUE(WebSafeBase64Unescape(StringPiece(encode_buffer, cipher_length), + &decoded)); EXPECT_EQ(decoded.size(), base64_tests[i].plain_length); EXPECT_EQ_ARRAY(decoded.size(), decoded, base64_tests[i].plaintext, i); @@ -782,7 +769,7 @@ TEST(Base64, EscapeAndUnescape) { reinterpret_cast(base64_strings[i].plaintext); int plain_length = strlen(base64_strings[i].plaintext); int cipher_length = strlen(base64_strings[i].ciphertext); - std::vector buffer(cipher_length+1); + std::vector buffer(cipher_length + 1); int encode_length = WebSafeBase64Escape(unsigned_plaintext, plain_length, &buffer[0], diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc index 13bf91c476f83..6c2a01c1183fb 100644 --- a/src/google/protobuf/text_format.cc +++ b/src/google/protobuf/text_format.cc @@ -348,6 +348,12 @@ class TextFormat::Parser::ParserImpl { } private: + static constexpr int32_t kint32max = std::numeric_limits::max(); + static constexpr uint32_t kuint32max = std::numeric_limits::max(); + static constexpr int64_t kint64min = std::numeric_limits::min(); + static constexpr int64_t kint64max = std::numeric_limits::max(); + static constexpr uint64_t kuint64max = std::numeric_limits::max(); + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserImpl); // Reports an error with the given message with information indicating diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h index 4831de6c4b264..32396632cea75 100644 --- a/src/google/protobuf/text_format.h +++ b/src/google/protobuf/text_format.h @@ -213,7 +213,7 @@ class PROTOBUF_EXPORT TextFormat { virtual ~Finder(); // Try to find an extension of *message by fully-qualified field - // name. Returns NULL if no extension is known for this name or number. + // name. Returns nullptr if no extension is known for this name or number. // The base implementation uses the extensions already known by the message. virtual const FieldDescriptor* FindExtension(Message* message, const std::string& name) const; @@ -224,7 +224,7 @@ class PROTOBUF_EXPORT TextFormat { const Descriptor* descriptor, int number) const; // Find the message type for an Any proto. - // Returns NULL if no message is known for this name. + // Returns nullptr if no message is known for this name. // The base implementation only accepts prefixes of type.googleprod.com/ or // type.googleapis.com/, and searches the DescriptorPool of the parent // message. @@ -564,18 +564,19 @@ class PROTOBUF_EXPORT TextFormat { // Like TextFormat::MergeFromString(). bool MergeFromString(ConstStringParam input, Message* output); - // Set where to report parse errors. If NULL (the default), errors will + // Set where to report parse errors. If nullptr (the default), errors will // be printed to stderr. void RecordErrorsTo(io::ErrorCollector* error_collector) { error_collector_ = error_collector; } - // Set how parser finds extensions. If NULL (the default), the + // Set how parser finds extensions. If nullptr (the default), the // parser will use the standard Reflection object associated with // the message being parsed. void SetFinder(const Finder* finder) { finder_ = finder; } - // Sets where location information about the parse will be written. If NULL + // Sets where location information about the parse will be written. If + // nullptr // (the default), then no location will be written. void WriteLocationsTo(ParseInfoTree* tree) { parse_info_tree_ = tree; } diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc index f8848c41b42b7..3c44be0389810 100644 --- a/src/google/protobuf/text_format_unittest.cc +++ b/src/google/protobuf/text_format_unittest.cc @@ -509,7 +509,7 @@ TEST_F(TextFormatTest, FieldSpecificCustomPrinterRegisterSameFieldTwice) { TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) { protobuf_unittest::TestAllTypes message; TextFormat::Printer printer; - // NULL printer. + // nullptr printer. EXPECT_FALSE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), static_cast(nullptr))); @@ -518,7 +518,7 @@ TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) { static_cast(nullptr))); // Because registration fails, the ownership of this printer is never taken. TextFormat::FieldValuePrinter my_field_printer; - // NULL field + // nullptr field EXPECT_FALSE(printer.RegisterFieldValuePrinter(nullptr, &my_field_printer)); } @@ -1086,7 +1086,7 @@ TEST_F(TextFormatTest, PrintExotic) { // seemed to trigger an odd case on MinGW/GCC 3.4.5 where GCC's parsing of // the value differed from strtod()'s parsing. That is to say, the // following assertion fails on MinGW: - // assert(1.23e22 == strtod("1.23e22", NULL)); + // assert(1.23e22 == strtod("1.23e22", nullptr)); // As a result, SimpleDtoa() would print the value as // "1.2300000000000001e+22" to make sure strtod() produce the exact same // result. Our goal is to test runtime parsing, not compile-time parsing, @@ -1504,11 +1504,11 @@ TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 12, 2, 12, 8); - // Verify a NULL tree for an unknown nested field. + // Verify a nullptr tree for an unknown nested field. TextFormat::ParseInfoTree* unknown_nested_tree = tree.GetTreeForNested(nested_field, 2); - EXPECT_EQ(NULL, unknown_nested_tree); + EXPECT_EQ(nullptr, unknown_nested_tree); } TEST_F(TextFormatParserTest, ParseFieldValueFromString) { diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc index a7ab3b9b237cd..ed0a6eb58af20 100644 --- a/src/google/protobuf/timestamp.pb.cc +++ b/src/google/protobuf/timestamp.pb.cc @@ -100,7 +100,7 @@ Timestamp::Timestamp(const Timestamp& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Timestamp) } -void Timestamp::SharedCtor() { +inline void Timestamp::SharedCtor() { ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&seconds_) - reinterpret_cast(this)), 0, static_cast(reinterpret_cast(&nanos_) - diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h index cb733a4cfce32..f0a05ef23d3f1 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h @@ -120,7 +120,12 @@ class PROTOBUF_EXPORT Timestamp final : } inline void Swap(Timestamp* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc index 7e8e795bd87bb..8ef4ba115d41c 100644 --- a/src/google/protobuf/type.pb.cc +++ b/src/google/protobuf/type.pb.cc @@ -385,7 +385,7 @@ Type::Type(const Type& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Type) } -void Type::SharedCtor() { +inline void Type::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&source_context_) - reinterpret_cast(this)), @@ -767,7 +767,7 @@ Field::Field(const Field& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Field) } -void Field::SharedCtor() { +inline void Field::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); json_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); @@ -1259,7 +1259,7 @@ Enum::Enum(const Enum& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Enum) } -void Enum::SharedCtor() { +inline void Enum::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast(this) + static_cast( reinterpret_cast(&source_context_) - reinterpret_cast(this)), @@ -1588,7 +1588,7 @@ EnumValue::EnumValue(const EnumValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValue) } -void EnumValue::SharedCtor() { +inline void EnumValue::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); number_ = 0; } @@ -1857,7 +1857,7 @@ Option::Option(const Option& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Option) } -void Option::SharedCtor() { +inline void Option::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); value_ = nullptr; } diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 8c63c27d9034f..9bfaffa14fb37 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h @@ -233,7 +233,12 @@ class PROTOBUF_EXPORT Type final : } inline void Swap(Type* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -478,7 +483,12 @@ class PROTOBUF_EXPORT Field final : } inline void Swap(Field* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -847,7 +857,12 @@ class PROTOBUF_EXPORT Enum final : } inline void Swap(Enum* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1066,7 +1081,12 @@ class PROTOBUF_EXPORT EnumValue final : } inline void Swap(EnumValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1245,7 +1265,12 @@ class PROTOBUF_EXPORT Option final : } inline void Swap(Option* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); diff --git a/src/google/protobuf/unknown_field_set_unittest.cc b/src/google/protobuf/unknown_field_set_unittest.cc index bc8db5f514f67..3a6968f4f91ea 100644 --- a/src/google/protobuf/unknown_field_set_unittest.cc +++ b/src/google/protobuf/unknown_field_set_unittest.cc @@ -72,13 +72,13 @@ class UnknownFieldSetTest : public testing::Test { const UnknownField* GetField(const std::string& name) { const FieldDescriptor* field = descriptor_->FindFieldByName(name); - if (field == NULL) return NULL; + if (field == nullptr) return nullptr; for (int i = 0; i < unknown_fields_->field_count(); i++) { if (unknown_fields_->field(i).number() == field->number()) { return &unknown_fields_->field(i); } } - return NULL; + return nullptr; } // Constructs a protocol buffer which contains fields with all the same @@ -145,7 +145,7 @@ TEST_F(UnknownFieldSetTest, AllFieldsPresent) { TEST_F(UnknownFieldSetTest, Varint) { const UnknownField* field = GetField("optional_int32"); - ASSERT_TRUE(field != NULL); + ASSERT_TRUE(field != nullptr); ASSERT_EQ(UnknownField::TYPE_VARINT, field->type()); EXPECT_EQ(all_fields_.optional_int32(), field->varint()); @@ -153,7 +153,7 @@ TEST_F(UnknownFieldSetTest, Varint) { TEST_F(UnknownFieldSetTest, Fixed32) { const UnknownField* field = GetField("optional_fixed32"); - ASSERT_TRUE(field != NULL); + ASSERT_TRUE(field != nullptr); ASSERT_EQ(UnknownField::TYPE_FIXED32, field->type()); EXPECT_EQ(all_fields_.optional_fixed32(), field->fixed32()); @@ -161,7 +161,7 @@ TEST_F(UnknownFieldSetTest, Fixed32) { TEST_F(UnknownFieldSetTest, Fixed64) { const UnknownField* field = GetField("optional_fixed64"); - ASSERT_TRUE(field != NULL); + ASSERT_TRUE(field != nullptr); ASSERT_EQ(UnknownField::TYPE_FIXED64, field->type()); EXPECT_EQ(all_fields_.optional_fixed64(), field->fixed64()); @@ -169,7 +169,7 @@ TEST_F(UnknownFieldSetTest, Fixed64) { TEST_F(UnknownFieldSetTest, LengthDelimited) { const UnknownField* field = GetField("optional_string"); - ASSERT_TRUE(field != NULL); + ASSERT_TRUE(field != nullptr); ASSERT_EQ(UnknownField::TYPE_LENGTH_DELIMITED, field->type()); EXPECT_EQ(all_fields_.optional_string(), field->length_delimited()); @@ -177,7 +177,7 @@ TEST_F(UnknownFieldSetTest, LengthDelimited) { TEST_F(UnknownFieldSetTest, Group) { const UnknownField* field = GetField("optionalgroup"); - ASSERT_TRUE(field != NULL); + ASSERT_TRUE(field != nullptr); ASSERT_EQ(UnknownField::TYPE_GROUP, field->type()); ASSERT_EQ(1, field->group().field_count()); @@ -185,7 +185,7 @@ TEST_F(UnknownFieldSetTest, Group) { const UnknownField& nested_field = field->group().field(0); const FieldDescriptor* nested_field_descriptor = unittest::TestAllTypes::OptionalGroup::descriptor()->FindFieldByName("a"); - ASSERT_TRUE(nested_field_descriptor != NULL); + ASSERT_TRUE(nested_field_descriptor != nullptr); EXPECT_EQ(nested_field_descriptor->number(), nested_field.number()); ASSERT_EQ(UnknownField::TYPE_VARINT, nested_field.type()); @@ -456,8 +456,8 @@ TEST_F(UnknownFieldSetTest, UnknownEnumValue) { TestAllTypes::descriptor()->FindFieldByName("optional_nested_enum"); const FieldDescriptor* repeated_field = TestAllTypes::descriptor()->FindFieldByName("repeated_nested_enum"); - ASSERT_TRUE(singular_field != NULL); - ASSERT_TRUE(repeated_field != NULL); + ASSERT_TRUE(singular_field != nullptr); + ASSERT_TRUE(repeated_field != nullptr); std::string data; diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc index 646f80706c748..25ff424ba6a0e 100644 --- a/src/google/protobuf/util/field_mask_util.cc +++ b/src/google/protobuf/util/field_mask_util.cc @@ -62,7 +62,7 @@ bool FieldMaskUtil::SnakeCaseToCamelCase(StringPiece input, std::string* output) { output->clear(); bool after_underscore = false; - for (const char& input_char : input) { + for (char input_char : input) { if (input_char >= 'A' && input_char <= 'Z') { // The field name must not contain uppercase letters. return false; diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc index c9c691a97085b..7f61cdafa7c77 100644 --- a/src/google/protobuf/util/internal/default_value_objectwriter.cc +++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc @@ -423,18 +423,14 @@ DataPiece DefaultValueObjectWriter::FindEnumDefault( return DataPiece(field.default_value(), true); } else { const std::string& enum_default_value_name = field.default_value(); - for (int enum_index = 0; - enum_index < enum_type->enumvalue_size(); - ++enum_index) { + for (int enum_index = 0; enum_index < enum_type->enumvalue_size(); + ++enum_index) { auto& enum_value = enum_type->enumvalue(enum_index); if (enum_value.name() == enum_default_value_name) return DataPiece(enum_value.number()); } - GOOGLE_LOG(WARNING) << "Could not find enum value '" - << enum_default_value_name - << "' with type '" - << field.type_url() - << "'"; + GOOGLE_LOG(WARNING) << "Could not find enum value '" << enum_default_value_name + << "' with type '" << field.type_url() << "'"; return DataPiece::NullData(); } } diff --git a/src/google/protobuf/util/internal/expecting_objectwriter.h b/src/google/protobuf/util/internal/expecting_objectwriter.h index 0f2eb1e547ff4..b40ef0c2ad3d0 100644 --- a/src/google/protobuf/util/internal/expecting_objectwriter.h +++ b/src/google/protobuf/util/internal/expecting_objectwriter.h @@ -93,7 +93,8 @@ class MockObjectWriter : public ObjectWriter { (override)); MOCK_METHOD(ObjectWriter*, RenderString, (StringPiece, StringPiece), (override)); - MOCK_METHOD(ObjectWriter*, RenderBytes, (StringPiece, StringPiece), (override)); + MOCK_METHOD(ObjectWriter*, RenderBytes, (StringPiece, StringPiece), + (override)); MOCK_METHOD(ObjectWriter*, RenderNull, (StringPiece), (override)); }; diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc index 4b94f68454afa..e68af898b88eb 100644 --- a/src/google/protobuf/wire_format.cc +++ b/src/google/protobuf/wire_format.cc @@ -92,19 +92,19 @@ bool WireFormat::SkipField(io::CodedInputStream* input, uint32_t tag, case WireFormatLite::WIRETYPE_VARINT: { uint64_t value; if (!input->ReadVarint64(&value)) return false; - if (unknown_fields != NULL) unknown_fields->AddVarint(number, value); + if (unknown_fields != nullptr) unknown_fields->AddVarint(number, value); return true; } case WireFormatLite::WIRETYPE_FIXED64: { uint64_t value; if (!input->ReadLittleEndian64(&value)) return false; - if (unknown_fields != NULL) unknown_fields->AddFixed64(number, value); + if (unknown_fields != nullptr) unknown_fields->AddFixed64(number, value); return true; } case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: { uint32_t length; if (!input->ReadVarint32(&length)) return false; - if (unknown_fields == NULL) { + if (unknown_fields == nullptr) { if (!input->Skip(length)) return false; } else { if (!input->ReadString(unknown_fields->AddLengthDelimited(number), @@ -116,8 +116,8 @@ bool WireFormat::SkipField(io::CodedInputStream* input, uint32_t tag, } case WireFormatLite::WIRETYPE_START_GROUP: { if (!input->IncrementRecursionDepth()) return false; - if (!SkipMessage(input, (unknown_fields == NULL) - ? NULL + if (!SkipMessage(input, (unknown_fields == nullptr) + ? nullptr : unknown_fields->AddGroup(number))) { return false; } @@ -136,7 +136,7 @@ bool WireFormat::SkipField(io::CodedInputStream* input, uint32_t tag, case WireFormatLite::WIRETYPE_FIXED32: { uint32_t value; if (!input->ReadLittleEndian32(&value)) return false; - if (unknown_fields != NULL) unknown_fields->AddFixed32(number, value); + if (unknown_fields != nullptr) unknown_fields->AddFixed32(number, value); return true; } default: { @@ -179,7 +179,7 @@ bool WireFormat::ReadPackedEnumPreserveUnknowns(io::CodedInputStream* input, input, &value)) { return false; } - if (is_valid == NULL || is_valid(value)) { + if (is_valid == nullptr || is_valid(value)) { values->Add(value); } else { unknown_fields->AddVarint(field_number, value); @@ -346,15 +346,15 @@ bool WireFormat::ParseAndMergePartial(io::CodedInputStream* input, return true; } - const FieldDescriptor* field = NULL; + const FieldDescriptor* field = nullptr; - if (descriptor != NULL) { + if (descriptor != nullptr) { int field_number = WireFormatLite::GetTagFieldNumber(tag); field = descriptor->FindFieldByNumber(field_number); // If that failed, check if the field is an extension. - if (field == NULL && descriptor->IsExtensionNumber(field_number)) { - if (input->GetExtensionPool() == NULL) { + if (field == nullptr && descriptor->IsExtensionNumber(field_number)) { + if (input->GetExtensionPool() == nullptr) { field = message_reflection->FindKnownExtensionByNumber(field_number); } else { field = input->GetExtensionPool()->FindExtensionByNumber( @@ -364,7 +364,7 @@ bool WireFormat::ParseAndMergePartial(io::CodedInputStream* input, // If that failed, but we're a MessageSet, and this is the tag for a // MessageSet item, then parse that. - if (field == NULL && descriptor->options().message_set_wire_format() && + if (field == nullptr && descriptor->options().message_set_wire_format() && tag == WireFormatLite::kMessageSetItemStartTag) { if (!ParseAndMergeMessageSetItem(input, message)) { return false; @@ -393,7 +393,7 @@ bool WireFormat::ParseAndMergeMessageSetField(uint32_t field_number, Message* message, io::CodedInputStream* input) { const Reflection* message_reflection = message->GetReflection(); - if (field == NULL) { + if (field == nullptr) { // We store unknown MessageSet extensions as groups. return SkipMessageSetField( input, field_number, message_reflection->MutableUnknownFields(message)); @@ -416,13 +416,13 @@ static bool StrictUtf8Check(const FieldDescriptor* field) { bool WireFormat::ParseAndMergeField( uint32_t tag, - const FieldDescriptor* field, // May be NULL for unknown + const FieldDescriptor* field, // May be nullptr for unknown Message* message, io::CodedInputStream* input) { const Reflection* message_reflection = message->GetReflection(); enum { UNKNOWN, NORMAL_FORMAT, PACKED_FORMAT } value_format; - if (field == NULL) { + if (field == nullptr) { value_format = UNKNOWN; } else if (WireFormatLite::GetTagWireType(tag) == WireTypeForFieldType(field->type())) { @@ -489,7 +489,7 @@ bool WireFormat::ParseAndMergeField( } else { const EnumValueDescriptor* enum_value = field->enum_type()->FindValueByNumber(value); - if (enum_value != NULL) { + if (enum_value != nullptr) { message_reflection->AddEnum(message, field, enum_value); } else { // The enum value is not one of the known values. Add it to the @@ -642,7 +642,7 @@ bool WireFormat::ParseAndMergeMessageSetItem(io::CodedInputStream* input, } bool SkipField(uint32_t tag, io::CodedInputStream* input) { - return WireFormat::SkipField(input, tag, NULL); + return WireFormat::SkipField(input, tag, nullptr); } const Reflection* message_reflection; @@ -992,9 +992,9 @@ const char* WireFormat::_InternalParseAndMergeField( } } if (field->is_repeated()) { - reflection->AddString(msg, field, value); + reflection->AddString(msg, field, std::move(value)); } else { - reflection->SetString(msg, field, value); + reflection->SetString(msg, field, std::move(value)); } return ptr; } diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h index 7ca217a11b4a5..3628be3f7168d 100644 --- a/src/google/protobuf/wire_format.h +++ b/src/google/protobuf/wire_format.h @@ -146,17 +146,17 @@ class PROTOBUF_EXPORT WireFormat { // Helpers for dealing with unknown fields // Skips a field value of the given WireType. The input should start - // positioned immediately after the tag. If unknown_fields is non-NULL, + // positioned immediately after the tag. If unknown_fields is non-nullptr, // the contents of the field will be added to it. static bool SkipField(io::CodedInputStream* input, uint32_t tag, UnknownFieldSet* unknown_fields); // Reads and ignores a message from the input. If unknown_fields is - // non-NULL, the contents will be added to it. + // non-nullptr, the contents will be added to it. static bool SkipMessage(io::CodedInputStream* input, UnknownFieldSet* unknown_fields); - // Read a packed enum field. If the is_valid function is not NULL, values + // Read a packed enum field. If the is_valid function is not nullptr, values // for which is_valid(value) returns false are appended to // unknown_fields_stream. static bool ReadPackedEnumPreserveUnknowns(io::CodedInputStream* input, @@ -225,24 +225,24 @@ class PROTOBUF_EXPORT WireFormat { // after the tag. static bool ParseAndMergeField( uint32_t tag, - const FieldDescriptor* field, // May be NULL for unknown + const FieldDescriptor* field, // May be nullptr for unknown Message* message, io::CodedInputStream* input); // Serialize a single field. static void SerializeFieldWithCachedSizes( - const FieldDescriptor* field, // Cannot be NULL + const FieldDescriptor* field, // Cannot be nullptr const Message& message, io::CodedOutputStream* output) { output->SetCur(InternalSerializeField(field, message, output->Cur(), output->EpsCopy())); } static uint8_t* InternalSerializeField( - const FieldDescriptor* field, // Cannot be NULL + const FieldDescriptor* field, // Cannot be nullptr const Message& message, uint8_t* target, io::EpsCopyOutputStream* stream); // Compute size of a single field. If the field is a message type, this // will call ByteSize() for the embedded message, insuring that it caches // its size. - static size_t FieldByteSize(const FieldDescriptor* field, // Cannot be NULL + static size_t FieldByteSize(const FieldDescriptor* field, // Can't be nullptr const Message& message); // Parse/serialize a MessageSet::Item group. Used with messages that use @@ -266,7 +266,7 @@ class PROTOBUF_EXPORT WireFormat { // length, but for other length-delimited types, the size of the length is // included. static size_t FieldDataOnlyByteSize( - const FieldDescriptor* field, // Cannot be NULL + const FieldDescriptor* field, // Cannot be nullptr const Message& message); enum Operation { @@ -357,7 +357,7 @@ inline void WireFormat::VerifyUTF8String(const char* data, int size, WireFormat::Operation op) { #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED WireFormatLite::VerifyUtf8String( - data, size, static_cast(op), NULL); + data, size, static_cast(op), nullptr); #else // Avoid the compiler warning about unused variables. (void)data; diff --git a/src/google/protobuf/wire_format_lite.cc b/src/google/protobuf/wire_format_lite.cc index f61f4e5bf5778..04251d39438e5 100644 --- a/src/google/protobuf/wire_format_lite.cc +++ b/src/google/protobuf/wire_format_lite.cc @@ -34,6 +34,7 @@ #include +#include #include #include #include @@ -303,7 +304,7 @@ bool WireFormatLite::ReadPackedEnumPreserveUnknowns( if (!ReadPrimitive(input, &value)) { return false; } - if (is_valid == NULL || is_valid(value)) { + if (is_valid == nullptr || is_valid(value)) { values->Add(value); } else { uint32_t tag = WireFormatLite::MakeTag(field_number, @@ -475,11 +476,13 @@ void WireFormatLite::WriteEnum(int field_number, int value, WriteEnumNoTag(value, output); } +constexpr size_t kInt32MaxSize = std::numeric_limits::max(); + void WireFormatLite::WriteString(int field_number, const std::string& value, io::CodedOutputStream* output) { // String is for UTF-8 text only WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - GOOGLE_CHECK_LE(value.size(), static_cast(kint32max)); + GOOGLE_CHECK_LE(value.size(), kInt32MaxSize); output->WriteVarint32(value.size()); output->WriteString(value); } @@ -488,14 +491,14 @@ void WireFormatLite::WriteStringMaybeAliased(int field_number, io::CodedOutputStream* output) { // String is for UTF-8 text only WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - GOOGLE_CHECK_LE(value.size(), static_cast(kint32max)); + GOOGLE_CHECK_LE(value.size(), kInt32MaxSize); output->WriteVarint32(value.size()); output->WriteRawMaybeAliased(value.data(), value.size()); } void WireFormatLite::WriteBytes(int field_number, const std::string& value, io::CodedOutputStream* output) { WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - GOOGLE_CHECK_LE(value.size(), static_cast(kint32max)); + GOOGLE_CHECK_LE(value.size(), kInt32MaxSize); output->WriteVarint32(value.size()); output->WriteString(value); } @@ -503,7 +506,7 @@ void WireFormatLite::WriteBytesMaybeAliased(int field_number, const std::string& value, io::CodedOutputStream* output) { WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - GOOGLE_CHECK_LE(value.size(), static_cast(kint32max)); + GOOGLE_CHECK_LE(value.size(), kInt32MaxSize); output->WriteVarint32(value.size()); output->WriteRawMaybeAliased(value.data(), value.size()); } @@ -583,7 +586,7 @@ void PrintUTF8ErrorLog(const char* field_name, const char* operation_str, bool WireFormatLite::VerifyUtf8String(const char* data, int size, Operation op, const char* field_name) { if (!IsStructurallyValidUTF8(data, size)) { - const char* operation_str = NULL; + const char* operation_str = nullptr; switch (op) { case PARSE: operation_str = "parsing"; diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h index 83668e9c029df..b04d17b3ced83 100644 --- a/src/google/protobuf/wire_format_lite.h +++ b/src/google/protobuf/wire_format_lite.h @@ -66,6 +66,7 @@ // #pragma pop_macro("TYPE_BOOL") #undef TYPE_BOOL + #include namespace google { @@ -293,14 +294,15 @@ class PROTOBUF_EXPORT WireFormatLite { static bool ReadPackedPrimitiveNoInline(io::CodedInputStream* input, RepeatedField* value); - // Read a packed enum field. If the is_valid function is not NULL, values for - // which is_valid(value) returns false are silently dropped. + // Read a packed enum field. If the is_valid function is not nullptr, values + // for which is_valid(value) returns false are silently dropped. static bool ReadPackedEnumNoInline(io::CodedInputStream* input, bool (*is_valid)(int), RepeatedField* values); - // Read a packed enum field. If the is_valid function is not NULL, values for - // which is_valid(value) returns false are appended to unknown_fields_stream. + // Read a packed enum field. If the is_valid function is not nullptr, values + // for which is_valid(value) returns false are appended to + // unknown_fields_stream. static bool ReadPackedEnumPreserveUnknowns( io::CodedInputStream* input, int field_number, bool (*is_valid)(int), io::CodedOutputStream* unknown_fields_stream, RepeatedField* values); @@ -1105,7 +1107,7 @@ inline bool WireFormatLite::ReadRepeatedFixedSizePrimitive( int num_read = 0; while (num_read < elements_available && (buffer = io::CodedInputStream::ExpectTagFromArray(buffer, tag)) != - NULL) { + nullptr) { buffer = ReadPrimitiveFromArray(buffer, &value); values->AddAlreadyReserved(value); ++num_read; diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc index d1322e96ab351..d98f54a331f2e 100644 --- a/src/google/protobuf/wrappers.pb.cc +++ b/src/google/protobuf/wrappers.pb.cc @@ -270,7 +270,7 @@ DoubleValue::DoubleValue(const DoubleValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.DoubleValue) } -void DoubleValue::SharedCtor() { +inline void DoubleValue::SharedCtor() { value_ = 0; } @@ -448,7 +448,7 @@ FloatValue::FloatValue(const FloatValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.FloatValue) } -void FloatValue::SharedCtor() { +inline void FloatValue::SharedCtor() { value_ = 0; } @@ -626,7 +626,7 @@ Int64Value::Int64Value(const Int64Value& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Int64Value) } -void Int64Value::SharedCtor() { +inline void Int64Value::SharedCtor() { value_ = int64_t{0}; } @@ -804,7 +804,7 @@ UInt64Value::UInt64Value(const UInt64Value& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.UInt64Value) } -void UInt64Value::SharedCtor() { +inline void UInt64Value::SharedCtor() { value_ = uint64_t{0u}; } @@ -982,7 +982,7 @@ Int32Value::Int32Value(const Int32Value& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.Int32Value) } -void Int32Value::SharedCtor() { +inline void Int32Value::SharedCtor() { value_ = 0; } @@ -1160,7 +1160,7 @@ UInt32Value::UInt32Value(const UInt32Value& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.UInt32Value) } -void UInt32Value::SharedCtor() { +inline void UInt32Value::SharedCtor() { value_ = 0u; } @@ -1338,7 +1338,7 @@ BoolValue::BoolValue(const BoolValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.BoolValue) } -void BoolValue::SharedCtor() { +inline void BoolValue::SharedCtor() { value_ = false; } @@ -1520,7 +1520,7 @@ StringValue::StringValue(const StringValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.StringValue) } -void StringValue::SharedCtor() { +inline void StringValue::SharedCtor() { value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } @@ -1717,7 +1717,7 @@ BytesValue::BytesValue(const BytesValue& from) // @@protoc_insertion_point(copy_constructor:google.protobuf.BytesValue) } -void BytesValue::SharedCtor() { +inline void BytesValue::SharedCtor() { value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h index f97db946b7f12..729d0d048260a 100644 --- a/src/google/protobuf/wrappers.pb.h +++ b/src/google/protobuf/wrappers.pb.h @@ -152,7 +152,12 @@ class PROTOBUF_EXPORT DoubleValue final : } inline void Swap(DoubleValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -295,7 +300,12 @@ class PROTOBUF_EXPORT FloatValue final : } inline void Swap(FloatValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -438,7 +448,12 @@ class PROTOBUF_EXPORT Int64Value final : } inline void Swap(Int64Value* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -581,7 +596,12 @@ class PROTOBUF_EXPORT UInt64Value final : } inline void Swap(UInt64Value* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -724,7 +744,12 @@ class PROTOBUF_EXPORT Int32Value final : } inline void Swap(Int32Value* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -867,7 +892,12 @@ class PROTOBUF_EXPORT UInt32Value final : } inline void Swap(UInt32Value* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1010,7 +1040,12 @@ class PROTOBUF_EXPORT BoolValue final : } inline void Swap(BoolValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1153,7 +1188,12 @@ class PROTOBUF_EXPORT StringValue final : } inline void Swap(StringValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); @@ -1301,7 +1341,12 @@ class PROTOBUF_EXPORT BytesValue final : } inline void Swap(BytesValue* other) { if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);