| 1 | // Copyright 2018 The RE2 Authors. All Rights Reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | #ifndef UTIL_POD_ARRAY_H_ |
| 6 | #define UTIL_POD_ARRAY_H_ |
| 7 | |
| 8 | #include <memory> |
| 9 | #include <type_traits> |
| 10 | |
| 11 | namespace re2 { |
| 12 | |
| 13 | template <typename T> |
| 14 | class PODArray { |
| 15 | public: |
| 16 | static_assert(std::is_pod<T>::value, |
| 17 | "T must be POD" ); |
| 18 | |
| 19 | PODArray() |
| 20 | : ptr_() {} |
| 21 | explicit PODArray(int len) |
| 22 | : ptr_(std::allocator<T>().allocate(len), Deleter(len)) {} |
| 23 | |
| 24 | T* data() const { |
| 25 | return ptr_.get(); |
| 26 | } |
| 27 | |
| 28 | int size() const { |
| 29 | return ptr_.get_deleter().len_; |
| 30 | } |
| 31 | |
| 32 | T& operator[](int pos) const { |
| 33 | return ptr_[pos]; |
| 34 | } |
| 35 | |
| 36 | private: |
| 37 | struct Deleter { |
| 38 | Deleter() |
| 39 | : len_(0) {} |
| 40 | explicit Deleter(int len) |
| 41 | : len_(len) {} |
| 42 | |
| 43 | void operator()(T* ptr) const { |
| 44 | std::allocator<T>().deallocate(ptr, len_); |
| 45 | } |
| 46 | |
| 47 | int len_; |
| 48 | }; |
| 49 | |
| 50 | std::unique_ptr<T[], Deleter> ptr_; |
| 51 | }; |
| 52 | |
| 53 | } // namespace re2 |
| 54 | |
| 55 | #endif // UTIL_POD_ARRAY_H_ |
| 56 | |