• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Defines utilities for the FieldMask well known type.
32 
33 #ifndef GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
34 #define GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
35 
36 #include <string>
37 
38 #include <google/protobuf/field_mask.pb.h>
39 #include <google/protobuf/descriptor.h>
40 #include <google/protobuf/stubs/strutil.h>
41 
42 // Must be included last.
43 #include <google/protobuf/port_def.inc>
44 
45 namespace google {
46 namespace protobuf {
47 namespace util {
48 
49 class PROTOBUF_EXPORT FieldMaskUtil {
50   typedef google::protobuf::FieldMask FieldMask;
51 
52  public:
53   // Converts FieldMask to/from string, formatted by separating each path
54   // with a comma (e.g., "foo_bar,baz.quz").
55   static std::string ToString(const FieldMask& mask);
56   static void FromString(StringPiece str, FieldMask* out);
57 
58   // Populates the FieldMask with the paths corresponding to the fields with the
59   // given numbers, after checking that all field numbers are valid.
60   template <typename T>
FromFieldNumbers(const std::vector<int64> & field_numbers,FieldMask * out)61   static void FromFieldNumbers(const std::vector<int64>& field_numbers,
62                                FieldMask* out) {
63     for (const auto field_number : field_numbers) {
64       const FieldDescriptor* field_desc =
65           T::descriptor()->FindFieldByNumber(field_number);
66       GOOGLE_CHECK(field_desc != nullptr)
67           << "Invalid field number for " << T::descriptor()->full_name() << ": "
68           << field_number;
69       AddPathToFieldMask<T>(field_desc->lowercase_name(), out);
70     }
71   }
72 
73   // Converts FieldMask to/from string, formatted according to proto3 JSON
74   // spec for FieldMask (e.g., "fooBar,baz.quz"). If the field name is not
75   // style conforming (i.e., not snake_case when converted to string, or not
76   // camelCase when converted from string), the conversion will fail.
77   static bool ToJsonString(const FieldMask& mask, std::string* out);
78   static bool FromJsonString(StringPiece str, FieldMask* out);
79 
80   // Get the descriptors of the fields which the given path from the message
81   // descriptor traverses, if field_descriptors is not null.
82   // Return false if the path is not valid, and the content of field_descriptors
83   // is unspecified.
84   static bool GetFieldDescriptors(
85       const Descriptor* descriptor, StringPiece path,
86       std::vector<const FieldDescriptor*>* field_descriptors);
87 
88   // Checks whether the given path is valid for type T.
89   template <typename T>
IsValidPath(StringPiece path)90   static bool IsValidPath(StringPiece path) {
91     return GetFieldDescriptors(T::descriptor(), path, nullptr);
92   }
93 
94   // Checks whether the given FieldMask is valid for type T.
95   template <typename T>
IsValidFieldMask(const FieldMask & mask)96   static bool IsValidFieldMask(const FieldMask& mask) {
97     for (int i = 0; i < mask.paths_size(); ++i) {
98       if (!GetFieldDescriptors(T::descriptor(), mask.paths(i), nullptr))
99         return false;
100     }
101     return true;
102   }
103 
104   // Adds a path to FieldMask after checking whether the given path is valid.
105   // This method check-fails if the path is not a valid path for type T.
106   template <typename T>
AddPathToFieldMask(StringPiece path,FieldMask * mask)107   static void AddPathToFieldMask(StringPiece path, FieldMask* mask) {
108     GOOGLE_CHECK(IsValidPath<T>(path)) << path;
109     mask->add_paths(std::string(path));
110   }
111 
112   // Creates a FieldMask with all fields of type T. This FieldMask only
113   // contains fields of T but not any sub-message fields.
114   template <typename T>
GetFieldMaskForAllFields()115   static FieldMask GetFieldMaskForAllFields() {
116     FieldMask out;
117     GetFieldMaskForAllFields(T::descriptor(), &out);
118     return out;
119   }
120   template <typename T>
121   PROTOBUF_DEPRECATED_MSG("Use *out = GetFieldMaskForAllFields() instead")
GetFieldMaskForAllFields(FieldMask * out)122   static void GetFieldMaskForAllFields(FieldMask* out) {
123     GetFieldMaskForAllFields(T::descriptor(), out);
124   }
125   // This flavor takes the protobuf type descriptor as an argument.
126   // Useful when the type is not known at compile time.
127   static void GetFieldMaskForAllFields(const Descriptor* descriptor,
128                                        FieldMask* out);
129 
130   // Converts a FieldMask to the canonical form. It will:
131   //   1. Remove paths that are covered by another path. For example,
132   //      "foo.bar" is covered by "foo" and will be removed if "foo"
133   //      is also in the FieldMask.
134   //   2. Sort all paths in alphabetical order.
135   static void ToCanonicalForm(const FieldMask& mask, FieldMask* out);
136 
137   // Creates an union of two FieldMasks.
138   static void Union(const FieldMask& mask1, const FieldMask& mask2,
139                     FieldMask* out);
140 
141   // Creates an intersection of two FieldMasks.
142   static void Intersect(const FieldMask& mask1, const FieldMask& mask2,
143                         FieldMask* out);
144 
145   // Subtracts mask2 from mask1 base of type T.
146   template <typename T>
Subtract(const FieldMask & mask1,const FieldMask & mask2,FieldMask * out)147   static void Subtract(const FieldMask& mask1, const FieldMask& mask2,
148                        FieldMask* out) {
149     Subtract(T::descriptor(), mask1, mask2, out);
150   }
151   // This flavor takes the protobuf type descriptor as an argument.
152   // Useful when the type is not known at compile time.
153   static void Subtract(const Descriptor* descriptor, const FieldMask& mask1,
154                        const FieldMask& mask2, FieldMask* out);
155 
156   // Returns true if path is covered by the given FieldMask. Note that path
157   // "foo.bar" covers all paths like "foo.bar.baz", "foo.bar.quz.x", etc.
158   // Also note that parent paths are not covered by explicit child path, i.e.
159   // "foo.bar" does NOT cover "foo", even if "bar" is the only child.
160   static bool IsPathInFieldMask(StringPiece path, const FieldMask& mask);
161 
162   class MergeOptions;
163   // Merges fields specified in a FieldMask into another message.
164   static void MergeMessageTo(const Message& source, const FieldMask& mask,
165                              const MergeOptions& options, Message* destination);
166 
167   class TrimOptions;
168   // Removes from 'message' any field that is not represented in the given
169   // FieldMask. If the FieldMask is empty, does nothing.
170   // Returns true if the message is modified.
171   static bool TrimMessage(const FieldMask& mask, Message* message);
172 
173   // Removes from 'message' any field that is not represented in the given
174   // FieldMask with customized TrimOptions.
175   // If the FieldMask is empty, does nothing.
176   // Returns true if the message is modified.
177   static bool TrimMessage(const FieldMask& mask, Message* message,
178                           const TrimOptions& options);
179 
180  private:
181   friend class SnakeCaseCamelCaseTest;
182   // Converts a field name from snake_case to camelCase:
183   //   1. Every character after "_" will be converted to uppercase.
184   //   2. All "_"s are removed.
185   // The conversion will fail if:
186   //   1. The field name contains uppercase letters.
187   //   2. Any character after a "_" is not a lowercase letter.
188   // If the conversion succeeds, it's guaranteed that the resulted
189   // camelCase name will yield the original snake_case name when
190   // converted using CamelCaseToSnakeCase().
191   //
192   // Note that the input can contain characters not allowed in C identifiers.
193   // For example, "foo_bar,baz_quz" will be converted to "fooBar,bazQuz"
194   // successfully.
195   static bool SnakeCaseToCamelCase(StringPiece input,
196                                    std::string* output);
197   // Converts a field name from camelCase to snake_case:
198   //   1. Every uppercase letter is converted to lowercase with an additional
199   //      preceding "_".
200   // The conversion will fail if:
201   //   1. The field name contains "_"s.
202   // If the conversion succeeds, it's guaranteed that the resulted
203   // snake_case name will yield the original camelCase name when
204   // converted using SnakeCaseToCamelCase().
205   //
206   // Note that the input can contain characters not allowed in C identifiers.
207   // For example, "fooBar,bazQuz" will be converted to "foo_bar,baz_quz"
208   // successfully.
209   static bool CamelCaseToSnakeCase(StringPiece input,
210                                    std::string* output);
211 };
212 
213 class PROTOBUF_EXPORT FieldMaskUtil::MergeOptions {
214  public:
MergeOptions()215   MergeOptions()
216       : replace_message_fields_(false), replace_repeated_fields_(false) {}
217   // When merging message fields, the default behavior is to merge the
218   // content of two message fields together. If you instead want to use
219   // the field from the source message to replace the corresponding field
220   // in the destination message, set this flag to true. When this flag is set,
221   // specified submessage fields that are missing in source will be cleared in
222   // destination.
set_replace_message_fields(bool value)223   void set_replace_message_fields(bool value) {
224     replace_message_fields_ = value;
225   }
replace_message_fields()226   bool replace_message_fields() const { return replace_message_fields_; }
227   // The default merging behavior will append entries from the source
228   // repeated field to the destination repeated field. If you only want
229   // to keep the entries from the source repeated field, set this flag
230   // to true.
set_replace_repeated_fields(bool value)231   void set_replace_repeated_fields(bool value) {
232     replace_repeated_fields_ = value;
233   }
replace_repeated_fields()234   bool replace_repeated_fields() const { return replace_repeated_fields_; }
235 
236  private:
237   bool replace_message_fields_;
238   bool replace_repeated_fields_;
239 };
240 
241 class PROTOBUF_EXPORT FieldMaskUtil::TrimOptions {
242  public:
TrimOptions()243   TrimOptions() : keep_required_fields_(false) {}
244   // When trimming message fields, the default behavior is to trim required
245   // fields of the present message if they are not specified in the field mask.
246   // If you instead want to keep required fields of the present message even
247   // they are not specified in the field mask, set this flag to true.
set_keep_required_fields(bool value)248   void set_keep_required_fields(bool value) { keep_required_fields_ = value; }
keep_required_fields()249   bool keep_required_fields() const { return keep_required_fields_; }
250 
251  private:
252   bool keep_required_fields_;
253 };
254 
255 }  // namespace util
256 }  // namespace protobuf
257 }  // namespace google
258 
259 #include <google/protobuf/port_undef.inc>
260 
261 #endif  // GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
262