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 <cstdint>
37#include <string>
38
39#include <google/protobuf/field_mask.pb.h>
40#include <google/protobuf/stubs/strutil.h>
41#include <google/protobuf/descriptor.h>
42
43// Must be included last.
44#include <google/protobuf/port_def.inc>
45
46namespace google {
47namespace protobuf {
48namespace util {
49
50class PROTOBUF_EXPORT FieldMaskUtil {
51 typedef google::protobuf::FieldMask FieldMask;
52
53 public:
54 // Converts FieldMask to/from string, formatted by separating each path
55 // with a comma (e.g., "foo_bar,baz.quz").
56 static std::string ToString(const FieldMask& mask);
57 static void FromString(StringPiece str, FieldMask* out);
58
59 // Populates the FieldMask with the paths corresponding to the fields with the
60 // given numbers, after checking that all field numbers are valid.
61 template <typename T>
62 static void FromFieldNumbers(const std::vector<int64_t>& field_numbers,
63 FieldMask* out) {
64 for (const auto field_number : field_numbers) {
65 const FieldDescriptor* field_desc =
66 T::descriptor()->FindFieldByNumber(field_number);
67 GOOGLE_CHECK(field_desc != nullptr)
68 << "Invalid field number for " << T::descriptor()->full_name() << ": "
69 << field_number;
70 AddPathToFieldMask<T>(field_desc->lowercase_name(), out);
71 }
72 }
73
74 // Converts FieldMask to/from string, formatted according to proto3 JSON
75 // spec for FieldMask (e.g., "fooBar,baz.quz"). If the field name is not
76 // style conforming (i.e., not snake_case when converted to string, or not
77 // camelCase when converted from string), the conversion will fail.
78 static bool ToJsonString(const FieldMask& mask, std::string* out);
79 static bool FromJsonString(StringPiece str, FieldMask* out);
80
81 // Get the descriptors of the fields which the given path from the message
82 // descriptor traverses, if field_descriptors is not null.
83 // Return false if the path is not valid, and the content of field_descriptors
84 // is unspecified.
85 static bool GetFieldDescriptors(
86 const Descriptor* descriptor, StringPiece path,
87 std::vector<const FieldDescriptor*>* field_descriptors);
88
89 // Checks whether the given path is valid for type T.
90 template <typename T>
91 static bool IsValidPath(StringPiece path) {
92 return GetFieldDescriptors(descriptor: T::descriptor(), path, field_descriptors: nullptr);
93 }
94
95 // Checks whether the given FieldMask is valid for type T.
96 template <typename T>
97 static bool IsValidFieldMask(const FieldMask& mask) {
98 for (int i = 0; i < mask.paths_size(); ++i) {
99 if (!GetFieldDescriptors(descriptor: T::descriptor(), path: mask.paths(index: i), field_descriptors: nullptr)) {
100 return false;
101 }
102 }
103 return true;
104 }
105
106 // Adds a path to FieldMask after checking whether the given path is valid.
107 // This method check-fails if the path is not a valid path for type T.
108 template <typename T>
109 static void AddPathToFieldMask(StringPiece path, FieldMask* mask) {
110 GOOGLE_CHECK(IsValidPath<T>(path)) << path;
111 mask->add_paths(value: std::string(path));
112 }
113
114 // Creates a FieldMask with all fields of type T. This FieldMask only
115 // contains fields of T but not any sub-message fields.
116 template <typename T>
117 static FieldMask GetFieldMaskForAllFields() {
118 FieldMask out;
119 GetFieldMaskForAllFields(T::descriptor(), &out);
120 return out;
121 }
122 template <typename T>
123 PROTOBUF_DEPRECATED_MSG("Use *out = GetFieldMaskForAllFields() instead")
124 static void GetFieldMaskForAllFields(FieldMask* out) {
125 GetFieldMaskForAllFields(T::descriptor(), out);
126 }
127 // This flavor takes the protobuf type descriptor as an argument.
128 // Useful when the type is not known at compile time.
129 static void GetFieldMaskForAllFields(const Descriptor* descriptor,
130 FieldMask* out);
131
132 // Converts a FieldMask to the canonical form. It will:
133 // 1. Remove paths that are covered by another path. For example,
134 // "foo.bar" is covered by "foo" and will be removed if "foo"
135 // is also in the FieldMask.
136 // 2. Sort all paths in alphabetical order.
137 static void ToCanonicalForm(const FieldMask& mask, FieldMask* out);
138
139 // Creates an union of two FieldMasks.
140 static void Union(const FieldMask& mask1, const FieldMask& mask2,
141 FieldMask* out);
142
143 // Creates an intersection of two FieldMasks.
144 static void Intersect(const FieldMask& mask1, const FieldMask& mask2,
145 FieldMask* out);
146
147 // Subtracts mask2 from mask1 base of type T.
148 template <typename T>
149 static void Subtract(const FieldMask& mask1, const FieldMask& mask2,
150 FieldMask* out) {
151 Subtract(T::descriptor(), mask1, mask2, out);
152 }
153 // This flavor takes the protobuf type descriptor as an argument.
154 // Useful when the type is not known at compile time.
155 static void Subtract(const Descriptor* descriptor, const FieldMask& mask1,
156 const FieldMask& mask2, FieldMask* out);
157
158 // Returns true if path is covered by the given FieldMask. Note that path
159 // "foo.bar" covers all paths like "foo.bar.baz", "foo.bar.quz.x", etc.
160 // Also note that parent paths are not covered by explicit child path, i.e.
161 // "foo.bar" does NOT cover "foo", even if "bar" is the only child.
162 static bool IsPathInFieldMask(StringPiece path, const FieldMask& mask);
163
164 class MergeOptions;
165 // Merges fields specified in a FieldMask into another message.
166 static void MergeMessageTo(const Message& source, const FieldMask& mask,
167 const MergeOptions& options, Message* destination);
168
169 class TrimOptions;
170 // Removes from 'message' any field that is not represented in the given
171 // FieldMask. If the FieldMask is empty, does nothing.
172 // Returns true if the message is modified.
173 static bool TrimMessage(const FieldMask& mask, Message* message);
174
175 // Removes from 'message' any field that is not represented in the given
176 // FieldMask with customized TrimOptions.
177 // If the FieldMask is empty, does nothing.
178 // Returns true if the message is modified.
179 static bool TrimMessage(const FieldMask& mask, Message* message,
180 const TrimOptions& options);
181
182 private:
183 friend class SnakeCaseCamelCaseTest;
184 // Converts a field name from snake_case to camelCase:
185 // 1. Every character after "_" will be converted to uppercase.
186 // 2. All "_"s are removed.
187 // The conversion will fail if:
188 // 1. The field name contains uppercase letters.
189 // 2. Any character after a "_" is not a lowercase letter.
190 // If the conversion succeeds, it's guaranteed that the resulted
191 // camelCase name will yield the original snake_case name when
192 // converted using CamelCaseToSnakeCase().
193 //
194 // Note that the input can contain characters not allowed in C identifiers.
195 // For example, "foo_bar,baz_quz" will be converted to "fooBar,bazQuz"
196 // successfully.
197 static bool SnakeCaseToCamelCase(StringPiece input,
198 std::string* output);
199 // Converts a field name from camelCase to snake_case:
200 // 1. Every uppercase letter is converted to lowercase with an additional
201 // preceding "_".
202 // The conversion will fail if:
203 // 1. The field name contains "_"s.
204 // If the conversion succeeds, it's guaranteed that the resulted
205 // snake_case name will yield the original camelCase name when
206 // converted using SnakeCaseToCamelCase().
207 //
208 // Note that the input can contain characters not allowed in C identifiers.
209 // For example, "fooBar,bazQuz" will be converted to "foo_bar,baz_quz"
210 // successfully.
211 static bool CamelCaseToSnakeCase(StringPiece input,
212 std::string* output);
213};
214
215class PROTOBUF_EXPORT FieldMaskUtil::MergeOptions {
216 public:
217 MergeOptions()
218 : replace_message_fields_(false), replace_repeated_fields_(false) {}
219 // When merging message fields, the default behavior is to merge the
220 // content of two message fields together. If you instead want to use
221 // the field from the source message to replace the corresponding field
222 // in the destination message, set this flag to true. When this flag is set,
223 // specified submessage fields that are missing in source will be cleared in
224 // destination.
225 void set_replace_message_fields(bool value) {
226 replace_message_fields_ = value;
227 }
228 bool replace_message_fields() const { return replace_message_fields_; }
229 // The default merging behavior will append entries from the source
230 // repeated field to the destination repeated field. If you only want
231 // to keep the entries from the source repeated field, set this flag
232 // to true.
233 void set_replace_repeated_fields(bool value) {
234 replace_repeated_fields_ = value;
235 }
236 bool replace_repeated_fields() const { return replace_repeated_fields_; }
237
238 private:
239 bool replace_message_fields_;
240 bool replace_repeated_fields_;
241};
242
243class PROTOBUF_EXPORT FieldMaskUtil::TrimOptions {
244 public:
245 TrimOptions() : keep_required_fields_(false) {}
246 // When trimming message fields, the default behavior is to trim required
247 // fields of the present message if they are not specified in the field mask.
248 // If you instead want to keep required fields of the present message even
249 // when they are not specified in the field mask, set this flag to true.
250 void set_keep_required_fields(bool value) { keep_required_fields_ = value; }
251 bool keep_required_fields() const { return keep_required_fields_; }
252
253 private:
254 bool keep_required_fields_;
255};
256
257} // namespace util
258} // namespace protobuf
259} // namespace google
260
261#include <google/protobuf/port_undef.inc>
262
263#endif // GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
264