• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 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_ZONE_ZONE_ALLOCATOR_H_
6 #define V8_ZONE_ZONE_ALLOCATOR_H_
7 #include <limits>
8 
9 #include "src/zone/zone.h"
10 
11 namespace v8 {
12 namespace internal {
13 
14 template <typename T>
15 class zone_allocator {
16  public:
17   typedef T* pointer;
18   typedef const T* const_pointer;
19   typedef T& reference;
20   typedef const T& const_reference;
21   typedef T value_type;
22   typedef size_t size_type;
23   typedef ptrdiff_t difference_type;
24   template <class O>
25   struct rebind {
26     typedef zone_allocator<O> other;
27   };
28 
29 #ifdef V8_CC_MSVC
30   // MSVS unfortunately requires the default constructor to be defined.
zone_allocator()31   zone_allocator() : zone_(nullptr) { UNREACHABLE(); }
32 #endif
zone_allocator(Zone * zone)33   explicit zone_allocator(Zone* zone) throw() : zone_(zone) {}
zone_allocator(const zone_allocator & other)34   explicit zone_allocator(const zone_allocator& other) throw()
35       : zone_(other.zone_) {}
36   template <typename U>
zone_allocator(const zone_allocator<U> & other)37   zone_allocator(const zone_allocator<U>& other) throw() : zone_(other.zone_) {}
38   template <typename U>
39   friend class zone_allocator;
40 
address(reference x)41   pointer address(reference x) const { return &x; }
address(const_reference x)42   const_pointer address(const_reference x) const { return &x; }
43 
44   pointer allocate(size_type n, const void* hint = 0) {
45     return static_cast<pointer>(
46         zone_->NewArray<value_type>(static_cast<int>(n)));
47   }
deallocate(pointer p,size_type)48   void deallocate(pointer p, size_type) { /* noop for Zones */
49   }
50 
max_size()51   size_type max_size() const throw() {
52     return std::numeric_limits<int>::max() / sizeof(value_type);
53   }
54   template <typename U, typename... Args>
construct(U * p,Args &&...args)55   void construct(U* p, Args&&... args) {
56     void* v_p = const_cast<void*>(static_cast<const void*>(p));
57     new (v_p) U(std::forward<Args>(args)...);
58   }
59   template <typename U>
destroy(U * p)60   void destroy(U* p) {
61     p->~U();
62   }
63 
64   bool operator==(zone_allocator const& other) const {
65     return zone_ == other.zone_;
66   }
67   bool operator!=(zone_allocator const& other) const {
68     return zone_ != other.zone_;
69   }
70 
zone()71   Zone* zone() { return zone_; }
72 
73  private:
74   Zone* zone_;
75 };
76 
77 typedef zone_allocator<bool> ZoneBoolAllocator;
78 typedef zone_allocator<int> ZoneIntAllocator;
79 }  // namespace internal
80 }  // namespace v8
81 
82 #endif  // V8_ZONE_ZONE_ALLOCATOR_H_
83