Home | History | Annotate | Download | only in lib
      1 // Copyright 2014 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_FILTER_CHAIN_H_
      6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_FILTER_CHAIN_H_
      7 
      8 #include <utility>
      9 #include <vector>
     10 
     11 #include "base/macros.h"
     12 #include "mojo/public/cpp/bindings/message.h"
     13 #include "mojo/public/cpp/bindings/message_filter.h"
     14 
     15 namespace mojo {
     16 namespace internal {
     17 
     18 class FilterChain {
     19  public:
     20   // Doesn't take ownership of |sink|. Therefore |sink| has to stay alive while
     21   // this object is alive.
     22   explicit FilterChain(MessageReceiver* sink = nullptr);
     23 
     24   FilterChain(FilterChain&& other);
     25   FilterChain& operator=(FilterChain&& other);
     26   ~FilterChain();
     27 
     28   template <typename FilterType, typename... Args>
     29   inline void Append(Args&&... args);
     30 
     31   // Doesn't take ownership of |sink|. Therefore |sink| has to stay alive while
     32   // this object is alive.
     33   void SetSink(MessageReceiver* sink);
     34 
     35   // Returns a receiver to accept messages. Messages flow through all filters in
     36   // the same order as they were appended to the chain. If all filters allow a
     37   // message to pass, it will be forwarded to |sink_|.
     38   // The returned value is invalidated when this object goes away.
     39   MessageReceiver* GetHead();
     40 
     41  private:
     42   // Owned by this object.
     43   // TODO(dcheng): Use unique_ptr.
     44   std::vector<MessageFilter*> filters_;
     45 
     46   MessageReceiver* sink_;
     47 
     48   DISALLOW_COPY_AND_ASSIGN(FilterChain);
     49 };
     50 
     51 template <typename FilterType, typename... Args>
     52 inline void FilterChain::Append(Args&&... args) {
     53   FilterType* filter = new FilterType(std::forward<Args>(args)..., sink_);
     54   if (!filters_.empty())
     55     filters_.back()->set_sink(filter);
     56   filters_.push_back(filter);
     57 }
     58 
     59 template <>
     60 inline void FilterChain::Append<PassThroughFilter>() {
     61 }
     62 
     63 }  // namespace internal
     64 }  // namespace mojo
     65 
     66 #endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_FILTER_CHAIN_H_
     67