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 V8_HEAP_CPPGC_VIRTUAL_MEMORY_H_
6#define V8_HEAP_CPPGC_VIRTUAL_MEMORY_H_
7
8#include <cstdint>
9
10#include "include/cppgc/platform.h"
11#include "src/base/macros.h"
12
13namespace cppgc {
14namespace internal {
15
16// Represents and controls an area of reserved memory.
17class V8_EXPORT_PRIVATE VirtualMemory {
18 public:
19  // Empty VirtualMemory object, controlling no reserved memory.
20  VirtualMemory() = default;
21
22  // Reserves virtual memory containing an area of the given size that is
23  // aligned per |alignment| rounded up to the |page_allocator|'s allocate page
24  // size. The |size| is aligned with |page_allocator|'s commit page size.
25  VirtualMemory(PageAllocator*, size_t size, size_t alignment,
26                void* hint = nullptr);
27
28  // Releases the reserved memory, if any, controlled by this VirtualMemory
29  // object.
30  ~VirtualMemory() V8_NOEXCEPT;
31
32  VirtualMemory(VirtualMemory&&) V8_NOEXCEPT;
33  VirtualMemory& operator=(VirtualMemory&&) V8_NOEXCEPT;
34
35  // Returns whether the memory has been reserved.
36  bool IsReserved() const { return start_ != nullptr; }
37
38  void* address() const {
39    DCHECK(IsReserved());
40    return start_;
41  }
42
43  size_t size() const {
44    DCHECK(IsReserved());
45    return size_;
46  }
47
48 private:
49  // Resets to the default state.
50  void Reset();
51
52  PageAllocator* page_allocator_ = nullptr;
53  void* start_ = nullptr;
54  size_t size_ = 0;
55};
56
57}  // namespace internal
58}  // namespace cppgc
59
60#endif  // V8_HEAP_CPPGC_VIRTUAL_MEMORY_H_
61