Line data Source code
1 : // Copyright 2017 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_DETACHABLE_VECTOR_H_
6 : #define V8_DETACHABLE_VECTOR_H_
7 :
8 : #include <vector>
9 :
10 : namespace v8 {
11 : namespace internal {
12 :
13 : // This class wraps a std::vector and provides a few of the common member
14 : // functions for accessing the data. It acts as a lazy wrapper of the vector,
15 : // not initiliazing the backing store until push_back() is first called. Two
16 : // extra methods are also provided: free() and detach(), which allow for manual
17 : // control of the backing store. This is currently required for use in the
18 : // HandleScopeImplementer. Any other class should just use a std::vector
19 : // directly.
20 : template <typename T>
21 : class DetachableVector {
22 : public:
23 55003 : DetachableVector() : vector_(nullptr) {}
24 :
25 313341 : ~DetachableVector() { delete vector_; }
26 :
27 : void push_back(const T& value) {
28 15358819 : ensureAttached();
29 15358917 : vector_->push_back(value);
30 : }
31 :
32 : // Free the backing store and clear our reference to it.
33 17569 : void free() {
34 34606 : delete vector_;
35 17569 : vector_ = nullptr;
36 17569 : }
37 :
38 : // Clear our reference to the backing store. Does not delete it!
39 24164 : void detach() { vector_ = nullptr; }
40 :
41 175328 : T& at(typename std::vector<T>::size_type i) const { return vector_->at(i); }
42 :
43 12750895 : T& back() const { return vector_->back(); }
44 :
45 1 : T& front() const { return vector_->front(); }
46 :
47 1196587 : void pop_back() { vector_->pop_back(); }
48 :
49 : typename std::vector<T>::size_type size() const {
50 1234849 : if (vector_) return vector_->size();
51 : return 0;
52 : }
53 :
54 : bool empty() const {
55 7787355 : if (vector_) return vector_->empty();
56 : return true;
57 : }
58 :
59 : private:
60 : std::vector<T>* vector_;
61 :
62 : // Attach a vector backing store if not present.
63 15358777 : void ensureAttached() {
64 15358777 : if (vector_ == nullptr) {
65 350288 : vector_ = new std::vector<T>();
66 : }
67 15358777 : }
68 : };
69 :
70 : } // namespace internal
71 : } // namespace v8
72 :
73 : #endif // V8_DETACHABLE_VECTOR_H_
|