• 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 #include <include/cppgc/allocation.h>
6 #include <include/cppgc/default-platform.h>
7 #include <include/cppgc/garbage-collected.h>
8 #include <include/cppgc/heap.h>
9 #include <include/cppgc/member.h>
10 #include <include/cppgc/platform.h>
11 #include <include/cppgc/visitor.h>
12 #include <include/v8.h>
13 
14 #include <iostream>
15 #include <memory>
16 #include <string>
17 
18 /**
19  * This sample program shows how to set up a stand-alone cppgc heap as an
20  * embedder of V8. Most importantly, this example shows how to reuse V8's
21  * platform for cppgc.
22  */
23 
24 /**
25  * Simple string rope to illustrate allocation and garbage collection below. The
26  * rope keeps the next parts alive via regular managed reference.
27  */
28 class Rope final : public cppgc::GarbageCollected<Rope> {
29  public:
Rope(std::string part,Rope * next=nullptr)30   explicit Rope(std::string part, Rope* next = nullptr)
31       : part_(part), next_(next) {}
32 
Trace(cppgc::Visitor * visitor) const33   void Trace(cppgc::Visitor* visitor) const { visitor->Trace(next_); }
34 
35  private:
36   std::string part_;
37   cppgc::Member<Rope> next_;
38 
39   friend std::ostream& operator<<(std::ostream& os, const Rope& rope);
40 };
41 
operator <<(std::ostream & os,const Rope & rope)42 std::ostream& operator<<(std::ostream& os, const Rope& rope) {
43   os << rope.part_;
44   if (rope.next_) {
45     os << *rope.next_;
46   }
47   return os;
48 }
49 
main(int argc,char * argv[])50 int main(int argc, char* argv[]) {
51   // Create a platform that is used by cppgc::Heap for execution and backend
52   // allocation.
53   auto cppgc_platform = std::make_shared<cppgc::DefaultPlatform>();
54   // Initialize the process. This must happen before any cppgc::Heap::Create()
55   // calls.
56   cppgc::InitializeProcess(cppgc_platform->GetPageAllocator());
57   // Create a managed heap.
58   std::unique_ptr<cppgc::Heap> heap = cppgc::Heap::Create(cppgc_platform);
59   // Allocate a string rope on the managed heap.
60   auto* greeting = cppgc::MakeGarbageCollected<Rope>(
61       heap->GetAllocationHandle(), "Hello ",
62       cppgc::MakeGarbageCollected<Rope>(heap->GetAllocationHandle(), "World!"));
63   // Manually trigger garbage collection. The object greeting is held alive
64   // through conservative stack scanning.
65   heap->ForceGarbageCollectionSlow("V8 embedders example", "Testing");
66   std::cout << *greeting << std::endl;
67   // Gracefully shutdown the process.
68   cppgc::ShutdownProcess();
69   return 0;
70 }
71