Browse Source

Merge pull request #8437 from haberman/sync-stage

Integrate from Piper for C++, Java, and Python
Joshua Haberman 4 years ago
parent
commit
e9360dfa53

+ 1 - 0
CHANGES.txt

@@ -1,6 +1,7 @@
 Unreleased Changes (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
 
   C++
+  * The ::pb namespace is no longer exposed due to conflicts.
   * Allow MessageDifferencer::TreatAsSet() (and friends) to override previous
     calls instead of crashing.
   * Reduce the size of generated proto headers for protos with `string` or

+ 19 - 3
java/core/src/main/java/com/google/protobuf/CodedInputStream.java

@@ -3523,9 +3523,25 @@ public abstract class CodedInputStream {
           return ByteString.wrap(bytes);
         }
       } else if (size > 0 && size <= remaining()) {
-        byte[] temp = new byte[size];
-        readRawBytesTo(temp, 0, size);
-        return ByteString.wrap(temp);
+        if (immutable && enableAliasing) {
+          ArrayList<ByteString> byteStrings = new ArrayList<>();
+          int l = size;
+          while (l > 0) {
+            if (currentRemaining() == 0) {
+              getNextByteBuffer();
+            }
+            int bytesToCopy = Math.min(l, (int) currentRemaining());
+            int idx = (int) (currentByteBufferPos - currentAddress);
+            byteStrings.add(ByteString.wrap(slice(idx, idx + bytesToCopy)));
+            l -= bytesToCopy;
+            currentByteBufferPos += bytesToCopy;
+          }
+          return ByteString.copyFrom(byteStrings);
+        } else {
+          byte[] temp = new byte[size];
+          readRawBytesTo(temp, 0, size);
+          return ByteString.wrap(temp);
+        }
       }
 
       if (size == 0) {

+ 41 - 8
java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java

@@ -1142,6 +1142,39 @@ public class CodedInputStreamTest extends TestCase {
     }
   }
 
+  public void testIterableByteBufferInputStreamReadBytesWithAlias() throws Exception {
+    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
+    CodedOutputStream output = CodedOutputStream.newInstance(byteArrayStream);
+    // A bytes field large enough that won't fit into the default block buffer.
+    // 4.5 is to test the case where the total size of input is not aligned with DEFAULT_BLOCK_SIZE.
+    final int bytesLength = DEFAULT_BLOCK_SIZE * 4 + (DEFAULT_BLOCK_SIZE / 2);
+    byte[] bytes = new byte[bytesLength];
+    for (int i = 0; i < bytesLength; i++) {
+      bytes[i] = (byte) (i % 256);
+    }
+    output.writeByteArrayNoTag(bytes);
+    output.flush();
+
+    // Input data is split into multiple ByteBuffers so that a single bytes spans across them.
+    // CodedInputStream with aliasing will decode it as a consequent rope by wrapping ByteBuffers.
+    byte[] data = byteArrayStream.toByteArray();
+    ArrayList<ByteBuffer> input = new ArrayList<>();
+    for (int i = 0; i < data.length; i += DEFAULT_BLOCK_SIZE) {
+      int rl = Math.min(DEFAULT_BLOCK_SIZE, data.length - i);
+      ByteBuffer rb = ByteBuffer.allocateDirect(rl);
+      rb.put(data, i, rl);
+      rb.flip();
+      input.add(rb);
+    }
+    final CodedInputStream inputStream = CodedInputStream.newInstance(input, true);
+    inputStream.enableAliasing(true);
+
+    ByteString result = inputStream.readBytes();
+    for (int i = 0; i < bytesLength; i++) {
+      assertEquals((byte) (i % 256), result.byteAt(i));
+    }
+  }
+
   public void testCompatibleTypes() throws Exception {
     long data = 0x100000000L;
     Int64Message message = Int64Message.newBuilder().setData(data).build();
@@ -1196,7 +1229,7 @@ public class CodedInputStreamTest extends TestCase {
       // Expected
     }
   }
-  
+
   public void testMaliciousInputStream() throws Exception {
     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
@@ -1210,17 +1243,17 @@ public class CodedInputStreamTest extends TestCase {
         return super.read(b, off, len);
       }
     };
-    
+
     // test ByteString
-    
+
     CodedInputStream codedInputStream = CodedInputStream.newInstance(inputStream, 1);
     ByteString byteString = codedInputStream.readBytes();
     assertEquals(0x0, byteString.byteAt(0));
     maliciousCapture.get(1)[0] = 0x9;
     assertEquals(0x0, byteString.byteAt(0));
-    
+
     // test ByteBuffer
-    
+
     inputStream.reset();
     maliciousCapture.clear();
     codedInputStream = CodedInputStream.newInstance(inputStream, 1);
@@ -1228,10 +1261,10 @@ public class CodedInputStreamTest extends TestCase {
     assertEquals(0x0, byteBuffer.get(0));
     maliciousCapture.get(1)[0] = 0x9;
     assertEquals(0x0, byteBuffer.get(0));
-    
+
 
     // test byte[]
-    
+
     inputStream.reset();
     maliciousCapture.clear();
     codedInputStream = CodedInputStream.newInstance(inputStream, 1);
@@ -1241,7 +1274,7 @@ public class CodedInputStreamTest extends TestCase {
     assertEquals(0x9, byteArray[0]); // MODIFICATION! Should we fix?
 
     // test rawBytes
-    
+
     inputStream.reset();
     maliciousCapture.clear();
     codedInputStream = CodedInputStream.newInstance(inputStream, 1);

+ 7 - 6
java/util/src/main/java/com/google/protobuf/util/Durations.java

@@ -149,6 +149,12 @@ public final class Durations {
     return (duration.getSeconds() == 0) ? duration.getNanos() < 0 : duration.getSeconds() < 0;
   }
 
+  /** Returns whether the given {@link Duration} is positive or not. */
+  public static boolean isPositive(Duration duration) {
+    checkValid(duration);
+    return !isNegative(duration) && !duration.equals(ZERO);
+  }
+
   /**
    * Ensures that the given {@link Duration} is not negative.
    *
@@ -157,7 +163,6 @@ public final class Durations {
    */
   @CanIgnoreReturnValue
   public static Duration checkNotNegative(Duration duration) {
-    checkValid(duration);
     checkArgument(!isNegative(duration), "duration (%s) must not be negative", toString(duration));
     return duration;
   }
@@ -170,11 +175,7 @@ public final class Durations {
    */
   @CanIgnoreReturnValue
   public static Duration checkPositive(Duration duration) {
-    checkValid(duration);
-    checkArgument(
-        !isNegative(duration) && !duration.equals(ZERO),
-        "duration (%s) must be positive",
-        toString(duration));
+    checkArgument(isPositive(duration), "duration (%s) must be positive", toString(duration));
     return duration;
   }
 

+ 2 - 1
python/google/protobuf/pyext/descriptor.cc

@@ -250,8 +250,9 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
                  message_type->full_name().c_str());
     return NULL;
   }
+  ScopedPyObjectPtr args(PyTuple_New(0));
   ScopedPyObjectPtr value(
-      PyObject_Call(message_class->AsPyObject(), NULL, NULL));
+      PyObject_Call(message_class->AsPyObject(), args.get(), NULL));
   Py_DECREF(message_class);
   if (value == NULL) {
     return NULL;

+ 2 - 1
python/google/protobuf/pyext/descriptor_pool.cc

@@ -178,7 +178,8 @@ static PyObject* New(PyTypeObject* type,
                      PyObject* args, PyObject* kwargs) {
   static const char* kwlist[] = {"descriptor_db", 0};
   PyObject* py_database = NULL;
-  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", const_cast<char**>(kwlist), &py_database)) {
+  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
+                                   const_cast<char**>(kwlist), &py_database)) {
     return NULL;
   }
   DescriptorDatabase* database = NULL;

+ 4 - 2
python/google/protobuf/pyext/map_container.cc

@@ -466,7 +466,8 @@ static PyObject* ScalarMapGet(PyObject* self, PyObject* args,
   static const char* kwlist[] = {"key", "default", nullptr};
   PyObject* key;
   PyObject* default_value = NULL;
-  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", const_cast<char**>(kwlist), &key,
+  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O",
+                                   const_cast<char**>(kwlist), &key,
                                    &default_value)) {
     return NULL;
   }
@@ -761,7 +762,8 @@ PyObject* MessageMapGet(PyObject* self, PyObject* args, PyObject* kwargs) {
   static const char* kwlist[] = {"key", "default", nullptr};
   PyObject* key;
   PyObject* default_value = NULL;
-  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", const_cast<char**>(kwlist), &key,
+  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O",
+                                   const_cast<char**>(kwlist), &key,
                                    &default_value)) {
     return NULL;
   }

+ 7 - 8
python/google/protobuf/pyext/message.cc

@@ -197,15 +197,14 @@ static int AddDescriptors(PyObject* cls, const Descriptor* descriptor) {
 }
 
 static PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
-  static const char *kwlist[] = {"name", "bases", "dict", 0};
+  static const char* kwlist[] = {"name", "bases", "dict", 0};
   PyObject *bases, *dict;
   const char* name;
 
   // Check arguments: (name, bases, dict)
-  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO!O!:type", const_cast<char**>(kwlist),
-                                   &name,
-                                   &PyTuple_Type, &bases,
-                                   &PyDict_Type, &dict)) {
+  if (!PyArg_ParseTupleAndKeywords(
+          args, kwargs, "sO!O!:type", const_cast<char**>(kwlist), &name,
+          &PyTuple_Type, &bases, &PyDict_Type, &dict)) {
     return NULL;
   }
 
@@ -1680,10 +1679,10 @@ static PyObject* InternalSerializeToString(
     CMessage* self, PyObject* args, PyObject* kwargs,
     bool require_initialized) {
   // Parse the "deterministic" kwarg; defaults to False.
-  static const char* kwlist[] = { "deterministic", 0 };
+  static const char* kwlist[] = {"deterministic", 0};
   PyObject* deterministic_obj = Py_None;
-  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", const_cast<char**>(kwlist),
-                                   &deterministic_obj)) {
+  if (!PyArg_ParseTupleAndKeywords(
+          args, kwargs, "|O", const_cast<char**>(kwlist), &deterministic_obj)) {
     return NULL;
   }
   // Preemptively convert to a bool first, so we don't need to back out of

+ 2 - 1
python/google/protobuf/pyext/message_factory.cc

@@ -79,7 +79,8 @@ PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool)
 PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
   static const char* kwlist[] = {"pool", 0};
   PyObject* pool = NULL;
-  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", const_cast<char**>(kwlist), &pool)) {
+  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
+                                   const_cast<char**>(kwlist), &pool)) {
     return NULL;
   }
   ScopedPyObjectPtr owned_pool;

+ 5 - 3
src/google/protobuf/compiler/command_line_interface.cc

@@ -290,7 +290,10 @@ class CommandLineInterface::ErrorPrinter
       public DescriptorPool::ErrorCollector {
  public:
   ErrorPrinter(ErrorFormat format, DiskSourceTree* tree = NULL)
-      : format_(format), tree_(tree), found_errors_(false), found_warnings_(false) {}
+      : format_(format),
+        tree_(tree),
+        found_errors_(false),
+        found_warnings_(false) {}
   ~ErrorPrinter() {}
 
   // implements MultiFileErrorCollector ------------------------------
@@ -1639,8 +1642,7 @@ bool CommandLineInterface::ParseArgument(const char* arg, std::string* name,
       *name == "--version" || *name == "--decode_raw" ||
       *name == "--print_free_field_numbers" ||
       *name == "--experimental_allow_proto3_optional" ||
-      *name == "--deterministic_output" ||
-      *name == "--fatal_warnings") {
+      *name == "--deterministic_output" || *name == "--fatal_warnings") {
     // HACK:  These are the only flags that don't take a value.
     //   They probably should not be hard-coded like this but for now it's
     //   not worth doing better.

+ 8 - 11
src/google/protobuf/compiler/command_line_interface_unittest.cc

@@ -525,8 +525,7 @@ void CommandLineInterfaceTest::ExpectCapturedStdoutSubstringWithZeroReturnCode(
 void CommandLineInterfaceTest::ExpectCapturedStderrSubstringWithZeroReturnCode(
     const std::string& expected_substring) {
   EXPECT_EQ(0, return_code_);
-  EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring,
-                      error_text_);
+  EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_);
 }
 
 void CommandLineInterfaceTest::ExpectFileContent(const std::string& filename,
@@ -2333,20 +2332,18 @@ TEST_F(CommandLineInterfaceTest, Warnings) {
   // Test --fatal_warnings.
 
   CreateTempFile("foo.proto",
-    "syntax = \"proto2\";\n"
-    "import \"bar.proto\";\n");
-  CreateTempFile("bar.proto",
-    "syntax = \"proto2\";\n");
+                 "syntax = \"proto2\";\n"
+                 "import \"bar.proto\";\n");
+  CreateTempFile("bar.proto", "syntax = \"proto2\";\n");
 
   Run("protocol_compiler --test_out=$tmpdir "
-    "--proto_path=$tmpdir foo.proto");
+      "--proto_path=$tmpdir foo.proto");
   ExpectCapturedStderrSubstringWithZeroReturnCode(
-    "foo.proto:2:1: warning: Import bar.proto is unused.");
+      "foo.proto:2:1: warning: Import bar.proto is unused.");
 
   Run("protocol_compiler --test_out=$tmpdir --fatal_warnings "
-    "--proto_path=$tmpdir foo.proto");
-  ExpectErrorSubstring(
-    "foo.proto:2:1: warning: Import bar.proto is unused.");
+      "--proto_path=$tmpdir foo.proto");
+  ExpectErrorSubstring("foo.proto:2:1: warning: Import bar.proto is unused.");
 }
 
 // -------------------------------------------------------------------

+ 0 - 7
src/google/protobuf/port.h

@@ -37,11 +37,4 @@
 #define GOOGLE_PROTOBUF_PORT_H__
 
 
-#include <google/protobuf/stubs/port.h>
-
-// Protobuf intends to move into the pb:: namespace.
-namespace protobuf_future_namespace_placeholder {}
-namespace pb = ::protobuf_future_namespace_placeholder;
-
-
 #endif  // GOOGLE_PROTOBUF_PORT_H__

+ 3 - 7
src/google/protobuf/stubs/status.cc

@@ -85,8 +85,7 @@ inline std::string StatusCodeToString(StatusCode code) {
 
 }  // namespace
 
-Status::Status() : error_code_(StatusCode::kOk) {
-}
+Status::Status() : error_code_(StatusCode::kOk) {}
 
 Status::Status(StatusCode error_code, StringPiece error_message)
     : error_code_(error_code) {
@@ -117,15 +116,12 @@ std::string Status::ToString() const {
     if (error_message_.empty()) {
       return StatusCodeToString(error_code_);
     } else {
-      return StatusCodeToString(error_code_) + ":" +
-          error_message_;
+      return StatusCodeToString(error_code_) + ":" + error_message_;
     }
   }
 }
 
-Status OkStatus() {
-  return Status();
-}
+Status OkStatus() { return Status(); }
 
 std::ostream& operator<<(std::ostream& os, const Status& x) {
   os << x.ToString();

+ 3 - 7
src/google/protobuf/stubs/status.h

@@ -78,12 +78,8 @@ class PROTOBUF_EXPORT Status {
   ~Status() {}
 
   // Accessor
-  bool ok() const {
-    return error_code_ == StatusCode::kOk;
-  }
-  StatusCode code() const {
-    return error_code_;
-  }
+  bool ok() const { return error_code_ == StatusCode::kOk; }
+  StatusCode code() const { return error_code_; }
   StringPiece message() const {
     return error_message_;
   }
@@ -173,7 +169,6 @@ using ::google::protobuf::util::status_internal::IsUnavailable;
 using ::google::protobuf::util::status_internal::IsUnimplemented;
 using ::google::protobuf::util::status_internal::IsUnknown;
 
-using ::google::protobuf::util::status_internal::OkStatus;
 using ::google::protobuf::util::status_internal::AbortedError;
 using ::google::protobuf::util::status_internal::AlreadyExistsError;
 using ::google::protobuf::util::status_internal::CancelledError;
@@ -183,6 +178,7 @@ using ::google::protobuf::util::status_internal::FailedPreconditionError;
 using ::google::protobuf::util::status_internal::InternalError;
 using ::google::protobuf::util::status_internal::InvalidArgumentError;
 using ::google::protobuf::util::status_internal::NotFoundError;
+using ::google::protobuf::util::status_internal::OkStatus;
 using ::google::protobuf::util::status_internal::OutOfRangeError;
 using ::google::protobuf::util::status_internal::PermissionDeniedError;
 using ::google::protobuf::util::status_internal::ResourceExhaustedError;

+ 1 - 3
src/google/protobuf/stubs/status_test.cc

@@ -247,9 +247,7 @@ TEST(Status, AssignEmpty) {
   ASSERT_TRUE(a.ok());
 }
 
-TEST(Status, EqualsOK) {
-  ASSERT_EQ(util::OkStatus(), util::Status());
-}
+TEST(Status, EqualsOK) { ASSERT_EQ(util::OkStatus(), util::Status()); }
 
 TEST(Status, EqualsSame) {
   const util::Status a = util::CancelledError("message");

+ 2 - 4
src/google/protobuf/stubs/statusor.h

@@ -174,10 +174,8 @@ struct StatusOrHelper::Specialize<T*> {
   static inline bool IsValueNull(const T* t) { return t == nullptr; }
 };
 
-template<typename T>
-inline StatusOr<T>::StatusOr()
-    : status_(util::UnknownError("")) {
-}
+template <typename T>
+inline StatusOr<T>::StatusOr() : status_(util::UnknownError("")) {}
 
 template<typename T>
 inline StatusOr<T>::StatusOr(const Status& status) {

+ 2 - 2
src/google/protobuf/stubs/statusor_test.cc

@@ -110,7 +110,7 @@ TEST(StatusOr, TestCopyCtorStatusOKConverting) {
 }
 
 TEST(StatusOr, TestCopyCtorStatusNotOkConverting) {
-  StatusOr<int>    original(util::CancelledError(""));
+  StatusOr<int> original(util::CancelledError(""));
   StatusOr<double> copy(original);
   EXPECT_EQ(original.status(), copy.status());
 }
@@ -141,7 +141,7 @@ TEST(StatusOr, TestAssignmentStatusOKConverting) {
 }
 
 TEST(StatusOr, TestAssignmentStatusNotOkConverting) {
-  StatusOr<int>    source(util::CancelledError(""));
+  StatusOr<int> source(util::CancelledError(""));
   StatusOr<double> target;
   target = source;
   EXPECT_EQ(source.status(), target.status());

+ 4 - 4
src/google/protobuf/util/field_comparator.h

@@ -173,6 +173,10 @@ class PROTOBUF_EXPORT SimpleFieldComparator : public FieldComparator {
                               const Message& message1, const Message& message2,
                               const util::FieldContext* field_context);
 
+  // Returns FieldComparator::SAME if boolean_result is true and
+  // FieldComparator::DIFFERENT otherwise.
+  ComparisonResult ResultFromBoolean(bool boolean_result) const;
+
  private:
   // Defines the tolerance for floating point comparison (fraction and margin).
   struct Tolerance {
@@ -239,10 +243,6 @@ class PROTOBUF_EXPORT SimpleFieldComparator : public FieldComparator {
   template <typename T>
   bool CompareDoubleOrFloat(const FieldDescriptor& field, T value_1, T value_2);
 
-  // Returns FieldComparator::SAME if boolean_result is true and
-  // FieldComparator::DIFFERENT otherwise.
-  ComparisonResult ResultFromBoolean(bool boolean_result) const;
-
   FloatComparison float_comparison_;
 
   // If true, floats and doubles that are both NaN are considered to be

+ 8 - 7
src/google/protobuf/util/internal/datapiece.cc

@@ -57,11 +57,10 @@ util::StatusOr<To> ValidateNumberConversion(To after, From before) {
       MathUtil::Sign<From>(before) == MathUtil::Sign<To>(after)) {
     return after;
   } else {
-    return util::InvalidArgumentError(std::is_integral<From>::value
-                               ? ValueAsString(before)
-                               : std::is_same<From, double>::value
-                                     ? DoubleAsString(before)
-                                     : FloatAsString(before));
+    return util::InvalidArgumentError(
+        std::is_integral<From>::value       ? ValueAsString(before)
+        : std::is_same<From, double>::value ? DoubleAsString(before)
+                                            : FloatAsString(before));
   }
 }
 
@@ -260,7 +259,8 @@ util::StatusOr<std::string> DataPiece::ToBytes() const {
   if (type_ == TYPE_STRING) {
     std::string decoded;
     if (!DecodeBase64(str_, &decoded)) {
-      return util::InvalidArgumentError(ValueAsStringOrDefault("Invalid data in input."));
+      return util::InvalidArgumentError(
+          ValueAsStringOrDefault("Invalid data in input."));
     }
     return decoded;
   } else {
@@ -358,7 +358,8 @@ util::StatusOr<To> DataPiece::StringToNumber(bool (*func)(StringPiece,
   }
   To result;
   if (func(str_, &result)) return result;
-  return util::InvalidArgumentError(StrCat("\"", std::string(str_), "\""));
+  return util::InvalidArgumentError(
+      StrCat("\"", std::string(str_), "\""));
 }
 
 bool DataPiece::DecodeBase64(StringPiece src, std::string* dest) const {

+ 9 - 12
src/google/protobuf/util/internal/field_mask_utility.cc

@@ -134,10 +134,9 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
         }
         // Un-escaped '"' must be followed with a ']'.
         if (i >= length - 1 || paths[i + 1] != ']') {
-          return util::InvalidArgumentError(
-              StrCat(
-                  "Invalid FieldMask '", paths,
-                  "'. Map keys should be represented as [\"some_key\"]."));
+          return util::InvalidArgumentError(StrCat(
+              "Invalid FieldMask '", paths,
+              "'. Map keys should be represented as [\"some_key\"]."));
         }
         // The end of the map key ("\"]") has been found.
         in_map_key = false;
@@ -146,10 +145,9 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
         // Checks whether the key ends at the end of a path segment.
         if (i < length - 1 && paths[i + 1] != '.' && paths[i + 1] != ',' &&
             paths[i + 1] != ')' && paths[i + 1] != '(') {
-          return util::InvalidArgumentError(
-              StrCat(
-                  "Invalid FieldMask '", paths,
-                  "'. Map keys should be at the end of a path segment."));
+          return util::InvalidArgumentError(StrCat(
+              "Invalid FieldMask '", paths,
+              "'. Map keys should be at the end of a path segment."));
         }
         is_escaping = false;
         continue;
@@ -158,10 +156,9 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
       // We are not in a map key, look for the start of one.
       if (paths[i] == '[') {
         if (i >= length - 1 || paths[i + 1] != '\"') {
-          return util::InvalidArgumentError(
-              StrCat(
-                  "Invalid FieldMask '", paths,
-                  "'. Map keys should be represented as [\"some_key\"]."));
+          return util::InvalidArgumentError(StrCat(
+              "Invalid FieldMask '", paths,
+              "'. Map keys should be represented as [\"some_key\"]."));
         }
         // "[\"" starts a map key.
         in_map_key = true;

+ 6 - 5
src/google/protobuf/util/internal/json_stream_parser.cc

@@ -302,7 +302,8 @@ util::Status JsonStreamParser::RunParser() {
         break;
 
       default:
-        result = util::InternalError(StrCat("Unknown parse type: ", type));
+        result =
+            util::InternalError(StrCat("Unknown parse type: ", type));
         break;
     }
     if (!result.ok()) {
@@ -872,8 +873,9 @@ util::Status JsonStreamParser::ReportFailure(StringPiece message,
   StringPiece segment(begin, end - begin);
   std::string location(p_start - begin, ' ');
   location.push_back('^');
-  return util::InvalidArgumentError(
+  auto status = util::InvalidArgumentError(
       StrCat(message, "\n", segment, "\n", location));
+  return status;
 }
 
 util::Status JsonStreamParser::ReportUnknown(StringPiece message,
@@ -892,9 +894,8 @@ util::Status JsonStreamParser::ReportUnknown(StringPiece message,
 util::Status JsonStreamParser::IncrementRecursionDepth(
     StringPiece key) const {
   if (++recursion_depth_ > max_recursion_depth_) {
-    return util::InvalidArgumentError(
-        StrCat("Message too deep. Max recursion depth reached for key '",
-                     key, "'"));
+    return util::InvalidArgumentError(StrCat(
+        "Message too deep. Max recursion depth reached for key '", key, "'"));
   }
   return util::Status();
 }

+ 2 - 2
src/google/protobuf/util/internal/protostream_objectsource.cc

@@ -317,8 +317,8 @@ util::Status ProtoStreamObjectSource::RenderTimestamp(
   int64_t seconds = p.first;
   int32_t nanos = p.second;
   if (seconds > kTimestampMaxSeconds || seconds < kTimestampMinSeconds) {
-    return util::InternalError(
-        StrCat("Timestamp seconds exceeds limit for field: ", field_name));
+    return util::InternalError(StrCat(
+        "Timestamp seconds exceeds limit for field: ", field_name));
   }
 
   if (nanos < 0 || nanos >= kNanosPerSecond) {

+ 6 - 9
src/google/protobuf/util/internal/protostream_objectwriter.cc

@@ -1025,9 +1025,8 @@ Status ProtoStreamObjectWriter::RenderTimestamp(ProtoStreamObjectWriter* ow,
   if (data.type() == DataPiece::TYPE_NULL) return Status();
   if (data.type() != DataPiece::TYPE_STRING) {
     return util::InvalidArgumentError(
-        StrCat(
-            "Invalid data type for timestamp, value is ",
-            data.ValueAsStringOrDefault("")));
+        StrCat("Invalid data type for timestamp, value is ",
+                     data.ValueAsStringOrDefault("")));
   }
 
   StringPiece value(data.str());
@@ -1057,9 +1056,8 @@ Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
   if (data.type() == DataPiece::TYPE_NULL) return Status();
   if (data.type() != DataPiece::TYPE_STRING) {
     return util::InvalidArgumentError(
-        StrCat(
-            "Invalid data type for field mask, value is ",
-            data.ValueAsStringOrDefault("")));
+        StrCat("Invalid data type for field mask, value is ",
+                     data.ValueAsStringOrDefault("")));
   }
 
   // TODO(tsun): figure out how to do proto descriptor based snake case
@@ -1074,9 +1072,8 @@ Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
   if (data.type() == DataPiece::TYPE_NULL) return Status();
   if (data.type() != DataPiece::TYPE_STRING) {
     return util::InvalidArgumentError(
-        StrCat(
-            "Invalid data type for duration, value is ",
-            data.ValueAsStringOrDefault("")));
+        StrCat("Invalid data type for duration, value is ",
+                     data.ValueAsStringOrDefault("")));
   }
 
   StringPiece value(data.str());

+ 2 - 3
src/google/protobuf/util/json_util.cc

@@ -154,9 +154,8 @@ class StatusErrorListener : public converter::ErrorListener {
 
   void MissingField(const converter::LocationTrackerInterface& loc,
                     StringPiece missing_name) override {
-    status_ = util::InvalidArgumentError(
-        StrCat(
-            GetLocString(loc), ": missing field ", std::string(missing_name)));
+    status_ = util::InvalidArgumentError(StrCat(
+        GetLocString(loc), ": missing field ", std::string(missing_name)));
   }
 
  private:

+ 4 - 4
src/google/protobuf/util/type_resolver_util.cc

@@ -80,8 +80,8 @@ class DescriptorPoolTypeResolver : public TypeResolver {
 
     const Descriptor* descriptor = pool_->FindMessageTypeByName(type_name);
     if (descriptor == NULL) {
-      return util::NotFoundError(
-          "Invalid type URL, unknown type: " + type_name);
+      return util::NotFoundError("Invalid type URL, unknown type: " +
+                                 type_name);
     }
     ConvertDescriptor(descriptor, type);
     return util::Status();
@@ -97,8 +97,8 @@ class DescriptorPoolTypeResolver : public TypeResolver {
 
     const EnumDescriptor* descriptor = pool_->FindEnumTypeByName(type_name);
     if (descriptor == NULL) {
-      return util::InvalidArgumentError(
-          "Invalid type URL, unknown type: " + type_name);
+      return util::InvalidArgumentError("Invalid type URL, unknown type: " +
+                                        type_name);
     }
     ConvertEnumDescriptor(descriptor, enum_type);
     return util::Status();