Home | History | Annotate | Download | only in src
      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   DetachableVector() : vector_(nullptr) {}
     24 
     25   ~DetachableVector() { delete vector_; }
     26 
     27   void push_back(const T& value) {
     28     ensureAttached();
     29     vector_->push_back(value);
     30   }
     31 
     32   // Free the backing store and clear our reference to it.
     33   void free() {
     34     delete vector_;
     35     vector_ = nullptr;
     36   }
     37 
     38   // Clear our reference to the backing store. Does not delete it!
     39   void detach() { vector_ = nullptr; }
     40 
     41   T& at(typename std::vector<T>::size_type i) const { return vector_->at(i); }
     42 
     43   T& back() const { return vector_->back(); }
     44 
     45   T& front() const { return vector_->front(); }
     46 
     47   void pop_back() { vector_->pop_back(); }
     48 
     49   typename std::vector<T>::size_type size() const {
     50     if (vector_) return vector_->size();
     51     return 0;
     52   }
     53 
     54   bool empty() const {
     55     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   void ensureAttached() {
     64     if (vector_ == nullptr) {
     65       vector_ = new std::vector<T>();
     66     }
     67   }
     68 };
     69 
     70 }  // namespace internal
     71 }  // namespace v8
     72 
     73 #endif  // V8_DETACHABLE_VECTOR_H_
     74