Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2006-2008 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 NET_BASE_COMPLETION_CALLBACK_H__
      6 #define NET_BASE_COMPLETION_CALLBACK_H__
      7 
      8 #include "base/task.h"
      9 
     10 namespace net {
     11 
     12 // A callback specialization that takes a single int parameter.  Usually this
     13 // is used to report a byte count or network error code.
     14 typedef Callback1<int>::Type CompletionCallback;
     15 
     16 // Used to implement a CompletionCallback.
     17 template <class T>
     18 class CompletionCallbackImpl :
     19     public CallbackImpl< T, void (T::*)(int), Tuple1<int> > {
     20  public:
     21   CompletionCallbackImpl(T* obj, void (T::* meth)(int))
     22     : CallbackImpl< T, void (T::*)(int),
     23                     Tuple1<int> >::CallbackImpl(obj, meth) {
     24   }
     25 };
     26 
     27 // CancelableCompletionCallback is used for completion callbacks
     28 // which may outlive the target for the method dispatch. In such a case, the
     29 // provider of the callback calls Cancel() to mark the callback as
     30 // "canceled". When the canceled callback is eventually run it does nothing
     31 // other than to decrement the refcount to 0 and free the memory.
     32 template <class T>
     33 class CancelableCompletionCallback :
     34     public CompletionCallbackImpl<T>,
     35     public base::RefCounted<CancelableCompletionCallback<T> > {
     36  public:
     37   CancelableCompletionCallback(T* obj, void (T::* meth)(int))
     38     : CompletionCallbackImpl<T>(obj, meth), is_canceled_(false) {
     39   }
     40 
     41   void Cancel() {
     42     is_canceled_ = true;
     43   }
     44 
     45   virtual void RunWithParams(const Tuple1<int>& params) {
     46     if (is_canceled_) {
     47       base::RefCounted<CancelableCompletionCallback<T> >::Release();
     48     } else {
     49       CompletionCallbackImpl<T>::RunWithParams(params);
     50     }
     51   }
     52 
     53  private:
     54   bool is_canceled_;
     55 };
     56 
     57 }  // namespace net
     58 
     59 #endif  // NET_BASE_COMPLETION_CALLBACK_H__
     60