• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 #ifndef GOOGLE_PROTOBUF_TEST_UTIL2_H__
9 #define GOOGLE_PROTOBUF_TEST_UTIL2_H__
10 
11 #include <string>
12 
13 #include <gtest/gtest.h>
14 #include "absl/strings/str_cat.h"
15 #include "absl/strings/string_view.h"
16 #include "absl/strings/strip.h"
17 #include "google/protobuf/io/zero_copy_stream.h"
18 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
19 #include "google/protobuf/util/message_differencer.h"
20 
21 #include "google/protobuf/testing/googletest.h"
22 
23 namespace google {
24 namespace protobuf {
25 namespace TestUtil {
26 
TestSourceDir()27 inline std::string TestSourceDir() {
28   return google::protobuf::TestSourceDir();
29 }
30 
GetTestDataPath(absl::string_view path)31 inline std::string GetTestDataPath(absl::string_view path) {
32   return absl::StrCat(TestSourceDir(), "/", path);
33 }
34 
35 // Checks the equality of "message" and serialized proto of type "ProtoType".
36 // Do not directly compare two serialized protos.
37 template <typename ProtoType>
EqualsToSerialized(const ProtoType & message,const std::string & data)38 bool EqualsToSerialized(const ProtoType& message, const std::string& data) {
39   ProtoType other;
40   other.ParsePartialFromString(data);
41   return util::MessageDifferencer::Equals(message, other);
42 }
43 
44 // Wraps io::ArrayInputStream while checking against bound. When a blocking
45 // stream is used with bounded length, proto parsing must not access beyond the
46 // bound. Otherwise, it can result in unintended block, then deadlock.
47 class BoundedArrayInputStream : public io::ZeroCopyInputStream {
48  public:
BoundedArrayInputStream(const void * data,int size)49   BoundedArrayInputStream(const void* data, int size)
50       : stream_(data, size), bound_(size) {}
~BoundedArrayInputStream()51   ~BoundedArrayInputStream() override {}
52 
Next(const void ** data,int * size)53   bool Next(const void** data, int* size) override {
54     ABSL_CHECK_LT(stream_.ByteCount(), bound_);
55     return stream_.Next(data, size);
56   }
BackUp(int count)57   void BackUp(int count) override { stream_.BackUp(count); }
Skip(int count)58   bool Skip(int count) override { return stream_.Skip(count); }
ByteCount()59   int64_t ByteCount() const override { return stream_.ByteCount(); }
60 
61  private:
62   io::ArrayInputStream stream_;
63   int bound_;
64 };
65 
66 }  // namespace TestUtil
67 }  // namespace protobuf
68 }  // namespace google
69 
70 #endif  // GOOGLE_PROTOBUF_TEST_UTIL2_H__
71