Google Cloud Pub/Sub C++ Client  1.32.1
A C++ Client Library for Google Cloud Pub/Sub
message.cc
Go to the documentation of this file.
1 // Copyright 2020 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "google/cloud/pubsub/message.h"
16 #include "google/cloud/internal/time_utils.h"
17 #include <google/protobuf/text_format.h>
18 #include <google/protobuf/util/message_differencer.h>
19 #include <iostream>
20 
21 namespace google {
22 namespace cloud {
23 namespace pubsub_internal {
24 inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
25 std::size_t MessageProtoSize(::google::pubsub::v1::PubsubMessage const& m) {
26  // see https://cloud.google.com/pubsub/pricing
27  auto constexpr kTimestampOverhead = 20;
28  std::size_t s = kTimestampOverhead + m.data().size();
29  s += m.message_id().size();
30  s += m.ordering_key().size();
31  for (auto const& kv : m.attributes()) {
32  s += kv.first.size() + kv.second.size();
33  }
34  return s;
35 }
36 } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
37 } // namespace pubsub_internal
38 
39 namespace pubsub {
40 inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
41 
42 std::chrono::system_clock::time_point Message::publish_time() const {
43  return google::cloud::internal::ToChronoTimePoint(proto_.publish_time());
44 }
45 
46 std::size_t Message::MessageSize() const {
47  return pubsub_internal::MessageProtoSize(proto_);
48 }
49 
50 bool operator==(Message const& a, Message const& b) {
51  google::protobuf::util::MessageDifferencer diff;
52  return diff.Compare(a.proto_, b.proto_);
53 }
54 
55 std::ostream& operator<<(std::ostream& os, Message const& rhs) {
56  auto constexpr kMaximumPayloadBytes = 64;
57  google::protobuf::TextFormat::Printer p;
58  p.SetSingleLineMode(true);
59  p.SetTruncateStringFieldLongerThan(kMaximumPayloadBytes);
60  std::string text;
61  p.PrintToString(rhs.proto_, &text);
62  return os << text;
63 }
64 
65 } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
66 } // namespace pubsub
67 } // namespace cloud
68 } // namespace google