• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 the V8 project 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 INCLUDE_CPPGC_CUSTOM_SPACE_H_
6 #define INCLUDE_CPPGC_CUSTOM_SPACE_H_
7 
8 #include <stddef.h>
9 
10 namespace cppgc {
11 
12 struct CustomSpaceIndex {
CustomSpaceIndexCustomSpaceIndex13   CustomSpaceIndex(size_t value) : value(value) {}  // NOLINT
14   size_t value;
15 };
16 
17 /**
18  * Top-level base class for custom spaces. Users must inherit from CustomSpace
19  * below.
20  */
21 class CustomSpaceBase {
22  public:
23   virtual ~CustomSpaceBase() = default;
24   virtual CustomSpaceIndex GetCustomSpaceIndex() const = 0;
25   virtual bool IsCompactable() const = 0;
26 };
27 
28 /**
29  * Base class custom spaces should directly inherit from. The class inheriting
30  * from `CustomSpace` must define `kSpaceIndex` as unique space index. These
31  * indices need for form a sequence starting at 0.
32  *
33  * Example:
34  * \code
35  * class CustomSpace1 : public CustomSpace<CustomSpace1> {
36  *  public:
37  *   static constexpr CustomSpaceIndex kSpaceIndex = 0;
38  * };
39  * class CustomSpace2 : public CustomSpace<CustomSpace2> {
40  *  public:
41  *   static constexpr CustomSpaceIndex kSpaceIndex = 1;
42  * };
43  * \endcode
44  */
45 template <typename ConcreteCustomSpace>
46 class CustomSpace : public CustomSpaceBase {
47  public:
GetCustomSpaceIndex()48   CustomSpaceIndex GetCustomSpaceIndex() const final {
49     return ConcreteCustomSpace::kSpaceIndex;
50   }
IsCompactable()51   bool IsCompactable() const final {
52     return ConcreteCustomSpace::kSupportsCompaction;
53   }
54 
55  protected:
56   static constexpr bool kSupportsCompaction = false;
57 };
58 
59 /**
60  * User-overridable trait that allows pinning types to custom spaces.
61  */
62 template <typename T, typename = void>
63 struct SpaceTrait {
64   using Space = void;
65 };
66 
67 namespace internal {
68 
69 template <typename CustomSpace>
70 struct IsAllocatedOnCompactableSpaceImpl {
71   static constexpr bool value = CustomSpace::kSupportsCompaction;
72 };
73 
74 template <>
75 struct IsAllocatedOnCompactableSpaceImpl<void> {
76   // Non-custom spaces are by default not compactable.
77   static constexpr bool value = false;
78 };
79 
80 template <typename T>
81 struct IsAllocatedOnCompactableSpace {
82  public:
83   static constexpr bool value =
84       IsAllocatedOnCompactableSpaceImpl<typename SpaceTrait<T>::Space>::value;
85 };
86 
87 }  // namespace internal
88 
89 }  // namespace cppgc
90 
91 #endif  // INCLUDE_CPPGC_CUSTOM_SPACE_H_
92