chromium/components/sync/base/weak_handle.h

// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_SYNC_BASE_WEAK_HANDLE_H_
#define COMPONENTS_SYNC_BASE_WEAK_HANDLE_H_

#include <cstddef>
#include <utility>

#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/gtest_prod_util.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/task/sequenced_task_runner.h"

// Weak handles provides a way to refer to weak pointers from another sequence.
// This is useful because it is not safe to reference a weak pointer from a
// sequence other than the sequence on which it was created.
//
// Weak handles can be passed across sequences, so for example, you can use them
// to do the "real" work on one thread and get notified on another thread:
//
// class FooIOWorker {
//  public:
//   FooIOWorker(const WeakHandle<Foo>& foo) : foo_(foo) {}
//
//   void OnIOStart() {
//     foo_.Call(FROM_HERE, &Foo::OnIOStart);
//   }
//
//  private:
//   const WeakHandle<Foo> foo_;
// };
//
// class Foo : public SupportsWeakPtr<Foo> {
//  public:
//   Foo() {
//     SpawnFooIOWorkerOnIOThread(base::MakeWeakHandle(AsWeakPtr()));
//   }
//
//   /* Will always be called on the correct sequence, and only if this
//      object hasn't been destroyed. */
//   void OnIOStart() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); .. }
//
//  private:
//   SEQUENCE_CHECKER(sequence_checker_);
// };

namespace base {
class Location;
}  // namespace base

namespace syncer {

template <typename T>
class WeakHandle;

namespace internal {
// These classes are part of the WeakHandle implementation.  DO NOT
// USE THESE CLASSES DIRECTLY YOURSELF.

// Base class for WeakHandleCore<T> to avoid template bloat.  Handles
// the interaction with the owner thread and its message loop.
class WeakHandleCoreBase {};

// WeakHandleCore<T> contains all the logic for WeakHandle<T>.
template <typename T>
class WeakHandleCore : public WeakHandleCoreBase,
                       public base::RefCountedThreadSafe<WeakHandleCore<T>> {};

}  // namespace internal

// May be destroyed on any thread.
// Copying and assignment are welcome.
template <typename T>
class WeakHandle {};

// Makes a WeakHandle from a WeakPtr.
template <typename T>
WeakHandle<T> MakeWeakHandle(const base::WeakPtr<T>& ptr) {}

}  // namespace syncer

#endif  // COMPONENTS_SYNC_BASE_WEAK_HANDLE_H_