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