Home | History | Annotate | Download | only in filter
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef AAPT2_FILTER_H
     18 #define AAPT2_FILTER_H
     19 
     20 #include <string>
     21 #include <vector>
     22 
     23 #include "util/Util.h"
     24 
     25 namespace aapt {
     26 
     27 /** A filter to be applied to a path segment. */
     28 class IPathFilter {
     29  public:
     30   virtual ~IPathFilter() = default;
     31 
     32   /** Returns true if the path should be kept. */
     33   virtual bool Keep(const std::string& path) = 0;
     34 };
     35 
     36 /**
     37  * Path filter that keeps anything that matches the provided prefix.
     38  */
     39 class PrefixFilter : public IPathFilter {
     40  public:
     41   explicit PrefixFilter(std::string prefix) : prefix_(std::move(prefix)) {
     42   }
     43 
     44   /** Returns true if the provided path matches the prefix. */
     45   bool Keep(const std::string& path) override {
     46     return util::StartsWith(path, prefix_);
     47   }
     48 
     49  private:
     50   const std::string prefix_;
     51 };
     52 
     53 /** Applies a set of IPathFilters to a path and returns true iif all filters keep the path. */
     54 class FilterChain : public IPathFilter {
     55  public:
     56   /** Adds a filter to the list to be applied to each path. */
     57   void AddFilter(std::unique_ptr<IPathFilter> filter) {
     58     filters_.push_back(std::move(filter));
     59   }
     60 
     61   /** Returns true if all filters keep the path. */
     62   bool Keep(const std::string& path) override {
     63     for (auto& filter : filters_) {
     64       if (!filter->Keep(path)) {
     65         return false;
     66       }
     67     }
     68     return true;
     69   }
     70 
     71  private:
     72   std::vector<std::unique_ptr<IPathFilter>> filters_;
     73 };
     74 
     75 }  // namespace aapt
     76 
     77 #endif  // AAPT2_FILTER_H
     78