1 /* 2 * Copyright 2020 The libgav1 Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef LIBGAV1_SRC_UTILS_DYNAMIC_BUFFER_H_ 18 #define LIBGAV1_SRC_UTILS_DYNAMIC_BUFFER_H_ 19 20 #include <memory> 21 #include <new> 22 23 #include "src/utils/memory.h" 24 25 namespace libgav1 { 26 27 template <typename T> 28 class DynamicBuffer { 29 public: get()30 T* get() { return buffer_.get(); } get()31 const T* get() const { return buffer_.get(); } 32 33 // Resizes the buffer so that it can hold at least |size| elements. Existing 34 // contents will be destroyed when resizing to a larger size. 35 // 36 // Returns true on success. If Resize() returns false, then subsequent calls 37 // to get() will return nullptr. Resize(size_t size)38 bool Resize(size_t size) { 39 if (size <= size_) return true; 40 buffer_.reset(new (std::nothrow) T[size]); 41 if (buffer_ == nullptr) { 42 size_ = 0; 43 return false; 44 } 45 size_ = size; 46 return true; 47 } 48 size()49 size_t size() const { return size_; } 50 51 private: 52 std::unique_ptr<T[]> buffer_; 53 size_t size_ = 0; 54 }; 55 56 template <typename T, int alignment> 57 class AlignedDynamicBuffer { 58 public: get()59 T* get() { return buffer_.get(); } 60 61 // Resizes the buffer so that it can hold at least |size| elements. Existing 62 // contents will be destroyed when resizing to a larger size. 63 // 64 // Returns true on success. If Resize() returns false, then subsequent calls 65 // to get() will return nullptr. Resize(size_t size)66 bool Resize(size_t size) { 67 if (size <= size_) return true; 68 buffer_ = MakeAlignedUniquePtr<T>(alignment, size); 69 if (buffer_ == nullptr) { 70 size_ = 0; 71 return false; 72 } 73 size_ = size; 74 return true; 75 } 76 77 private: 78 AlignedUniquePtr<T> buffer_; 79 size_t size_ = 0; 80 }; 81 82 } // namespace libgav1 83 84 #endif // LIBGAV1_SRC_UTILS_DYNAMIC_BUFFER_H_ 85