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 <cstddef> 21 #include <memory> 22 #include <new> 23 24 #include "src/utils/memory.h" 25 26 namespace libgav1 { 27 28 template <typename T> 29 class DynamicBuffer { 30 public: get()31 T* get() { return buffer_.get(); } get()32 const T* get() const { return buffer_.get(); } 33 34 // Resizes the buffer so that it can hold at least |size| elements. Existing 35 // contents will be destroyed when resizing to a larger size. 36 // 37 // Returns true on success. If Resize() returns false, then subsequent calls 38 // to get() will return nullptr. Resize(size_t size)39 bool Resize(size_t size) { 40 if (size <= size_) return true; 41 buffer_.reset(new (std::nothrow) T[size]); 42 if (buffer_ == nullptr) { 43 size_ = 0; 44 return false; 45 } 46 size_ = size; 47 return true; 48 } 49 size()50 size_t size() const { return size_; } 51 52 private: 53 std::unique_ptr<T[]> buffer_; 54 size_t size_ = 0; 55 }; 56 57 template <typename T, int alignment> 58 class AlignedDynamicBuffer { 59 public: get()60 T* get() { return buffer_.get(); } 61 62 // Resizes the buffer so that it can hold at least |size| elements. Existing 63 // contents will be destroyed when resizing to a larger size. 64 // 65 // Returns true on success. If Resize() returns false, then subsequent calls 66 // to get() will return nullptr. Resize(size_t size)67 bool Resize(size_t size) { 68 if (size <= size_) return true; 69 buffer_ = MakeAlignedUniquePtr<T>(alignment, size); 70 if (buffer_ == nullptr) { 71 size_ = 0; 72 return false; 73 } 74 size_ = size; 75 return true; 76 } 77 78 private: 79 AlignedUniquePtr<T> buffer_; 80 size_t size_ = 0; 81 }; 82 83 } // namespace libgav1 84 85 #endif // LIBGAV1_SRC_UTILS_DYNAMIC_BUFFER_H_ 86