Home | History | Annotate | Download | only in lib
      1 // Copyright 2013 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_BINDINGS_LIB_PASSABLE_H_
      6 #define MOJO_PUBLIC_BINDINGS_LIB_PASSABLE_H_
      7 
      8 #include "mojo/public/system/core_cpp.h"
      9 
     10 namespace mojo {
     11 
     12 template <typename HandleType>
     13 class Passable {
     14  public:
     15   // |ptr| may be null.
     16   explicit Passable(HandleType* ptr) : ptr_(ptr) {
     17   }
     18 
     19   bool is_valid() {
     20     return ptr_ && ptr_->is_valid();
     21   }
     22 
     23   HandleType get() {
     24     return ptr_ ? *ptr_ : HandleType();
     25   }
     26 
     27   HandleType release() MOJO_WARN_UNUSED_RESULT {
     28     return ptr_ ? internal::FetchAndReset(ptr_) : HandleType();
     29   }
     30 
     31   ScopedHandleBase<HandleType> Pass() {
     32     return ScopedHandleBase<HandleType>(release());
     33   }
     34 
     35  protected:
     36   Passable();
     37   // The default copy-ctor and operator= are OK.
     38 
     39   HandleType* ptr_;
     40 };
     41 
     42 template <typename HandleType>
     43 inline Passable<HandleType> MakePassable(HandleType* ptr) {
     44   return Passable<HandleType>(ptr);
     45 }
     46 
     47 template <typename HandleType>
     48 class AssignableAndPassable : public Passable<HandleType> {
     49  public:
     50   explicit AssignableAndPassable(HandleType* ptr) : Passable<HandleType>(ptr) {
     51     assert(ptr);
     52   }
     53 
     54   void operator=(ScopedHandleBase<HandleType> scoper) {
     55     reset(scoper.release());
     56   }
     57 
     58   void reset(HandleType obj = HandleType()) {
     59     ScopedHandleBase<HandleType>(*this->ptr_);
     60     this->ptr_->set_value(obj.value());
     61   }
     62 };
     63 
     64 template <typename HandleType>
     65 inline AssignableAndPassable<HandleType> MakeAssignableAndPassable(
     66     HandleType* ptr) {
     67   return AssignableAndPassable<HandleType>(ptr);
     68 }
     69 
     70 }  // namespace mojo
     71 
     72 #endif  // MOJO_PUBLIC_BINDINGS_LIB_PASSABLE_H_
     73