liveness-broker.h 1.87 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef INCLUDE_CPPGC_LIVENESS_BROKER_H_
#define INCLUDE_CPPGC_LIVENESS_BROKER_H_

8 9 10
#include "cppgc/heap.h"
#include "cppgc/member.h"
#include "cppgc/trace-trait.h"
11
#include "v8config.h"  // NOLINT(build/include_directory)
12 13 14 15 16 17 18

namespace cppgc {

namespace internal {
class LivenessBrokerFactory;
}  // namespace internal

19 20 21
/**
 * The broker is passed to weak callbacks to allow (temporarily) querying
 * the liveness state of an object. References to non-live objects must be
22
 * cleared when `IsHeapObjectAlive()` returns false.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 *
 * \code
 * class GCedWithCustomWeakCallback final
 *   : public GarbageCollected<GCedWithCustomWeakCallback> {
 *  public:
 *   UntracedMember<Bar> bar;
 *
 *   void CustomWeakCallbackMethod(const LivenessBroker& broker) {
 *     if (!broker.IsHeapObjectAlive(bar))
 *       bar = nullptr;
 *   }
 *
 *   void Trace(cppgc::Visitor* visitor) const {
 *     visitor->RegisterWeakCallbackMethod<
 *         GCedWithCustomWeakCallback,
 *         &GCedWithCustomWeakCallback::CustomWeakCallbackMethod>(this);
 *   }
 * };
 * \endcode
 */
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
class V8_EXPORT LivenessBroker final {
 public:
  template <typename T>
  bool IsHeapObjectAlive(const T* object) const {
    return object &&
           IsHeapObjectAliveImpl(
               TraceTrait<T>::GetTraceDescriptor(object).base_object_payload);
  }

  template <typename T>
  bool IsHeapObjectAlive(const UntracedMember<T>& untraced_member) const {
    return (untraced_member != kSentinelPointer) &&
           IsHeapObjectAlive<T>(untraced_member.Get());
  }

 private:
  LivenessBroker() = default;

  bool IsHeapObjectAliveImpl(const void*) const;

  friend class internal::LivenessBrokerFactory;
};

}  // namespace cppgc

#endif  // INCLUDE_CPPGC_LIVENESS_BROKER_H_