1 // Copyright (C) 2019 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 "icing/result/projector.h"
16 
17 #include <algorithm>
18 
19 namespace icing {
20 namespace lib {
21 
22 namespace projector {
23 
Project(const std::vector<ProjectionTree::Node> & projection_tree,DocumentProto * document)24 void Project(const std::vector<ProjectionTree::Node>& projection_tree,
25              DocumentProto* document) {
26   int num_kept = 0;
27   for (int cur_pos = 0; cur_pos < document->properties_size(); ++cur_pos) {
28     PropertyProto* prop = document->mutable_properties(cur_pos);
29     auto itr = std::find_if(projection_tree.begin(), projection_tree.end(),
30                             [&prop](const ProjectionTree::Node& node) {
31                               return node.name == prop->name();
32                             });
33     if (itr == projection_tree.end()) {
34       // Property is not present in the projection tree. Just skip it.
35       continue;
36     }
37     // This property should be kept.
38     document->mutable_properties()->SwapElements(num_kept, cur_pos);
39     ++num_kept;
40     if (itr->children.empty()) {
41       // A field mask does refer to this property, but it has no children. So
42       // we should take the entire property, with all of its
43       // subproperties/values
44       continue;
45     }
46     // The field mask refers to children of this property. Recurse through the
47     // document values that this property holds and project the children
48     // requested by this field mask.
49     for (DocumentProto& subproperty : *(prop->mutable_document_values())) {
50       Project(itr->children, &subproperty);
51     }
52   }
53   document->mutable_properties()->DeleteSubrange(
54       num_kept, document->properties_size() - num_kept);
55 }
56 
57 }  // namespace projector
58 
59 }  // namespace lib
60 }  // namespace icing
61